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

sentry-example-page

+ +

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

+ + + + {hasSentError ? ( +

Error sent to Sentry.

+ ) : !isConnected ? ( +
+

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

+
+ ) : ( +
+ )} + +
+
+ + +
+ ); +} +`; +} + +export function getSentryExamplePagesDirApiRoute({ + isTypeScript, +}: { + isTypeScript: boolean; +}) { + const sentryImport = `import * as Sentry from "@sentry/nextjs"; + +`; + + const loggerCall = ` Sentry.logger.info("Sentry example API called"); +`; + + return `${sentryImport}// Custom error class for Sentry testing +class SentryExampleAPIError extends Error { + constructor(message${isTypeScript ? ": string | undefined" : ""}) { + super(message); + this.name = "SentryExampleAPIError"; + } +} +// A faulty API route to test Sentry's error monitoring +export default function handler(_req, res) { +${loggerCall}throw new SentryExampleAPIError("This error is raised on the backend called by the example page."); +res.status(200).json({ name: "John Doe" }); +} +`; +} + +export type ExampleApiRouteDynamicStrategy = "force-dynamic" | "connection"; + +export function getSentryExampleAppDirApiRoute({ + isTypeScript, + dynamicStrategy, +}: { + isTypeScript: boolean; + /** + * How the route opts out of static rendering so the throwing handler runs at + * request time instead of during the build: + * - `force-dynamic`: `export const dynamic = "force-dynamic"`. Needed on Next.js 14, + * where GET route handlers are cached by default. + * - `connection`: `await connection()` from `next/server` (Next.js 15+). Required on + * Next.js 16 with `cacheComponents`, which rejects route segment config. + */ + dynamicStrategy: ExampleApiRouteDynamicStrategy; +}) { + const useConnection = dynamicStrategy === "connection"; + + const sentryImport = `import * as Sentry from "@sentry/nextjs"; +${useConnection ? 'import { connection } from "next/server";\n' : ""}`; + + const forceDynamicExport = useConnection + ? "" + : `export const dynamic = "force-dynamic"; + +`; + + const connectionCall = useConnection + ? ` + // Opt out of prerendering so the error is thrown at request time + await connection();` + : ""; + + const loggerCall = ` + Sentry.logger.info("Sentry example API called");`; + + // Note: We intentionally don't have a return statement after throw - it would be unreachable code + // We also don't import NextResponse since we don't use it (Biome noUnusedImports rule) + return `${sentryImport}${forceDynamicExport}class SentryExampleAPIError extends Error { + constructor(message${isTypeScript ? ": string | undefined" : ""}) { + super(message); + this.name = "SentryExampleAPIError"; + } +} + +// A faulty API route to test Sentry's error monitoring +export ${ + useConnection ? "async " : "" + }function GET() {${connectionCall}${loggerCall} + throw new SentryExampleAPIError( + "This error is raised on the backend called by the example page.", + ); +} +`; +} + +export function getSentryDefaultUnderscoreErrorPage() { + return `import * as Sentry from "@sentry/nextjs"; +import Error from "next/error"; + +const CustomErrorComponent = (props) => { + return ; +}; + +CustomErrorComponent.getInitialProps = async (contextData) => { + // In case this is running in a serverless function, await this in order to give Sentry + // time to send the error before the lambda exits + await Sentry.captureUnderscoreErrorException(contextData); + + // This will contain the status code of the response + return Error.getInitialProps(contextData); +}; + +export default CustomErrorComponent; +`; +} + +export function getSimpleUnderscoreErrorCopyPasteSnippet() { + return ` +${chalk.green(`import * as Sentry from '@sentry/nextjs';`)} +${chalk.green(`import Error from "next/error";`)} + +${chalk.dim( + '// Replace "YourCustomErrorComponent" with your custom error component!', +)} +YourCustomErrorComponent.getInitialProps = async (${chalk.green( + "contextData", + )}) => { + ${chalk.green("await Sentry.captureUnderscoreErrorException(contextData);")} + + ${chalk.dim("// ...other getInitialProps code")} + + return Error.getInitialProps(contextData); +}; +`; +} + +export function getGenerateMetadataSnippet(isTs: boolean) { + return makeCodeSnippet(true, (unchanged, plus) => { + return plus(` + import * as Sentry from '@sentry/nextjs'; + ${isTs ? `import type { Metadata } from 'next';` : ""} + + ${unchanged( + '// Add or edit your "generateMetadata" to include the Sentry trace data:', + )} + export function generateMetadata()${isTs ? ": Metadata" : ""} { + return { + // ... your existing metadata + other: { + ...Sentry.getTraceData() + } + }; + } +`); + }); +} + +export function getFullUnderscoreErrorCopyPasteSnippet(isTs: boolean) { + return ` +import * as Sentry from '@sentry/nextjs';${ + isTs ? '\nimport type { NextPageContext } from "next";' : "" + } +import Error from "next/error"; + +${chalk.dim( + '// Replace "YourCustomErrorComponent" with your custom error component!', +)} +YourCustomErrorComponent.getInitialProps = async (contextData${ + isTs ? ": NextPageContext" : "" + }) => { + await Sentry.captureUnderscoreErrorException(contextData); + + return Error.getInitialProps(contextData); +}; +`; +} + +export function getInstrumentationHookContent( + instrumentationHookLocation: "src" | "root", +) { + return `import * as Sentry from "@sentry/nextjs"; + +export async function register() { + if (process.env.NEXT_RUNTIME === "nodejs") { + await import("${ + instrumentationHookLocation === "root" ? "." : ".." + }/sentry.server.config"); + } + + if (process.env.NEXT_RUNTIME === "edge") { + await import("${ + instrumentationHookLocation === "root" ? "." : ".." + }/sentry.edge.config"); + } +} + +export const onRequestError = Sentry.captureRequestError; +`; +} + +export function getInstrumentationHookCopyPasteSnippet( + instrumentationHookLocation: "src" | "root", +) { + return makeCodeSnippet(true, (unchanged, plus) => { + return unchanged(`${plus("import * as Sentry from '@sentry/nextjs';")} + +export ${plus("async")} function register() { + ${plus(`if (process.env.NEXT_RUNTIME === 'nodejs') { + await import('${ + instrumentationHookLocation === "root" ? "." : ".." + }/sentry.server.config'); + } + + if (process.env.NEXT_RUNTIME === 'edge') { + await import('${ + instrumentationHookLocation === "root" ? "." : ".." + }/sentry.edge.config'); + }`)} +} + +${plus("export const onRequestError = Sentry.captureRequestError;")} +`); + }); +} + +export function getInstrumentationClientHookCopyPasteSnippet( + dsn: string, + selectedFeaturesMap: { + replay: boolean; + performance: boolean; + }, + reduceDataCollection: boolean, + spotlight = false, +) { + return makeCodeSnippet(true, (_unchanged, plus) => { + return plus( + getInstrumentationClientFileContents( + dsn, + selectedFeaturesMap, + reduceDataCollection, + spotlight, + ), + ); + }); +} + +export function getSentryDefaultGlobalErrorPage(isTs: boolean) { + return isTs + ? `"use client"; + +import * as Sentry from "@sentry/nextjs"; +import NextError from "next/error"; +import { useEffect } from "react"; + +export default function GlobalError({ + error, +}: { + error: Error & { digest?: string }; +}) { + useEffect(() => { + Sentry.captureException(error); + }, [error]); + + return ( + + + {/* \`NextError\` is the default Next.js error page component. Its type + definition requires a \`statusCode\` prop. However, since the App Router + does not expose status codes for errors, we simply pass 0 to render a + generic error message. */} + + + + ); +} +` + : `"use client"; + +import * as Sentry from "@sentry/nextjs"; +import NextError from "next/error"; +import { useEffect } from "react"; + +export default function GlobalError({ error }) { + useEffect(() => { + Sentry.captureException(error); + }, [error]); + + return ( + + + {/* \`NextError\` is the default Next.js error page component. Its type + definition requires a \`statusCode\` prop. However, since the App Router + does not expose status codes for errors, we simply pass 0 to render a + generic error message. */} + + + + ); +} +`; +} + +export function getGlobalErrorCopyPasteSnippet(isTs: boolean) { + if (isTs) { + return `"use client"; + +${chalk.green('import * as Sentry from "@sentry/nextjs";')} +${chalk.green('import Error from "next/error";')} +${chalk.green('import { useEffect } from "react";')} + +export default function GlobalError(${chalk.green( + "{ error }: { error: Error }", + )}) { + ${chalk.green(`useEffect(() => { + Sentry.captureException(error); + }, [error]);`)} + + return ( + + + {/* Your Error component here... */} + + + ); +} +`; + } + return `"use client"; + +${chalk.green('import * as Sentry from "@sentry/nextjs";')} +${chalk.green('import Error from "next/error";')} +${chalk.green('import { useEffect } from "react";')} + +export default function GlobalError(${chalk.green("{ error }")}) { + ${chalk.green(`useEffect(() => { + Sentry.captureException(error); + }, [error]);`)} + + return ( + + + {/* Your Error component here... */} + + + ); +} +`; +} + +export const getRootLayout = ( + isTs: boolean, +) => `// This file was generated by the Sentry wizard because we couldn't find a root layout file. +// You can delete this file at any time. + +export const metadata = { + title: 'Sentry NextJS Example', + description: 'Generated by Sentry', +} + +export default function RootLayout({ + children, +}${ + isTs + ? `: { + children: React.ReactNode +}` + : "" +}) { + return ( + + {children} + + ) +} +`; + +export const getRootLayoutWithGenerateMetadata = ( + isTs: boolean, +) => `// This file was generated by the Sentry wizard because we couldn't find a root layout file. +import * as Sentry from '@sentry/nextjs'; +${isTs ? `import type { Metadata } from 'next';` : ""} + +export function generateMetadata()${isTs ? ": Metadata" : ""} { + return { + other: { + ...Sentry.getTraceData(), + } + } +}; + +export default function RootLayout({ + children, +}${ + isTs + ? `: { + children: React.ReactNode +}` + : "" +}) { + return ( + + {children} + + ) +} +`; diff --git a/packages/cli/src/lib/wizard/nextjs/utils.ts b/packages/cli/src/lib/wizard/nextjs/utils.ts new file mode 100644 index 0000000000..c99e6ecc25 --- /dev/null +++ b/packages/cli/src/lib/wizard/nextjs/utils.ts @@ -0,0 +1,182 @@ +/** + * Helpers of the Next.js wizard: SDK versions, project layout, and + * config-file detection. + */ + +import { existsSync, lstatSync } from "node:fs"; +import path from "node:path"; +import { lt, major, minVersion } from "semver"; +import { type ASTNode, builders, type ProxifiedModule } from "magicast"; +import { + SENTRY_NEXTJS_CONFIG_IMPORT_PATH, + SENTRY_NEXTJS_ROOT_IMPORT_PATH, + type ExampleApiRouteDynamicStrategy, +} from "./templates.js"; +import { debug } from "../utils/debug.js"; + +/** First `@sentry/nextjs` release that exposes `withSentryConfig` on the `/config` subpath. */ +export const MIN_SDK_VERSION_WITH_CONFIG_SUBPATH = "10.73.0"; + +/** + * Returns the module `withSentryConfig` should be imported from for the + * installed SDK version. The wizard installs `^11`, but a user can keep an + * older SDK by declining the update prompt. Those releases only expose + * `withSentryConfig` on the root export, so fall back to it there. Unknown or + * unparseable versions get the subpath, which is the only option on v11. + */ +export function getWithSentryConfigImportPath( + sdkVersion: string | undefined, +): string { + if (!sdkVersion) { + return SENTRY_NEXTJS_CONFIG_IMPORT_PATH; + } + + try { + const minVer = minVersion(sdkVersion); + if (minVer && lt(minVer, MIN_SDK_VERSION_WITH_CONFIG_SUBPATH)) { + return SENTRY_NEXTJS_ROOT_IMPORT_PATH; + } + } catch (error) { + debug(error); + // fall through + } + + return SENTRY_NEXTJS_CONFIG_IMPORT_PATH; +} + +/** Minimum Next.js major supported by the Sentry Next.js SDK (v11 dropped Next.js 13). */ +export const MIN_SUPPORTED_NEXTJS_MAJOR = 14; + +/** + * Returns `false` when the given Next.js version range is definitely below the + * minimum the SDK supports. Unknown or unparseable versions are treated as supported. + */ +export function isNextJsVersionSupported(version: string | undefined): boolean { + if (!version) { + return true; + } + + try { + const minVer = minVersion(version); + if (!minVer) { + return true; + } + return major(minVer) >= MIN_SUPPORTED_NEXTJS_MAJOR; + } catch (error) { + debug(error); + return true; + } +} + +/** + * Picks how the generated example API route opts out of static rendering. + * Next.js 14 caches GET route handlers by default, so the route needs + * `export const dynamic = "force-dynamic"` or the build evaluates (and fails on) + * the throwing handler. Next.js 15+ ships `connection()` from `next/server`, + * which also works on Next.js 16 with `cacheComponents`, where route segment + * config is rejected. Unknown versions keep the previous `force-dynamic` behavior. + */ +export function getExampleApiRouteDynamicStrategy( + version: string | undefined, +): ExampleApiRouteDynamicStrategy { + if (!version) { + return "force-dynamic"; + } + + try { + const minVer = minVersion(version); + if (!minVer) { + return "force-dynamic"; + } + return major(minVer) >= 15 ? "connection" : "force-dynamic"; + } catch (error) { + debug(error); + return "force-dynamic"; + } +} + +/** + * Adds `import { withSentryConfig } from ` to the module. + * If the module already imports `withSentryConfig` (e.g. from the root + * `@sentry/nextjs` export used by SDK v10 and earlier), the existing import is + * rewritten to the given path instead of adding a duplicate binding. + */ +export function addWithSentryConfigImport( + mod: ProxifiedModule, + importPath: string = SENTRY_NEXTJS_CONFIG_IMPORT_PATH, +): void { + mod.imports.$add({ + from: importPath, + imported: "withSentryConfig", + local: "withSentryConfig", + }); +} + +export function getNextJsVersionBucket(version: string | undefined) { + if (!version) { + return "none"; + } + + try { + const minVer = minVersion(version); + if (!minVer) { + return "invalid"; + } + const majorVersion = major(minVer); + if (majorVersion >= 11) { + return `${majorVersion}.x`; + } + return "<11.0.0"; + } catch (error) { + debug(error); + return "unknown"; + } +} + +export function getMaybeAppDirLocation() { + const maybeAppDirPath = path.join(process.cwd(), "app"); + const maybeSrcAppDirPath = path.join(process.cwd(), "src", "app"); + + return existsSync(maybeAppDirPath) && lstatSync(maybeAppDirPath).isDirectory() + ? ["app"] + : existsSync(maybeSrcAppDirPath) && + lstatSync(maybeSrcAppDirPath).isDirectory() + ? ["src", "app"] + : undefined; +} + +export function hasRootLayoutFile(appFolderPath: string) { + return ["jsx", "tsx", "js"].some((ext) => + existsSync(path.join(appFolderPath, `layout.${ext}`)), + ); +} + +/** + * Unwraps a withSentryConfig call expression using magicast. + */ +export function unwrapSentryConfigAst(astNode: ASTNode): ASTNode { + if ( + astNode.type === "CallExpression" && + astNode.callee.type === "Identifier" && + astNode.callee.name === "withSentryConfig" + ) { + // Return the first argument (the config being wrapped) + return astNode.arguments[0] ?? astNode; + } + + return astNode; +} + +/** + * Wraps a magicast module export with withSentryConfig using magicast + */ +export function wrapWithSentryConfig( + moduleExport: unknown, + optionsTemplate: string, +): ReturnType { + return builders.functionCall( + "withSentryConfig", + moduleExport, + builders.raw(optionsTemplate), + ); +} diff --git a/packages/cli/src/lib/wizard/run.ts b/packages/cli/src/lib/wizard/run.ts new file mode 100644 index 0000000000..8bd377980b --- /dev/null +++ b/packages/cli/src/lib/wizard/run.ts @@ -0,0 +1,128 @@ +/** + * Pick and run a setup wizard for `sentry wizard`. + * + * Each integration's flow lives in its own directory and loads with a + * dynamic `import()`, so a run loads only the flow it needs (and its heavy + * dependencies, such as magicast). + */ + +import { ValidationError } from "../errors.js"; +import { abortIfCancelled } from "./utils/clack/index.js"; +import { clack } from "./utils/clack/prompts.js"; +import { enableDebugLogs } from "./utils/debug.js"; +import type { WizardOptions } from "./utils/types.js"; +import { CLI_VERSION } from "../constants.js"; + +/** + * The integrations `sentry wizard -i` accepts, in the order the picker lists + * them. The ids are the ones `@sentry/wizard -i` took. + */ +export const WIZARD_INTEGRATIONS = [ + { id: "reactNative", label: "React Native" }, + { id: "flutter", label: "Flutter" }, + { id: "ios", label: "iOS" }, + { id: "appleSnapshots", label: "Apple Snapshots" }, + { id: "angular", label: "Angular" }, + { id: "android", label: "Android" }, + { id: "nextjs", label: "Next.js" }, + { id: "nuxt", label: "Nuxt" }, + { id: "remix", label: "Remix" }, + { id: "reactRouter", label: "React Router" }, + { id: "sveltekit", label: "SvelteKit" }, + { id: "cloudflare", label: "Cloudflare" }, + { id: "sourcemaps", label: "Configure Source Maps Upload" }, +] as const; + +/** An integration id `sentry wizard -i` accepts. */ +export type WizardIntegration = (typeof WIZARD_INTEGRATIONS)[number]["id"]; + +/** + * Every value `-i` accepts. The Cordova and Electron wizards of + * `@sentry/wizard` were retired; their setup guides are in the Sentry docs. + */ +export const INTEGRATION_IDS: readonly WizardIntegration[] = + WIZARD_INTEGRATIONS.map((integration) => integration.id); + +/** Runs the wizard of one integration. */ +type WizardRunner = (options: WizardOptions) => Promise; + +/** + * The flow of each integration. Integrations without one are still being + * moved over from sentry-wizard. + */ +const WIZARD_RUNNERS: Partial> = { + nextjs: async (options) => { + const { runNextjsWizard } = await import("./nextjs/nextjs-wizard.js"); + await runNextjsWizard(options); + }, +}; + +/** What `sentry wizard` passes to {@link runWizard}. */ +export type RunWizardArgs = { + /** `-i`: the integration to set up; prompts for one when unset. */ + integration?: string | undefined; + /** `--debug`: print the wizard's debug output. */ + debug: boolean; + /** The options every wizard flow takes. */ + wizardOptions: WizardOptions; +}; + +/** + * Run the wizard of `args.integration`, after asking for one when it is + * unset. + * + * @throws {ValidationError} For an unknown integration, or one that has no + * flow in this version yet + */ +export async function runWizard(args: RunWizardArgs): Promise { + if (args.debug) { + enableDebugLogs(); + } + + const integration = args.integration + ? toWizardIntegration(args.integration) + : await askForIntegration(); + + const runner = WIZARD_RUNNERS[integration]; + if (!runner) { + throw new ValidationError( + `The ${integration} wizard is not available in this version yet.`, + "integration", + ); + } + await runner(args.wizardOptions); +} + +/** + * `id` as one of {@link WIZARD_INTEGRATIONS}. `-i` already checks its + * value; `SENTRY_WIZARD_INTEGRATION` is checked here. + * + * @throws {ValidationError} When `id` names no integration + */ +function toWizardIntegration(id: string): WizardIntegration { + const match = WIZARD_INTEGRATIONS.find( + (integration) => integration.id === id, + ); + if (!match) { + throw new ValidationError( + `Unknown integration "${id}". Pick one of: ${INTEGRATION_IDS.join(", ")}.`, + "integration", + ); + } + return match.id; +} + +/** Ask which integration to set up, out of the ones that have a flow. */ +async function askForIntegration(): Promise { + clack.intro(`Sentry Wizard ${CLI_VERSION}`); + const integration = await abortIfCancelled( + clack.select({ + message: "What do you want to set up?", + options: WIZARD_INTEGRATIONS.filter(({ id }) => id in WIZARD_RUNNERS).map( + ({ id, label }) => ({ value: id, label }), + ), + }), + ); + clack.outro(`Starting ${integration} setup`); + return integration; +} diff --git a/packages/cli/src/lib/wizard/sourcemaps/ci.ts b/packages/cli/src/lib/wizard/sourcemaps/ci.ts new file mode 100644 index 0000000000..e725f44a51 --- /dev/null +++ b/packages/cli/src/lib/wizard/sourcemaps/ci.ts @@ -0,0 +1,130 @@ +/** + * Help the user make the source map upload auth token available in CI. + * + * Shared by the framework wizards and the source maps wizard. Ported from + * sentry-wizard's `src/sourcemaps/sourcemaps-wizard.ts`. + */ + +import chalk from "chalk"; +import { Sentry, traceStep } from "../telemetry.js"; +import { + abortIfCancelled, + SENTRY_CLI_RC_FILE, + SENTRY_DOT_ENV_FILE, +} from "../utils/clack/index.js"; +import { clack } from "../utils/clack/prompts.js"; +import type { WizardOptions } from "../utils/types.js"; + +/** Tools that upload with `sentry` commands and read `.sentryclirc`. */ +const CLI_BASED_FLOW_TOOLS: readonly string[] = [ + "sentry-cli", + "tsc", + "angular", + "create-react-app", +]; + +/** + * Ask whether the user builds in CI and, if so, show the auth token to set + * there. Skipped for partner flows (Vercel) that already set the token. + * + * @param selectedTool - The build tool the wizard configured, such as `nextjs` + * @param authToken - The token written to the local config file + * @param comingFrom - The partner the command came from (`--coming-from`) + */ +export async function setupCI( + selectedTool: string, + authToken: string, + comingFrom: WizardOptions["comingFrom"], +): Promise { + if (comingFrom === "vercel") { + clack.log.info( + "Sentry Vercel integration is already configured. Skipping CI setup.", + ); + Sentry.setTag("using-ci", true); + } else { + await traceStep("configure-ci", () => configureCI(selectedTool, authToken)); + } +} + +/** Ask about CI and show the auth token to set there. */ +async function configureCI( + selectedTool: string, + authToken: string, +): Promise { + const isUsingCI = await abortIfCancelled( + clack.select({ + message: `Are you using a CI/CD tool to build and deploy your application?`, + options: [ + { + label: "Yes", + hint: "I use a tool like GitHub Actions, GitLab, CircleCI, TravisCI, Jenkins, Vercel, ...", + value: true, + }, + { + label: "No", + hint: "I build and deploy my application manually", + value: false, + }, + ], + initialValue: true, + }), + ); + + Sentry.setTag("using-ci", isUsingCI); + + const authTokenFile = CLI_BASED_FLOW_TOOLS.includes(selectedTool) + ? SENTRY_CLI_RC_FILE + : SENTRY_DOT_ENV_FILE; + + if (!isUsingCI) { + clack.log.info( + `No Problem! Just make sure that the Sentry auth token from ${chalk.cyan( + authTokenFile, + )} is available whenever you build and deploy your app.`, + ); + return; + } + + await traceStep("ci-auth-token-setup", () => setupAuthTokenInCI(authToken)); +} + +/** Show the auth token to add to the CI environment. */ +async function setupAuthTokenInCI(authToken: string): Promise { + clack.log.step( + "Add the Sentry authentication token as an environment variable to your CI setup:", + ); + + // Printed outside clack's gutter so that it can be copied/pasted directly + clack.rawOutput( + chalk.greenBright(` +SENTRY_AUTH_TOKEN=${authToken} +`), + ); + + clack.log.warn( + chalk.yellow("DO NOT commit this auth token to your repository!"), + ); + + const addedEnvVarToCI = await abortIfCancelled( + clack.select({ + message: "Did you configure CI as shown above?", + options: [ + { label: "Yes, continue!", value: true }, + { + label: "I'll do it later...", + value: false, + hint: chalk.yellow( + "You need to set the auth token to upload source maps in CI", + ), + }, + ], + initialValue: true, + }), + ); + + Sentry.setTag("added-env-var-to-ci", addedEnvVarToCI); + + if (!addedEnvVarToCI) { + clack.log.info("Don't forget! :)"); + } +} diff --git a/packages/cli/src/lib/wizard/telemetry.ts b/packages/cli/src/lib/wizard/telemetry.ts new file mode 100644 index 0000000000..09a39e330d --- /dev/null +++ b/packages/cli/src/lib/wizard/telemetry.ts @@ -0,0 +1,78 @@ +/** + * Telemetry for the setup wizards, recorded through the CLI's own Sentry + * client. + * + * `sentry wizard` already runs inside the CLI's command transaction, so a + * wizard flow is a `wizard.flow` span under it and each step a `wizard.step` + * span under that. Tags go on the same scope as the CLI's. Telemetry is off + * when the CLI's is (`SENTRY_CLI_NO_TELEMETRY`, `DO_NOT_TRACK`, or + * `sentry cli defaults telemetry off`), and `--disable-telemetry` turns it + * off for the run. + * + * The old wizard sent its telemetry to a project of its own; the tag names + * stay the same so its dashboards can move over. + */ + +import { type Span, setTag, setUser, startSpan } from "@sentry/node"; +import type { WizardOptions } from "./utils/types.js"; + +/** + * The scope helpers the wizard flows call as `Sentry.setTag(…)`. + * + * Report errors with `reportCliError` from `lib/error-reporting.js`, never a + * raw `captureException`. + */ +export const Sentry = { setTag, setUser }; + +/** + * Run a wizard flow in a `wizard.flow` span, tagged with the integration and + * which of `--org`, `--project`, and `--saas` were passed. + */ +export async function withTelemetry( + options: { + /** Unused: the CLI decides whether telemetry is on. Kept for the flows' call sites. */ + enabled?: boolean | undefined; + integration: string; + wizardOptions: WizardOptions; + }, + callback: () => F | Promise, +): Promise { + setTag("integration", options.integration); + setTag("args.project", Boolean(options.wizardOptions.projectSlug)); + setTag("args.org", Boolean(options.wizardOptions.orgSlug)); + setTag("args.saas", Boolean(options.wizardOptions.saas)); + + return await startSpan( + { + name: "sentry-wizard-execution", + op: "wizard.flow", + onlyIfParent: true, + }, + async () => { + updateProgress("start"); + const result = await callback(); + updateProgress("finished"); + return result; + }, + ); +} + +/** + * Run one wizard step in a `wizard.step` span and record it as the latest + * `progress` tag, so an aborted run shows where it stopped. + */ +export function traceStep( + step: string, + callback: (span: Span | undefined) => T, +): T { + updateProgress(step); + return startSpan( + { name: step, op: "wizard.step", onlyIfParent: true }, + (span) => callback(span), + ); +} + +/** Record `step` as the furthest step the wizard reached. */ +export function updateProgress(step: string): void { + setTag("progress", step); +} diff --git a/packages/cli/src/lib/wizard/utils/clack/index.ts b/packages/cli/src/lib/wizard/utils/clack/index.ts new file mode 100644 index 0000000000..fd740e4b6e --- /dev/null +++ b/packages/cli/src/lib/wizard/utils/clack/index.ts @@ -0,0 +1,1781 @@ +/** + * Shared prompts and project helpers of the setup wizards: aborting, git + * checks, package installs, Sentry CLI config files, formatters, and + * copy/paste instructions. Ported from sentry-wizard's `src/utils/clack`. + * + * The wizards never exit the process: {@link abort} and + * {@link abortIfCancelled} throw a {@link WizardExitError}, which + * `sentry wizard` turns into its exit code. + */ + +import { execSync, spawn } from "node:child_process"; +import { + accessSync, + existsSync, + promises, + readFileSync, + writeFileSync, +} from "node:fs"; +import { createRequire } from "node:module"; +import path, { basename, dirname, isAbsolute, join, relative } from "node:path"; +import chalk from "chalk"; +import { gte, minVersion, validRange } from "semver"; +import { sentry } from "../../../app-identity.js"; +import { CLI_VERSION } from "../../../constants.js"; +import { reportCliError } from "../../../error-reporting.js"; +import { WizardExitError } from "../../../errors.js"; +import { Sentry, traceStep } from "../../telemetry.js"; +import { debug } from "../debug.js"; +import { getUncommittedOrUntrackedFilePaths, isInGitRepo } from "../git.js"; +import { + getPackageVersion, + hasPackageInstalled, + type PackageDotJson, +} from "../package-json.js"; +import { + _detectPackageManger, + NPM, + type PackageManager, + packageManagers, +} from "../package-manager.js"; +import { fulfillsVersionRange } from "../semver.js"; +import type { Feature } from "../types.js"; +import { clack } from "./prompts.js"; + +export { getOrAskForProjectData } from "../project-data.js"; + +export const SENTRY_DOT_ENV_FILE = ".env.sentry-build-plugin"; +export const SENTRY_CLI_RC_FILE = ".sentryclirc"; +export const SENTRY_PROPERTIES_FILE = "sentry.properties"; + +export interface CliSetupConfig { + filename: string; + name: string; + gitignore: boolean; + + likelyAlreadyHasAuthToken(contents: string): boolean; + tokenContent(authToken: string): string; + + likelyAlreadyHasOrgAndProject(contents: string): boolean; + orgAndProjContent(org: string, project: string): string; + + likelyAlreadyHasUrl?(contents: string): boolean; + urlContent?(url: string): string; +} + +export interface CliSetupConfigContent { + authToken: string; + org?: string | undefined; + project?: string | undefined; + url?: string | undefined; +} + +export const rcCliSetupConfig: CliSetupConfig = { + filename: SENTRY_CLI_RC_FILE, + name: "source maps", + gitignore: true, + likelyAlreadyHasAuthToken: function (contents: string): boolean { + return !!(contents.includes("[auth]") && contents.match(/token=./g)); + }, + tokenContent: function (authToken: string): string { + return `[auth]\ntoken=${authToken}`; + }, + likelyAlreadyHasOrgAndProject: function (contents: string): boolean { + return !!( + contents.includes("[defaults]") && + contents.match(/org=./g) && + contents.match(/project=./g) + ); + }, + orgAndProjContent: function (org: string, project: string): string { + return `[defaults]\norg=${org}\nproject=${project}`; + }, +}; + +export const propertiesCliSetupConfig: Required = { + filename: SENTRY_PROPERTIES_FILE, + gitignore: true, + name: "debug files", + likelyAlreadyHasAuthToken(contents: string): boolean { + return !!contents.match(/auth\.token=./g); + }, + tokenContent(authToken: string): string { + return `auth.token=${authToken}`; + }, + likelyAlreadyHasOrgAndProject(contents: string): boolean { + return !!( + contents.match(/defaults\.org=./g) && + contents.match(/defaults\.project=./g) + ); + }, + orgAndProjContent(org: string, project: string): string { + return `defaults.org=${org}\ndefaults.project=${project}`; + }, + likelyAlreadyHasUrl(contents: string): boolean { + return !!contents.match(/defaults\.url=./g); + }, + urlContent(url: string): string { + return `defaults.url=${url}`; + }, +}; + +/** + * Stop the wizard with `message`. `status` 0 means the user chose to stop; + * anything else is a failure. Throws, so code after it never runs. + * + * @param message - Shown as the outro. Defaults to "Wizard setup cancelled." + * @param status - Exit code of `sentry wizard`. Defaults to 1. + */ +export async function abort(message?: string, status?: number): Promise { + clack.outro(message ?? "Wizard setup cancelled."); + Sentry.setTag("wizard.outcome", status === 0 ? "cancelled" : "aborted"); + throw new WizardExitError(status ?? 1); +} + +/** + * Resolve `input`, or stop the wizard with exit code 0 when the user + * cancelled the prompt (Ctrl+C). + */ +export async function abortIfCancelled( + input: T | Promise, +): Promise> { + const value = await input; + if (clack.isCancel(value)) { + clack.cancel("Wizard setup cancelled."); + Sentry.setTag("wizard.outcome", "cancelled"); + throw new WizardExitError(0); + } + return value as Exclude; +} + +/** Print the intro banner and welcome note of a wizard. */ +export function printWelcome(options: { + wizardName: string; + promoCode?: string | undefined; + message?: string | undefined; + telemetryEnabled?: boolean | undefined; +}): void { + clack.rawOutput(""); + clack.intro(chalk.inverse(` ${options.wizardName} `)); + + let welcomeText = + options.message || + `The ${options.wizardName} will help you set up Sentry for your application.\nThank you for using Sentry :)`; + + if (options.promoCode) { + welcomeText = `${welcomeText}\n\nUsing promo-code: ${options.promoCode}`; + } + + welcomeText = `${welcomeText}\n\nVersion: ${CLI_VERSION}`; + + if (options.telemetryEnabled) { + welcomeText = `${welcomeText} + +This wizard sends telemetry data and crash reports to Sentry. This helps us improve the Wizard. +You can turn this off at any time by running ${chalk.cyanBright( + sentry`wizard --disable-telemetry`, + )}.`; + } + + clack.note(welcomeText); +} + +/** + * Confirms if the user wants to continue with the wizard if the project is not a git repository. + * + * @param options.ignoreGitChanges If true, the wizard will not check if the project is a git repository. + * @param options.cwd The directory of the project. If undefined, the current process working directory will be used. + */ +export async function confirmContinueIfNoOrDirtyGitRepo({ + ignoreGitChanges, + cwd, + nonInteractive = false, +}: { + ignoreGitChanges: boolean | undefined; + cwd: string | undefined; + nonInteractive?: boolean | undefined; +}): Promise { + return await traceStep("check-git-status", async () => { + if ( + !isInGitRepo({ + cwd: cwd, + }) && + ignoreGitChanges !== true + ) { + if (nonInteractive) { + clack.log.error( + "Project is not inside a git repository in non-interactive mode. Run from a git repository or pass --ignore-git-changes to skip this safety check.", + ); + Sentry.setTag("continue-without-git", false); + await abort(); + } + + const continueWithoutGit = await abortIfCancelled( + clack.confirm({ + message: + "You are not inside a git repository. The wizard will create and update files. Do you want to continue anyway?", + }), + ); + + Sentry.setTag("continue-without-git", continueWithoutGit); + + if (!continueWithoutGit) { + await abort(undefined, 0); + } + // return early to avoid checking for uncommitted files + return; + } + + const uncommittedOrUntrackedFilePaths = getUncommittedOrUntrackedFilePaths({ + cwd: cwd, + }); + + if (uncommittedOrUntrackedFilePaths.length && ignoreGitChanges !== true) { + clack.log.warn( + `You have uncommitted or untracked files in your repo: + +${uncommittedOrUntrackedFilePaths.map((file) => `- ${file}`).join("\n")} + +The wizard will create and update files.`, + ); + + if (nonInteractive) { + clack.log.error( + "Project has uncommitted or untracked files in non-interactive mode. Commit or stash your changes, or pass --ignore-git-changes to skip this safety check.", + ); + Sentry.setTag("continue-with-dirty-repo", false); + await abort(); + } + + const continueWithDirtyRepo = await abortIfCancelled( + clack.confirm({ + message: "Do you want to continue anyway?", + }), + ); + + Sentry.setTag("continue-with-dirty-repo", continueWithDirtyRepo); + + if (!continueWithDirtyRepo) { + await abort(undefined, 0); + } + } + }); +} + +export async function askToInstallSentryCLI(): Promise { + return await abortIfCancelled( + clack.confirm({ + message: + "You don't have Sentry CLI installed. Do you want to install it?", + }), + ); +} + +export async function askForItemSelection( + items: string[], + message: string, +): Promise<{ value: string; index: number }> { + const selection: { value: string; index: number } | symbol = + await abortIfCancelled( + clack.select({ + maxItems: 12, + message: message, + options: items.map((item, index) => { + return { + value: { value: item, index: index }, + label: item, + }; + }), + }), + ); + + return selection; +} + +export async function confirmContinueIfPackageVersionNotSupported({ + packageId, + packageName, + packageVersion, + acceptableVersions, + note, +}: { + packageId: string; + packageName: string; + packageVersion: string; + acceptableVersions: string; + note?: string | undefined; +}): Promise { + return await traceStep(`check-package-version`, async () => { + Sentry.setTag(`${packageName.toLowerCase()}-version`, packageVersion); + const isSupportedVersion = fulfillsVersionRange({ + acceptableVersions, + version: packageVersion, + canBeLatest: true, + }); + + if (isSupportedVersion) { + Sentry.setTag(`${packageName.toLowerCase()}-supported`, true); + return; + } + + clack.log.warn( + `You have an unsupported version of ${packageName} installed: + + ${packageId}@${packageVersion}`, + ); + + clack.note( + note ?? + `Please upgrade to ${acceptableVersions} if you wish to use the Sentry Wizard.`, + ); + const continueWithUnsupportedVersion = await abortIfCancelled( + clack.confirm({ + message: "Do you want to continue anyway?", + }), + ); + Sentry.setTag( + `${packageName.toLowerCase()}-continue-with-unsupported-version`, + continueWithUnsupportedVersion, + ); + + if (!continueWithUnsupportedVersion) { + await abort(undefined, 0); + } + }); +} + +const JS_SDK_V11_MIGRATION_GUIDE_URL = + "https://docs.sentry.io/platforms/javascript/migration/v10-to-v11/"; + +/** Docs guide slugs of the SDKs that have a platform-specific migration guide. */ +const JS_SDK_V11_MIGRATION_GUIDE_SLUGS: Record = { + "@sentry/angular": "angular", + "@sentry/cloudflare": "cloudflare", + "@sentry/nextjs": "nextjs", + "@sentry/nuxt": "nuxt", + "@sentry/react-router": "react-router", + "@sentry/remix": "remix", + "@sentry/sveltekit": "sveltekit", +}; + +function getSdkV11MigrationGuideUrl(packageName: string): string { + const slug = JS_SDK_V11_MIGRATION_GUIDE_SLUGS[packageName]; + + return slug + ? `https://docs.sentry.io/platforms/javascript/guides/${slug}/migration/v10-to-v11/` + : JS_SDK_V11_MIGRATION_GUIDE_URL; +} + +/** + * Logs a link to the v10 to v11 migration guide if @param packageName is + * already installed at a version below v11. The wizard updates the SDK to v11, + * which contains breaking changes the user must apply to their code. + */ +export function printSdkV11MigrationGuideIfOutdated( + packageName: string, + packageJson: PackageDotJson, +): void { + const installedRange = getPackageVersion(packageName, packageJson); + const installedVersion = + installedRange && validRange(installedRange) + ? minVersion(installedRange) + : null; + + if (!installedVersion || gte(installedVersion, "11.0.0")) { + return; + } + + clack.log.warn( + `The wizard updates ${chalk.cyan( + packageName, + )} to version 11, which has ${chalk.bold("breaking changes")}. +Follow the migration guide to update your code: ${chalk.cyan( + getSdkV11MigrationGuideUrl(packageName), + )}`, + ); +} + +type InstallPackageOptions = { + /** The string that is passed to the package manager CLI as identifier to install (e.g. `@sentry/nextjs`, or `@sentry/nextjs@^8`) */ + packageName: string; + alreadyInstalled: boolean; + askBeforeUpdating?: boolean | undefined; + /** Overrides what is shown in the installation logs in place of the `packageName` option. Useful if the `packageName` is ugly (e.g. `@sentry/nextjs@^8`) */ + packageNameDisplayLabel?: string | undefined; + packageManager?: PackageManager | undefined; + /** Add force install flag to command to skip install precondition fails */ + forceInstall?: boolean | undefined; + /** Install as a dev dependency (@default: false) */ + devDependency?: boolean | undefined; +}; + +/** + * Installs or updates a package with the user's package manager. + * + * IMPORTANT: This function modifies the `package.json`! Be sure to re-read + * it if you make additional modifications to it after calling this function! + */ +export async function installPackage({ + packageName, + alreadyInstalled, + askBeforeUpdating = true, + packageNameDisplayLabel, + packageManager, + forceInstall = false, + devDependency = false, +}: InstallPackageOptions): Promise<{ packageManager?: PackageManager }> { + return await traceStep("install-package", async () => { + if (alreadyInstalled && askBeforeUpdating) { + const shouldUpdatePackage = await abortIfCancelled( + clack.confirm({ + message: `The ${chalk.bold.cyan( + packageNameDisplayLabel ?? packageName, + )} package is already installed. Do you want to update it to the latest version?`, + }), + ); + + if (!shouldUpdatePackage) { + return {}; + } + } + + const sdkInstallSpinner = clack.spinner(); + + const pkgManager = packageManager || (await getPackageManager()); + + if (pkgManager.name === "pnpm") { + clack.log.info( + `If you use pnpm 11, dependency build scripts require explicit approval. If installation fails with ${chalk.cyan( + "ERR_PNPM_IGNORED_BUILDS", + )}, review the pending packages, run ${chalk.cyan( + "pnpm approve-builds", + )}, and then rerun the wizard.`, + ); + } + + sdkInstallSpinner.start( + `${alreadyInstalled ? "Updating" : "Installing"} ${chalk.bold.cyan( + packageNameDisplayLabel ?? packageName, + )} with ${chalk.bold(pkgManager.label)}.`, + ); + + try { + await new Promise((resolve, reject) => { + const installArgs = [ + pkgManager.installCommand, + ...(devDependency ? ["-D"] : []), + pkgManager.registry + ? `${pkgManager.registry}:${packageName}` + : packageName, + ...(pkgManager.flags ? pkgManager.flags.split(" ") : []), + ...(forceInstall ? [pkgManager.forceInstallFlag] : []), + ]; + + const stringifiedInstallCmd = `${pkgManager.name} ${installArgs.join( + " ", + )}`; + + function handleErrorAndReject( + code: number | null, + cause: Error | string, + type: "spawn_error" | "process_error", + ) { + const output = [stdout, stderr].filter(Boolean).join("\n"); + // Write a log file so we can better troubleshoot issues + writeFileSync( + join( + process.cwd(), + `sentry-wizard-installation-error-${Date.now()}.log`, + ), + output, + { encoding: "utf8" }, + ); + + reportCliError(new Error("Package Installation Error"), { + tags: { + "install-command": stringifiedInstallCmd, + "package-manager": pkgManager.name, + "package-name": packageName, + "error-type": type, + }, + }); + + reject( + new Error( + `Installation command ${chalk.cyan( + stringifiedInstallCmd, + )} exited with code ${code ?? "null"}.`, + { + cause, + }, + ), + ); + } + + const installProcess = spawn(pkgManager.name, installArgs, { + shell: true, + // Ignoring Yarn `stdout` to prevent certain node + yarn v4 (observed on ubuntu + snap) + // combinations from crashing here. See #851 + stdio: [ + "pipe", + pkgManager.name === "yarn" ? "ignore" : "pipe", + "pipe", + ], + }); + + let stdout = ""; + let stderr = ""; + + // Defining data as unknown to avoid TS and ESLint errors because of `any` type + installProcess.stdout?.on("data", (data: unknown) => { + stdout += String(data); + }); + installProcess.stderr?.on("data", (data: unknown) => { + stderr += String(data); + }); + + installProcess.on("error", (err) => { + handleErrorAndReject(null, err, "spawn_error"); + }); + + installProcess.on("close", (code) => { + if (code !== 0) { + handleErrorAndReject(code, stderr, "process_error"); + } else { + resolve(); + } + }); + }); + } catch (e) { + sdkInstallSpinner.stop("Installation failed."); + clack.log.error( + `${chalk.red( + "Encountered the following error during installation:", + )}\n\n${String(e)}\n\n${chalk.dim( + "The wizard has created a `sentry-wizard-installation-error-*.log` file. Review it for sensitive information before sharing it. If you think this issue is caused by the Sentry wizard, create an issue on GitHub and include the redacted log file's content:\nhttps://github.com/getsentry/toolkit/issues", + )}`, + ); + await abort(); + } + + sdkInstallSpinner.stop( + `${alreadyInstalled ? "Updated" : "Installed"} ${chalk.bold.cyan( + packageNameDisplayLabel ?? packageName, + )} with ${chalk.bold(pkgManager.label)}.`, + ); + + return { packageManager: pkgManager }; + }); +} + +export async function addSentryCliConfig( + { authToken, org, project, url }: CliSetupConfigContent, + setupConfig: CliSetupConfig = rcCliSetupConfig, +): Promise { + return await traceStep("add-sentry-cli-config", async () => { + const configPath = join(process.cwd(), setupConfig.filename); + const configExists = existsSync(configPath); + + let configContents = + (configExists && readFileSync(configPath, "utf8")) || ""; + configContents = addAuthTokenToSentryConfig( + configContents, + authToken, + setupConfig, + ); + configContents = addOrgAndProjectToSentryConfig( + configContents, + org, + project, + setupConfig, + ); + configContents = addUrlToSentryConfig(configContents, url, setupConfig); + + try { + await promises.writeFile(configPath, configContents, { + encoding: "utf8", + flag: "w", + }); + clack.log.success( + `${configExists ? "Saved" : "Created"} ${chalk.cyan( + setupConfig.filename, + )}.`, + ); + } catch { + clack.log.warning( + `Failed to add auth token to ${chalk.cyan( + setupConfig.filename, + )}. Uploading ${ + setupConfig.name + } during build will likely not work locally.`, + ); + } + + if (setupConfig.gitignore) { + await addCliConfigFileToGitIgnore(setupConfig.filename); + } else { + clack.log.warn( + chalk.yellow("DO NOT commit auth token to your repository!"), + ); + } + }); +} + +function addAuthTokenToSentryConfig( + configContents: string, + authToken: string | undefined, + setupConfig: CliSetupConfig, +): string { + if (!authToken) { + return configContents; + } + + if (setupConfig.likelyAlreadyHasAuthToken(configContents)) { + clack.log.warn( + `${chalk.cyan( + setupConfig.filename, + )} already has auth token. Will not add one.`, + ); + return configContents; + } + + const newContents = `${configContents}\n${setupConfig.tokenContent( + authToken, + )}\n`; + clack.log.success( + `Added auth token to ${chalk.cyan( + setupConfig.filename, + )} for you to test uploading ${setupConfig.name} locally.`, + ); + return newContents; +} + +function addOrgAndProjectToSentryConfig( + configContents: string, + org: string | undefined, + project: string | undefined, + setupConfig: CliSetupConfig, +): string { + if (!org || !project) { + return configContents; + } + + if (setupConfig.likelyAlreadyHasOrgAndProject(configContents)) { + clack.log.warn( + `${chalk.cyan( + setupConfig.filename, + )} already has org and project. Will not add them.`, + ); + return configContents; + } + + const newContents = `${configContents}\n${setupConfig.orgAndProjContent( + org, + project, + )}\n`; + clack.log.success( + `Added default org and project to ${chalk.cyan( + setupConfig.filename, + )} for you to test uploading ${setupConfig.name} locally.`, + ); + return newContents; +} + +function addUrlToSentryConfig( + configContents: string, + url: string | undefined, + setupConfig: CliSetupConfig, +): string { + if (!url || !setupConfig.urlContent || !setupConfig.likelyAlreadyHasUrl) { + return configContents; + } + + if (setupConfig.likelyAlreadyHasUrl(configContents)) { + clack.log.warn( + `${chalk.cyan(setupConfig.filename)} already has url. Will not add one.`, + ); + return configContents; + } + + const newContents = `${configContents}\n${setupConfig.urlContent(url)}\n`; + clack.log.success( + `Added default url to ${chalk.cyan( + setupConfig.filename, + )} for you to test uploading ${setupConfig.name} locally.`, + ); + return newContents; +} + +export async function addDotEnvSentryBuildPluginFile( + authToken: string, +): Promise { + const envVarContent = `# DO NOT commit this file to your repository! +# The SENTRY_AUTH_TOKEN variable is picked up by the Sentry Build Plugin. +# It's used for authentication when uploading source maps. +# You can also set this env variable in your own \`.env\` files and remove this file. +SENTRY_AUTH_TOKEN=${authToken} +`; + + const dotEnvFilePath = join(process.cwd(), SENTRY_DOT_ENV_FILE); + const dotEnvFileExists = existsSync(dotEnvFilePath); + + if (dotEnvFileExists) { + const dotEnvFileContent = readFileSync(dotEnvFilePath, "utf8"); + + const hasAuthToken = !!dotEnvFileContent.match( + /^\s*SENTRY_AUTH_TOKEN\s*=/g, + ); + + if (hasAuthToken) { + clack.log.warn( + `${chalk.bold.cyan( + SENTRY_DOT_ENV_FILE, + )} already has auth token. Will not add one.`, + ); + } else { + try { + await promises.writeFile( + dotEnvFilePath, + `${dotEnvFileContent}\n${envVarContent}`, + { + encoding: "utf8", + flag: "w", + }, + ); + clack.log.success( + `Added auth token to ${chalk.bold.cyan(SENTRY_DOT_ENV_FILE)}`, + ); + } catch { + clack.log.warning( + `Failed to add auth token to ${chalk.bold.cyan( + SENTRY_DOT_ENV_FILE, + )}. Uploading source maps during build will likely not work locally.`, + ); + } + } + } else { + try { + await promises.writeFile(dotEnvFilePath, envVarContent, { + encoding: "utf8", + flag: "w", + }); + clack.log.success( + `Created ${chalk.bold.cyan( + SENTRY_DOT_ENV_FILE, + )} with auth token for you to test source map uploading locally.`, + ); + } catch { + clack.log.warning( + `Failed to create ${chalk.bold.cyan( + SENTRY_DOT_ENV_FILE, + )} with auth token. Uploading source maps during build will likely not work locally.`, + ); + } + } + + await addCliConfigFileToGitIgnore(SENTRY_DOT_ENV_FILE); +} + +async function addCliConfigFileToGitIgnore(filename: string): Promise { + const gitignorePath = join(process.cwd(), ".gitignore"); + + try { + const gitignoreContent = await promises.readFile(gitignorePath, "utf8"); + if (gitignoreContent.split(/\r?\n/).includes(filename)) { + clack.log.info( + `${chalk.bold(".gitignore")} already has ${chalk.bold( + filename, + )}. Will not add it again.`, + ); + return; + } + + await promises.appendFile( + gitignorePath, + `\n# Sentry Config File\n${filename}\n`, + { encoding: "utf8" }, + ); + clack.log.success( + `Added ${chalk.cyan(filename)} to ${chalk.cyan(".gitignore")}.`, + ); + } catch { + clack.log.error( + `Failed adding ${chalk.cyan(filename)} to ${chalk.cyan( + ".gitignore", + )}. Please add it manually!`, + ); + } +} + +/** + * Returns the changed or untracked files for the formatter step, or null if not + * in a git repo or nothing changed. + */ +function getFormatterTargetFiles(): string[] | null { + if (!isInGitRepo({ cwd: undefined })) { + return null; + } + + const changedOrUntrackedFiles = + getUncommittedOrUntrackedFilePaths().filter(Boolean); + + return changedOrUntrackedFiles.length ? changedOrUntrackedFiles : null; +} + +/** Resolves a package's bin entry point from the target project, or null. */ +function resolveFormatterBinary( + packageName: string, + binName: string, +): string | null { + const requireFromProject = createRequire(join(process.cwd(), "package.json")); + + const packageJsonCandidates: string[] = []; + try { + packageJsonCandidates.push( + requireFromProject.resolve(`${packageName}/package.json`), + ); + } catch (error) { + debug(error); + // Package may not expose package.json via exports; fall through. + } + packageJsonCandidates.push( + join(process.cwd(), "node_modules", packageName, "package.json"), + ); + + for (const packageJsonPath of packageJsonCandidates) { + try { + const pkg = JSON.parse(readFileSync(packageJsonPath, "utf8")) as { + bin?: string | Record | undefined; + }; + const relativeBin = + typeof pkg.bin === "string" ? pkg.bin : pkg.bin?.[binName]; + if (relativeBin) { + return join(dirname(packageJsonPath), relativeBin); + } + } catch (error) { + debug(error); + // Try the next candidate. + } + } + + return null; +} + +/** + * Runs a formatter without passing file names through a shell (command + * injection) and with a `--` separator (option injection). POSIX runs `npx` + * directly; Windows resolves the bin and runs it via Node, since `npx.cmd` + * would otherwise need a shell. + * + * @param packageName The npm package that provides the formatter. + * @param binName The bin entry to run from that package (Windows only). + * @param subArgs The formatter flags and subcommands. + * @param files The file paths to format. + * @param options.ignoreExitCode When true, a non-zero exit or unresolved binary resolves instead of rejecting. + */ +function runFormatterCommand( + packageName: string, + binName: string, + subArgs: string[], + files: string[], + { ignoreExitCode }: { ignoreExitCode: boolean }, +): Promise { + let command: string; + let args: string[]; + + if (process.platform === "win32") { + const binPath = resolveFormatterBinary(packageName, binName); + if (!binPath) { + return ignoreExitCode + ? Promise.resolve() + : Promise.reject( + new Error(`Could not resolve the ${packageName} binary.`), + ); + } + command = process.execPath; + args = [binPath, ...subArgs, "--", ...files]; + } else { + command = "npx"; + args = [packageName, ...subArgs, "--", ...files]; + } + + return new Promise((resolve, reject) => { + const child = spawn(command, args, { + shell: false, + stdio: "ignore", + }); + + child.on("error", (err) => { + if (ignoreExitCode) { + resolve(); + } else { + reject(err); + } + }); + + child.on("close", (code) => { + if (code !== 0 && !ignoreExitCode) { + reject(new Error(`Formatter exited with code ${code ?? "null"}.`)); + } else { + resolve(); + } + }); + }); +} + +/** + * Runs available formatters (Prettier and/or Biome) on the changed or untracked files in the project. + * This function provides a unified interface for running multiple formatters with a single user prompt. + * + * @param _opts The directory of the project. If undefined, the current process working directory will be used. + */ +export async function runFormatters(_opts: { + cwd: string | undefined; +}): Promise { + return await traceStep("run-formatters", async () => { + const targetFiles = getFormatterTargetFiles(); + if (!targetFiles) { + return; + } + + const packageJson = await getPackageDotJson(); + const prettierInstalled = hasPackageInstalled("prettier", packageJson); + const biomeInstalled = hasPackageInstalled("@biomejs/biome", packageJson); + + Sentry.setTag("prettier-installed", prettierInstalled); + Sentry.setTag("biome-installed", biomeInstalled); + + if (!prettierInstalled && !biomeInstalled) { + return; + } + + // Determine prompt message based on what's installed + const formattersAvailable = []; + if (prettierInstalled) formattersAvailable.push("Prettier"); + if (biomeInstalled) formattersAvailable.push("Biome"); + + const message = + formattersAvailable.length === 1 + ? `Looks like you have ${formattersAvailable[0]} in your project. Do you want to run it on your files?` + : `Looks like you have ${formattersAvailable.join( + " and ", + )} in your project. Do you want to run them on your files?`; + + const shouldRun = await abortIfCancelled(clack.confirm({ message })); + + if (!shouldRun) { + return; + } + + const spinner = clack.spinner(); + spinner.start("Running formatters on your files."); + + try { + // Run Prettier first if installed (handles general formatting) + if (prettierInstalled) { + await runFormatterCommand( + "prettier", + "prettier", + ["--ignore-unknown", "--write"], + targetFiles, + { ignoreExitCode: false }, + ); + } + + // Run Biome if installed (handles linting + additional formatting) + if (biomeInstalled) { + // Format first + await runFormatterCommand( + "@biomejs/biome", + "biome", + ["format", "--write"], + targetFiles, + // Ignore errors, just continue + { ignoreExitCode: true }, + ); + + // Then lint with fixes (using --unsafe for auto-fixable issues) + // See: https://biomejs.dev/linter/#unsafe-fixes + // The --unsafe flag applies potentially behavior-changing fixes like removing unused imports. + // This is acceptable for wizard-generated code which may have fixable issues. + await runFormatterCommand( + "@biomejs/biome", + "biome", + ["check", "--write", "--unsafe"], + targetFiles, + // Ignore errors, Biome exits non-zero if there are remaining issues + { ignoreExitCode: true }, + ); + } + + spinner.stop("Formatters have processed your files."); + } catch (e) { + spinner.stop("Formatting encountered an issue."); + clack.log.warn( + "Formatting encountered an issue. There may be formatting or linting issues in your updated files.", + ); + } + }); +} + +/** + * Runs prettier on the changed or untracked files in the project. + * + * @param options.cwd The directory of the project. If undefined, the current process working directory will be used. + */ +export async function runPrettierIfInstalled(_opts: { + cwd: string | undefined; +}): Promise { + return await traceStep("run-prettier", async () => { + const changedOrUntrackedFiles = getFormatterTargetFiles(); + if (!changedOrUntrackedFiles) { + return; + } + + const packageJson = await getPackageDotJson(); + const prettierInstalled = hasPackageInstalled("prettier", packageJson); + + Sentry.setTag("prettier-installed", prettierInstalled); + + if (!prettierInstalled) { + return; + } + + // prompt the user if they want to run prettier + const shouldRunPrettier = await abortIfCancelled( + clack.confirm({ + message: + "Looks like you have Prettier in your project. Do you want to run it on your files?", + }), + ); + + if (!shouldRunPrettier) { + return; + } + + const prettierSpinner = clack.spinner(); + prettierSpinner.start("Running Prettier on your files."); + + try { + await runFormatterCommand( + "prettier", + "prettier", + ["--ignore-unknown", "--write"], + changedOrUntrackedFiles, + { ignoreExitCode: false }, + ); + } catch (e) { + prettierSpinner.stop("Prettier failed to run."); + clack.log.warn( + "Prettier failed to run. There may be formatting issues in your updated files.", + ); + return; + } + + prettierSpinner.stop("Prettier has formatted your files."); + }); +} + +/** + * Runs Biome on the changed or untracked files in the project. + * + * @param options.cwd The directory of the project. If undefined, the current process working directory will be used. + */ +export async function runBiomeIfInstalled(_opts: { + cwd: string | undefined; +}): Promise { + return await traceStep("run-biome", async () => { + const changedOrUntrackedFiles = getFormatterTargetFiles(); + if (!changedOrUntrackedFiles) { + return; + } + + const packageJson = await getPackageDotJson(); + const biomeInstalled = hasPackageInstalled("@biomejs/biome", packageJson); + + Sentry.setTag("biome-installed", biomeInstalled); + + if (!biomeInstalled) { + return; + } + + // prompt the user if they want to run biome + const shouldRunBiome = await abortIfCancelled( + clack.confirm({ + message: + "Looks like you have Biome in your project. Do you want to run it on your files?", + }), + ); + + if (!shouldRunBiome) { + return; + } + + const biomeSpinner = clack.spinner(); + biomeSpinner.start("Running Biome on your files."); + + try { + // Use biome format --write for formatting (always succeeds if it can format) + // Then biome check --write for lint fixes + // We ignore exit codes because Biome exits non-zero if there are unfixable issues + await runFormatterCommand( + "@biomejs/biome", + "biome", + ["format", "--write"], + changedOrUntrackedFiles, + // Ignore errors, just continue + { ignoreExitCode: true }, + ); + + await runFormatterCommand( + "@biomejs/biome", + "biome", + ["check", "--write", "--unsafe"], + changedOrUntrackedFiles, + // Ignore errors, Biome exits non-zero if there are remaining issues + { ignoreExitCode: true }, + ); + } catch (e) { + biomeSpinner.stop("Biome encountered an issue."); + clack.log.warn( + "Biome encountered an issue. There may be formatting or linting issues in your updated files.", + ); + return; + } + + biomeSpinner.stop("Biome has formatted your files."); + }); +} + +/** + * Checks if @param packageId is listed as a dependency in @param packageJson. + * If not, it will ask users if they want to continue without the package. + * + * Use this function to check if e.g. a the framework of the SDK is installed + * + * @param packageJson the package.json object + * @param packageId the npm name of the package + * @param packageName a human readable name of the package + */ +export async function ensurePackageIsInstalled( + packageJson: PackageDotJson, + packageId: string, + packageName: string, +): Promise { + return await traceStep("ensure-package-installed", async () => { + const installed = hasPackageInstalled(packageId, packageJson); + + Sentry.setTag(`${packageName.toLowerCase()}-installed`, installed); + + if (!installed) { + Sentry.setTag(`${packageName.toLowerCase()}-installed`, false); + const continueWithoutPackage = await abortIfCancelled( + clack.confirm({ + message: `${packageName} does not seem to be installed. Do you still want to continue?`, + initialValue: false, + }), + ); + + if (!continueWithoutPackage) { + await abort(undefined, 0); + } + } + }); +} + +export async function getPackageDotJson(): Promise { + const packageJsonFileContents = await promises + .readFile(join(process.cwd(), "package.json"), "utf8") + .catch(() => { + clack.log.error( + "Could not find package.json. Make sure to run the wizard in the root of your app!", + ); + return abort(); + }); + + let packageJson: PackageDotJson | undefined = undefined; + + try { + packageJson = JSON.parse(packageJsonFileContents); + } catch { + clack.log.error( + `Unable to parse your ${chalk.cyan( + "package.json", + )}. Make sure it has a valid format!`, + ); + + await abort(); + } + + return packageJson || {}; +} + +export async function updatePackageDotJson( + packageDotJson: PackageDotJson, +): Promise { + try { + await promises.writeFile( + join(process.cwd(), "package.json"), + // TODO: maybe figure out the original indentation + JSON.stringify(packageDotJson, null, 2), + { + encoding: "utf8", + flag: "w", + }, + ); + } catch { + clack.log.error(`Unable to update your ${chalk.cyan("package.json")}.`); + + await abort(); + } +} + +/** + * Use this function to get the used JS Package manager. + * + * This function: + * - attempts to auto-detect the used package manager and return it + * - if unsuccessful, returns the passed fallback package manager + * - if no fallback is passed, it asks the user to select a package manager + * + * The result is cached on the first invocation to avoid asking the user multiple times. + * + * @param fallback the package manager to use if auto-detection fails and you don't want to + * ask the user. This is useful in cases where asking users would be too intrusive/low in value + * and where it's okay to fall back to a default package manager. Use this with caution. + */ +export async function getPackageManager( + fallback?: PackageManager, +): Promise { + const globalWithSentryWizard: typeof global & { + __sentry_wizard_cached_package_manager?: PackageManager | undefined; + } = global; + + if (globalWithSentryWizard.__sentry_wizard_cached_package_manager) { + return globalWithSentryWizard.__sentry_wizard_cached_package_manager; + } + + const detectedPackageManager = _detectPackageManger(); + + if (detectedPackageManager) { + globalWithSentryWizard.__sentry_wizard_cached_package_manager = + detectedPackageManager; + return detectedPackageManager; + } + + if (fallback) { + // explicitly avoiding to cache the fallback in case this function + // gets called again without a fallback (or a different fallback) + // later on in the wizard flow. + return fallback; + } + + const selectedPackageManager: PackageManager | symbol = + await abortIfCancelled( + clack.select({ + message: "Please select your package manager.", + options: packageManagers.map((packageManager) => ({ + value: packageManager, + label: packageManager.label, + })), + }), + ); + + globalWithSentryWizard.__sentry_wizard_cached_package_manager = + selectedPackageManager; + + Sentry.setTag("package-manager", selectedPackageManager.name); + + return selectedPackageManager; +} + +export function isUsingTypeScript() { + try { + return existsSync(join(process.cwd(), "tsconfig.json")); + } catch (error) { + debug(error); + return false; + } +} + +/** + * Asks users if they have a config file for @param tool (e.g. Vite). + * If yes, asks users to specify the path to their config file. + * + * Use this helper function as a fallback mechanism if the lookup for + * a config file with its most usual location/name fails. + * + * @param toolName Name of the tool for which we're looking for the config file + * @param configFileName Name of the most common config file name (e.g. vite.config.js) + * + * @returns a user path to the config file or undefined if the user doesn't have a config file + */ +export async function askForToolConfigPath( + toolName: string, + configFileName: string, +): Promise { + const hasConfig = await abortIfCancelled( + clack.confirm({ + message: `Do you have a ${toolName} config file (e.g. ${chalk.cyan( + configFileName, + )})?`, + initialValue: true, + }), + ); + + if (!hasConfig) { + return undefined; + } + + return await abortIfCancelled( + clack.text({ + message: `Please enter the path to your ${toolName} config file:`, + placeholder: join(".", configFileName), + validate: (value) => { + if (!value) { + return "Please enter a path."; + } + + try { + accessSync(value); + } catch (error) { + debug(error); + return "Could not access the file at this path."; + } + return undefined; + }, + }), + ); +} + +type ShowCopyPasteInstructionsOptions = { codeSnippet: string } & ( + | { + filename: string; + hint?: string | undefined; + } + | { + instructions: string; + } +); + +/** + * Prints copy/paste-able instructions to the console. + * Afterwards asks the user if they added the code snippet to their file. + * + * While there's no point in providing a "no" answer here, it gives users time to fulfill the + * task before the wizard continues with additional steps. + * + * Use this function if you want to show users instructions on how to add/modify + * code in their file. This is helpful if automatic insertion failed or is not possible/feasible. + * + * @param filename the name of the file to which the code snippet should be applied. + * If a path is provided, only the filename will be used. + * + * @param codeSnippet the snippet to be printed. Use {@link makeCodeSnippet} to create the + * diff-like format for visually highlighting unchanged or modified lines of code. + * + * @param hint (optional) a hint to be printed after the main instruction to add + * the code from @param codeSnippet to their @param filename. + * + * More guidelines on copy/paste instructions: + * @see {@link https://develop.sentry.dev/sdk/setup-wizards/#copy--paste-snippets} + * + * TODO: refactor copy paste instructions across different wizards to use this function. + * this might require adding a custom message parameter to the function + */ +export async function showCopyPasteInstructions( + opts: ShowCopyPasteInstructionsOptions, +): Promise { + if ("instructions" in opts) { + clack.log.step(opts.instructions); + } else { + const defaultInstructions = `Add the following code to your ${chalk.cyan( + basename(opts.filename), + )} file:${opts.hint ? chalk.dim(` (${chalk.dim(opts.hint)})`) : ""}`; + + clack.log.step(defaultInstructions); + } + + // Padding the code snippet to be printed with a \n at the beginning and end + // This makes it easier to distinguish the snippet from the rest of the output + // Printed outside clack's gutter so that the code can be copied/pasted directly + clack.rawOutput(`\n${opts.codeSnippet}\n`); + + await abortIfCancelled( + clack.select({ + message: "Did you apply the snippet above?", + options: [{ label: "Yes, continue!", value: true }], + initialValue: true, + }), + ); +} + +/** + * Callback that exposes formatting helpers for a code snippet. + * @param unchanged - Formats text as old code. + * @param plus - Formats text as new code. + * @param minus - Formats text as removed code. + */ +type CodeSnippetFormatter = ( + unchanged: (txt: string) => string, + plus: (txt: string) => string, + minus: (txt: string) => string, +) => string; + +/** + * Crafts a code snippet that can be used to e.g. + * - print copy/paste instructions to the console + * - create a new config file. + * + * @param colors set this to true if you want the final snippet to be colored. + * This is useful for printing the snippet to the console as part of copy/paste instructions. + * + * @param callback the callback that returns the formatted code snippet. + * It exposes takes the helper functions for marking code as unchanged, new or removed. + * These functions no-op if no special formatting should be applied + * and otherwise apply the appropriate formatting/coloring. + * (@see {@link CodeSnippetFormatter}) + * + * @see {@link showCopyPasteInstructions} for the helper with which to display the snippet in the console. + * + * @returns a string containing the final, formatted code snippet. + */ +export function makeCodeSnippet( + colors: boolean, + callback: CodeSnippetFormatter, +): string { + const unchanged = (txt: string) => (colors ? chalk.grey(txt) : txt); + const plus = (txt: string) => (colors ? chalk.greenBright(txt) : txt); + const minus = (txt: string) => (colors ? chalk.redBright(txt) : txt); + + return callback(unchanged, plus, minus); +} + +/** + * Creates a new config file with the given @param filepath and @param codeSnippet. + * + * Use this function to create a new config file for users. This is useful + * when users answered that they don't yet have a config file for a tool. + * + * (This doesn't mean that they don't yet have some other way of configuring + * their tool but we can leave it up to them to figure out how to merge configs + * here.) + * + * @param filepath absolute path to the new config file + * @param codeSnippet the snippet to be inserted into the file + * @param moreInformation (optional) the message to be printed after the file was created + * For example, this can be a link to more information about configuring the tool. + * + * @returns true on success, false otherwise + */ +export async function createNewConfigFile( + filepath: string, + codeSnippet: string, + moreInformation?: string, +): Promise { + if (!isAbsolute(filepath)) { + debug(`createNewConfigFile: filepath is not absolute: ${filepath}`); + return false; + } + + const prettyFilename = chalk.cyan(relative(process.cwd(), filepath)); + + try { + await promises.writeFile(filepath, codeSnippet); + + clack.log.success(`Added new ${prettyFilename} file.`); + + if (moreInformation) { + clack.log.info(chalk.gray(moreInformation)); + } + + return true; + } catch (e) { + debug(e); + clack.log.warn( + `Could not create a new ${prettyFilename} file. Please create one manually and follow the instructions below.`, + ); + } + + return false; +} + +export async function askShouldCreateExamplePage( + customRoute?: string, +): Promise { + const route = chalk.cyan(customRoute ?? "/sentry-example-page"); + + const createExamplePage = await traceStep("ask-create-example-page", () => + abortIfCancelled( + clack.select({ + message: `Do you want to create an example page ("${route}") to test your Sentry setup?`, + initialValue: true, + options: [ + { + value: true, + label: "Yes", + hint: "Recommended - Check your git status before committing!", + }, + { value: false, label: "No" }, + ], + }), + ), + ); + + Sentry.setTag("create-example-page", createExamplePage); + return createExamplePage; +} + +export async function askShouldCreateExampleComponent(): Promise { + return await traceStep("ask-create-example-component", () => + abortIfCancelled( + clack.select({ + message: `Do you want to create an example component to test your Sentry setup?`, + options: [ + { + value: true, + label: "Yes", + hint: "Recommended - Check your git status before committing!", + }, + { value: false, label: "No" }, + ], + }), + ), + ); +} + +export async function featureSelectionPrompt>( + features: F, +): Promise> { + return await traceStep("feature-selection", async () => { + const selectedFeatures: Record = {}; + + for (const feature of features) { + const selected = await abortIfCancelled( + clack.select({ + message: feature.prompt, + initialValue: true, + options: [ + { + value: true, + label: "Yes", + ...(feature.enabledHint ? { hint: feature.enabledHint } : {}), + }, + { + value: false, + label: "No", + ...(feature.disabledHint ? { hint: feature.disabledHint } : {}), + }, + ], + }), + ); + + selectedFeatures[feature.id] = selected; + } + + return selectedFeatures; + }); +} + +export async function askShouldInstallPackage( + pkgName: string, +): Promise { + return await traceStep(`ask-install-package`, () => + abortIfCancelled( + clack.confirm({ + message: `Do you want to install ${chalk.cyan(pkgName)}?`, + }), + ), + ); +} + +export async function askShouldAddPackageOverride( + pkgName: string, + pkgVersion: string, +): Promise { + return await traceStep(`ask-add-package-override`, () => + abortIfCancelled( + clack.confirm({ + message: `Do you want to add an override for ${chalk.cyan( + pkgName, + )} version ${chalk.cyan(pkgVersion)}?`, + }), + ), + ); +} + +async function getBuildCommand(): Promise { + const packageDotJson = await getPackageDotJson(); + return typeof packageDotJson.scripts?.["build"] === "string" ? "build" : null; +} + +export function artifactsExist(relativePath: string): boolean { + return existsSync(path.join(process.cwd(), relativePath)); +} + +export async function askToRunBuildOrEnterPathOrProceed({ + relativeArtifactPath, +}: { + relativeArtifactPath: string; +}): Promise<{ validPath: boolean; relativeArtifactPath?: string }> { + const options: { label: string; value: string }[] = []; + + const buildCommand = await getBuildCommand(); + + if (buildCommand) { + options.push({ + label: "Let the wizard run the build command", + value: "run-build", + }); + } + + options.push( + { + label: "Enter a different path manually", + value: "manual", + }, + { + label: "Proceed anyway — I believe the path is correct", + value: "proceed", + }, + ); + + const whatToDo = await abortIfCancelled( + clack.select({ + message: `We couldn't find build artifacts at "${relativeArtifactPath}". What would you like to do?`, + options, + initialValue: buildCommand ? "run-build" : "manual", + }), + ); + + if (whatToDo === "proceed") { + return { + validPath: true, + }; + } + + if (whatToDo === "run-build" && buildCommand) { + const ranBuildAndCheckArtifacts = await runBuildAndCheckArtifacts( + buildCommand, + relativeArtifactPath, + ); + + if (!ranBuildAndCheckArtifacts.validPath) { + return await askToRunBuildOrEnterPathOrProceed({ relativeArtifactPath }); + } + + return ranBuildAndCheckArtifacts; + } + + return { + validPath: false, + }; +} + +function getPossibleBuildFolders(): string[] { + const commonBuildFolders = ["build", "dist", "out", ".next"]; + + return commonBuildFolders.filter((folder) => + existsSync(path.join(process.cwd(), folder)), + ); +} + +async function promptForAlternativeArtifactPath(): Promise { + const folders = getPossibleBuildFolders(); + + if (!folders.length) { + return undefined; + } + + if (folders.length === 1) { + const [onlyFolder] = folders; + + const confirmed = await abortIfCancelled( + clack.select({ + message: `Detected one possible build folder. Use "${onlyFolder}" as your build artifacts folder?`, + options: [ + { + value: true, + label: "Yes", + }, + { value: false, label: "No" }, + ], + }), + ); + + return confirmed ? onlyFolder : undefined; + } + + const selected = await abortIfCancelled( + clack.select({ + message: `Detected multiple possible build folders. Is one of these your build artifacts folder?`, + options: [ + ...folders.map((f) => ({ value: f, label: f })), + { value: false, label: "No" }, + ], + }), + ); + + if (selected) { + return String(selected); + } + + return undefined; +} + +async function runBuildCommand(buildCommand: string): Promise { + const packageManager = await getPackageManager(NPM); + const command = `${packageManager.runScriptCommand} ${buildCommand}`; + const spinner = clack.spinner(); + + spinner.start(`Running ${chalk.cyan(command)}...`); + try { + execSync(command, { + stdio: "inherit", + cwd: process.cwd(), + }); + spinner.stop("Build finished running."); + return true; + } catch (error) { + spinner.stop( + `Build failed: ${error instanceof Error ? error.message : String(error)}`, + ); + clack.log.error( + "Failed to run your build command. Please run it manually and try again.", + ); + return false; + } +} + +async function runBuildAndCheckArtifacts( + buildCommand: string, + relativeArtifactPath: string, +): Promise<{ validPath: boolean; relativeArtifactPath?: string }> { + const buildRan = await runBuildCommand(buildCommand); + + if (!buildRan) { + return { validPath: false }; + } + + const found = artifactsExist(relativeArtifactPath); + + if (found) { + clack.log.success("Build completed and build artifacts folder found!"); + return { validPath: true }; + } + + clack.log.warn( + `Build ran, but build artifacts folder still not found at ${relativeArtifactPath}.`, + ); + + const fallbackPath = await promptForAlternativeArtifactPath(); + + if (!fallbackPath) { + return { validPath: false }; + } + + return { + validPath: artifactsExist(fallbackPath), + relativeArtifactPath: fallbackPath, + }; +} diff --git a/packages/cli/src/lib/wizard/utils/clack/mcp-config.ts b/packages/cli/src/lib/wizard/utils/clack/mcp-config.ts new file mode 100644 index 0000000000..867c9c0140 --- /dev/null +++ b/packages/cli/src/lib/wizard/utils/clack/mcp-config.ts @@ -0,0 +1,639 @@ +/** + * Offer to add a project-scoped Sentry MCP server to the user's editors + * (Cursor, VS Code, Claude Code) at the end of a wizard run. + */ + +import { mkdirSync, promises } from "node:fs"; +import path from "node:path"; +import { spawn } from "node:child_process"; +import { Sentry } from "../../telemetry.js"; +import chalk from "chalk"; +import { clack } from "./prompts.js"; +import { abortIfCancelled, showCopyPasteInstructions } from "./index.js"; +import { debug } from "../debug.js"; + +const SENTRY_MCP_BASE_URL = "https://mcp.sentry.dev/mcp"; + +// Type definitions for MCP configurations +interface CursorMcpConfig { + mcpServers?: Record | undefined; +} + +interface VsCodeMcpConfig { + servers?: Record | undefined; +} + +interface ClaudeCodeMcpConfig { + mcpServers?: Record | undefined; +} + +interface OpenCodeMcpConfig { + $schema?: string | undefined; + mcp?: + | Record + | undefined; +} + +/** + * Constructs the MCP URL with optional org and project slugs + */ +function getMcpUrl(orgSlug?: string, projectSlug?: string): string { + if (orgSlug && projectSlug) { + return `${SENTRY_MCP_BASE_URL}/${orgSlug}/${projectSlug}`; + } + return SENTRY_MCP_BASE_URL; +} + +function ensureDir(dirpath: string): void { + mkdirSync(dirpath, { recursive: true }); +} + +async function readJsonIfExists(filepath: string): Promise { + try { + const txt = await promises.readFile(filepath, "utf8"); + return JSON.parse(txt) as unknown; + } catch (error) { + debug(error); + return null; + } +} + +async function writeJson(filepath: string, obj: unknown): Promise { + ensureDir(path.dirname(filepath)); + await promises.writeFile(filepath, JSON.stringify(obj, null, 2), "utf8"); +} + +function getCursorMcpJsonSnippet( + orgSlug?: string, + projectSlug?: string, +): string { + const obj = { + mcpServers: { + Sentry: { + url: getMcpUrl(orgSlug, projectSlug), + }, + }, + } as const; + return JSON.stringify(obj, null, 2); +} + +function getVsCodeMcpJsonSnippet( + orgSlug?: string, + projectSlug?: string, +): string { + const obj = { + servers: { + Sentry: { + url: getMcpUrl(orgSlug, projectSlug), + type: "http", + }, + }, + } as const; + return JSON.stringify(obj, null, 2); +} + +function getClaudeCodeMcpJsonSnippet( + orgSlug?: string, + projectSlug?: string, +): string { + const obj = { + mcpServers: { + Sentry: { + url: getMcpUrl(orgSlug, projectSlug), + }, + }, + } as const; + return JSON.stringify(obj, null, 2); +} + +function getJetBrainsMcpJsonSnippet( + orgSlug?: string, + projectSlug?: string, +): string { + const obj = { + mcpServers: { + Sentry: { + url: getMcpUrl(orgSlug, projectSlug), + }, + }, + } as const; + return JSON.stringify(obj, null, 2); +} + +function getOpenCodeMcpJsonSnippet( + orgSlug?: string, + projectSlug?: string, +): string { + const obj = { + $schema: "https://opencode.ai/config.json", + mcp: { + Sentry: { + type: "remote", + url: getMcpUrl(orgSlug, projectSlug), + oauth: {}, + }, + }, + } as const; + return JSON.stringify(obj, null, 2); +} + +function getGenericMcpJsonSnippet( + orgSlug?: string, + projectSlug?: string, +): string { + const obj = { + mcpServers: { + Sentry: { + url: getMcpUrl(orgSlug, projectSlug), + }, + }, + } as const; + return JSON.stringify(obj, null, 2); +} + +async function addCursorMcpConfig( + orgSlug?: string, + projectSlug?: string, +): Promise { + const file = path.join(process.cwd(), ".cursor", "mcp.json"); + const existing = await readJsonIfExists(file); + if (!existing) { + await writeJson( + file, + JSON.parse(getCursorMcpJsonSnippet(orgSlug, projectSlug)), + ); + clack.log.success( + chalk.cyan(path.join(".cursor", "mcp.json")) + " created.", + ); + return; + } + try { + const updated = { ...existing } as CursorMcpConfig; + updated.mcpServers = updated.mcpServers || {}; + updated.mcpServers["Sentry"] = { + url: getMcpUrl(orgSlug, projectSlug), + }; + await writeJson(file, updated); + clack.log.success("Updated .cursor/mcp.json"); + } catch { + throw new Error("Failed to update .cursor/mcp.json"); + } +} + +async function addVsCodeMcpConfig( + orgSlug?: string, + projectSlug?: string, +): Promise { + const file = path.join(process.cwd(), ".vscode", "mcp.json"); + const existing = await readJsonIfExists(file); + if (!existing) { + await writeJson( + file, + JSON.parse(getVsCodeMcpJsonSnippet(orgSlug, projectSlug)), + ); + clack.log.success( + chalk.cyan(path.join(".vscode", "mcp.json")) + " created.", + ); + return; + } + try { + const updated = { ...existing } as VsCodeMcpConfig; + updated.servers = updated.servers || {}; + updated.servers["Sentry"] = { + url: getMcpUrl(orgSlug, projectSlug), + type: "http", + }; + await writeJson(file, updated); + clack.log.success("Updated .vscode/mcp.json"); + } catch { + throw new Error("Failed to update .vscode/mcp.json"); + } +} + +async function addClaudeCodeMcpConfig( + orgSlug?: string, + projectSlug?: string, +): Promise { + const file = path.join(process.cwd(), ".mcp.json"); + const existing = await readJsonIfExists(file); + if (!existing) { + await writeJson( + file, + JSON.parse(getClaudeCodeMcpJsonSnippet(orgSlug, projectSlug)), + ); + clack.log.success(chalk.cyan(".mcp.json") + " created."); + return; + } + try { + const updated = { ...existing } as ClaudeCodeMcpConfig; + updated.mcpServers = updated.mcpServers || {}; + updated.mcpServers["Sentry"] = { + url: getMcpUrl(orgSlug, projectSlug), + }; + await writeJson(file, updated); + clack.log.success("Updated .mcp.json"); + } catch { + throw new Error("Failed to update .mcp.json"); + } +} + +async function addOpenCodeMcpConfig( + orgSlug?: string, + projectSlug?: string, +): Promise { + const file = path.join(process.cwd(), "opencode.json"); + const existing = await readJsonIfExists(file); + if (!existing) { + await writeJson( + file, + JSON.parse(getOpenCodeMcpJsonSnippet(orgSlug, projectSlug)), + ); + clack.log.success(chalk.cyan("opencode.json") + " created."); + return; + } + try { + const updated = { ...existing } as OpenCodeMcpConfig; + updated.$schema ||= "https://opencode.ai/config.json"; + updated.mcp = updated.mcp || {}; + updated.mcp["Sentry"] = { + type: "remote", + url: getMcpUrl(orgSlug, projectSlug), + oauth: {}, + }; + await writeJson(file, updated); + clack.log.success("Updated opencode.json"); + } catch { + throw new Error("Failed to update opencode.json"); + } +} + +/** + * Copies text to clipboard across different platforms + */ +async function copyToClipboard(text: string): Promise { + try { + const platform = process.platform; + let command: string; + + if (platform === "darwin") { + command = "pbcopy"; + } else if (platform === "win32") { + command = "clip"; + } else { + // Linux + command = "xclip -selection clipboard"; + } + + const proc = spawn(command, [], { shell: true }); + proc.stdin.write(text); + proc.stdin.end(); + + return await new Promise((resolve) => { + proc.on("close", (code) => { + resolve(code === 0); + }); + proc.on("error", () => { + resolve(false); + }); + }); + } catch (error) { + debug(error); + return false; + } +} + +/** + * Shows MCP configuration for JetBrains IDEs with copy-to-clipboard option + */ +async function showJetBrainsMcpConfig( + orgSlug?: string, + projectSlug?: string, +): Promise { + const configSnippet = getJetBrainsMcpJsonSnippet(orgSlug, projectSlug); + + clack.log.info( + chalk.cyan("For JetBrains IDEs (WebStorm, IntelliJ IDEA, PyCharm, etc.):"), + ); + clack.log.info( + chalk.dim( + "Add the following configuration to your IDE's MCP settings.\n" + + "See: https://www.jetbrains.com/help/webstorm/mcp-server.html", + ), + ); + + // Display the configuration + clack.rawOutput("\n" + chalk.green(configSnippet) + "\n"); + + // Ask if user wants to copy to clipboard + const shouldCopy: boolean = await abortIfCancelled( + clack.select({ + message: "Copy configuration to clipboard?", + options: [ + { label: "Yes", value: true }, + { label: "No", value: false }, + ], + initialValue: true, + }), + ); + + if (shouldCopy) { + const copied = await copyToClipboard(configSnippet); + + if (copied) { + clack.log.success("Configuration copied to clipboard!"); + Sentry.setTag("mcp-clipboard-copy", "success"); + } else { + clack.log.warn( + "Failed to copy to clipboard. Please copy the configuration above manually.", + ); + Sentry.setTag("mcp-clipboard-copy", "failed"); + } + } else { + Sentry.setTag("mcp-clipboard-copy", "declined"); + } + + clack.log.info( + chalk.dim( + "Note: You may need to restart your IDE for MCP changes to take effect.", + ), + ); +} + +/** + * Shows generic MCP configuration for unsupported IDEs with copy-to-clipboard option + */ +async function showGenericMcpConfig( + orgSlug?: string, + projectSlug?: string, +): Promise { + const configSnippet = getGenericMcpJsonSnippet(orgSlug, projectSlug); + + clack.log.info(chalk.cyan("Generic MCP configuration for your IDE:")); + clack.log.info( + chalk.dim( + "If your IDE supports MCP servers, you can use the following configuration.\n" + + "Please consult your IDE's documentation for how to add MCP server configurations.", + ), + ); + + // Display the configuration + clack.rawOutput("\n" + chalk.green(configSnippet) + "\n"); + + // Ask if user wants to copy to clipboard + const shouldCopy: boolean = await abortIfCancelled( + clack.select({ + message: "Copy configuration to clipboard?", + options: [ + { label: "Yes", value: true }, + { label: "No", value: false }, + ], + initialValue: true, + }), + ); + + if (shouldCopy) { + const copied = await copyToClipboard(configSnippet); + + if (copied) { + clack.log.success("Configuration copied to clipboard!"); + Sentry.setTag("mcp-clipboard-copy", "success"); + } else { + clack.log.warn( + "Failed to copy to clipboard. Please copy the configuration above manually.", + ); + Sentry.setTag("mcp-clipboard-copy", "failed"); + } + } else { + Sentry.setTag("mcp-clipboard-copy", "declined"); + } + + clack.log.info( + chalk.dim( + "Note: The exact configuration format may vary depending on your IDE.\n" + + "If your IDE doesn't support MCP yet, please check back later or open an issue at:\n" + + "https://github.com/getsentry/toolkit/issues", + ), + ); +} + +/** + * Explains what MCP is and its benefits for Sentry users + */ +async function explainMCP(): Promise { + clack.log.info(chalk.cyan("What is MCP (Model Context Protocol)?")); + + clack.log.info( + chalk.dim( + "MCP is a protocol that allows AI assistants in your IDE to interact with external tools and services.\n\n" + + "The Sentry MCP server enables AI assistants to:\n" + + " • Query and analyze your Sentry issues directly from your IDE\n" + + " • Get context about errors and performance problems\n" + + " • Help debug issues with production data insights\n" + + " • Suggest fixes based on real error patterns\n\n" + + "This makes it easier to fix bugs by bringing Sentry's insights directly into your development workflow.\n\n" + + "Learn more: " + + chalk.cyan("https://docs.sentry.io/product/sentry-mcp/"), + ), + ); + + // Ask again after explanation + const shouldAddAfterExplanation: boolean = await abortIfCancelled( + clack.select({ + message: "Would you like to configure MCP for your IDE now?", + options: [ + { label: "Yes", value: true }, + { label: "No", value: false, hint: "You can add it later anytime" }, + ], + initialValue: true, + }), + ); + + return shouldAddAfterExplanation; +} + +/** + * Offers to add a project-scoped MCP server configuration for the Sentry MCP. + * Supports Cursor, VS Code, and Claude Code. + * @param orgSlug - Optional organization slug to include in the MCP URL + * @param projectSlug - Optional project slug to include in the MCP URL + */ +export async function offerProjectScopedMcpConfig( + orgSlug?: string, + projectSlug?: string, +): Promise { + type InitialChoice = "yes" | "no" | "explain"; + + const initialChoice: InitialChoice = await abortIfCancelled( + clack.select({ + message: + "Optionally add a project-scoped MCP server configuration for the Sentry MCP?", + options: [ + { label: "Yes", value: "yes" }, + { label: "No", value: "no", hint: "You can add it later anytime" }, + { + label: "What is MCP?", + value: "explain", + hint: "Learn about MCP benefits", + }, + ], + initialValue: "yes", + }), + ); + + let shouldAdd: boolean; + + if (initialChoice === "explain") { + Sentry.setTag("mcp-choice", "explain"); + shouldAdd = await explainMCP(); + Sentry.setTag("mcp-configured-after-explain", shouldAdd); + } else { + shouldAdd = initialChoice === "yes"; + Sentry.setTag("mcp-choice", initialChoice); + } + + if (!shouldAdd) { + Sentry.setTag("mcp-configured", false); + return; + } + + Sentry.setTag("mcp-configured", true); + + type EditorChoice = + | "cursor" + | "vscode" + | "claudeCode" + | "openCode" + | "jetbrains" + | "other"; + const editors: EditorChoice[] = await abortIfCancelled( + clack.multiselect({ + message: "Which editor(s) do you want to configure?", + options: [ + { value: "cursor", label: "Cursor (project .cursor/mcp.json)" }, + { value: "vscode", label: "VS Code (project .vscode/mcp.json)" }, + { value: "claudeCode", label: "Claude Code (project .mcp.json)" }, + { value: "openCode", label: "OpenCode (project opencode.json)" }, + { + value: "jetbrains", + label: "JetBrains IDE (WebStorm, IntelliJ IDEA, PyCharm, etc.)", + hint: "Manual configuration required", + }, + { + value: "other", + label: "I use a different IDE", + hint: "We'll show you the configuration to copy", + }, + ], + required: false, + }), + ); + + // If no editors were selected, return early + if (editors.length === 0) { + clack.log.info("No editors selected. You can add MCP configuration later."); + Sentry.setTag("mcp-configured", false); + return; + } + + // Track number of editors selected + Sentry.setTag("mcp-editors-count", editors.length); + + // Configure each selected editor + for (const editor of editors) { + // Track which editor is being configured + Sentry.setTag("mcp-editor", editor); + + try { + switch (editor) { + case "cursor": + await addCursorMcpConfig(orgSlug, projectSlug); + clack.log.success( + "Added project-scoped Sentry MCP configuration for Cursor.", + ); + clack.log.info( + chalk.dim( + "Note: You may need to reload your editor for MCP changes to take effect.", + ), + ); + break; + case "vscode": + await addVsCodeMcpConfig(orgSlug, projectSlug); + clack.log.success( + "Added project-scoped Sentry MCP configuration for VS Code.", + ); + clack.log.info( + chalk.dim( + "Note: You may need to reload your editor for MCP changes to take effect.", + ), + ); + break; + case "claudeCode": + await addClaudeCodeMcpConfig(orgSlug, projectSlug); + clack.log.success( + "Added project-scoped Sentry MCP configuration for Claude Code.", + ); + clack.log.info( + chalk.dim( + "Note: You may need to reload your editor for MCP changes to take effect.", + ), + ); + break; + case "openCode": + await addOpenCodeMcpConfig(orgSlug, projectSlug); + clack.log.success( + "Added project-scoped Sentry MCP configuration for OpenCode.", + ); + clack.log.info( + chalk.dim( + "Note: You may need to restart OpenCode for MCP changes to take effect.", + ), + ); + break; + case "jetbrains": + await showJetBrainsMcpConfig(orgSlug, projectSlug); + Sentry.setTag("mcp-config-manual", true); + break; + case "other": + await showGenericMcpConfig(orgSlug, projectSlug); + Sentry.setTag("mcp-config-manual", true); + break; + } + Sentry.setTag(`mcp-config-${editor}-success`, true); + } catch (e) { + Sentry.setTag(`mcp-config-${editor}-success`, false); + Sentry.setTag("mcp-config-fallback", true); + clack.log.warn( + chalk.yellow( + `Failed to write MCP config for ${editor} automatically. Please copy/paste the snippet below into your project config file.`, + ), + ); + + // Fallback: show per-editor instructions + if (editor === "cursor") { + await showCopyPasteInstructions({ + filename: path.join(".cursor", "mcp.json"), + codeSnippet: getCursorMcpJsonSnippet(orgSlug, projectSlug), + hint: "create the file if it does not exist", + }); + } else if (editor === "vscode") { + await showCopyPasteInstructions({ + filename: path.join(".vscode", "mcp.json"), + codeSnippet: getVsCodeMcpJsonSnippet(orgSlug, projectSlug), + hint: "create the file if it does not exist", + }); + } else if (editor === "claudeCode") { + await showCopyPasteInstructions({ + filename: ".mcp.json", + codeSnippet: getClaudeCodeMcpJsonSnippet(orgSlug, projectSlug), + hint: "create the file if it does not exist", + }); + } else if (editor === "openCode") { + await showCopyPasteInstructions({ + filename: "opencode.json", + codeSnippet: getOpenCodeMcpJsonSnippet(orgSlug, projectSlug), + hint: "create the file if it does not exist", + }); + } + } + } +} diff --git a/packages/cli/src/lib/wizard/utils/clack/prompts.ts b/packages/cli/src/lib/wizard/utils/clack/prompts.ts new file mode 100644 index 0000000000..3e969a1c52 --- /dev/null +++ b/packages/cli/src/lib/wizard/utils/clack/prompts.ts @@ -0,0 +1,71 @@ +/** + * The `@clack/prompts` functions the setup wizards use, gathered on one + * object so the ported flows keep their `clack.log.info(…)` call sites. + * + * The wizards run only under `sentry wizard`, whose chunk loads on demand, so + * importing clack here does not reach other commands or the completion bundle. + * + * `rawOutput` prints text the user copies as-is (code snippets, tokens): + * outside clack's gutter, so nothing gets prefixed to the copied lines. + * + * Each member is a getter, so a test that mocks `@clack/prompts` with only + * the functions its code path calls (as the sentry-wizard tests do) still + * loads this module. + */ + +import { + cancel, + confirm, + intro, + isCancel, + log, + multiselect, + note, + outro, + select, + spinner, + text, +} from "@clack/prompts"; + +/** Print `value` to stdout on its own lines, outside clack's gutter. */ +function rawOutput(value: string): void { + process.stdout.write(`${value}\n`); +} + +/** The clack prompts and log helpers the wizards call. */ +export const clack = { + get cancel() { + return cancel; + }, + get confirm() { + return confirm; + }, + get intro() { + return intro; + }, + get isCancel() { + return isCancel; + }, + get log() { + return log; + }, + get multiselect() { + return multiselect; + }, + get note() { + return note; + }, + get outro() { + return outro; + }, + rawOutput, + get select() { + return select; + }, + get spinner() { + return spinner; + }, + get text() { + return text; + }, +}; diff --git a/packages/cli/src/lib/wizard/utils/data-collection.ts b/packages/cli/src/lib/wizard/utils/data-collection.ts new file mode 100644 index 0000000000..8c157c1cf7 --- /dev/null +++ b/packages/cli/src/lib/wizard/utils/data-collection.ts @@ -0,0 +1,122 @@ +/** + * Ask whether the SDK should collect less personal data, for the + * `dataCollection` option the wizards write into `Sentry.init()`. + */ + +import { clack } from "./clack/prompts.js"; +import { Sentry } from "../telemetry.js"; +import chalk from "chalk"; + +import { traceStep } from "../telemetry.js"; +import { abortIfCancelled } from "./clack/index.js"; +import { getMajorVersion } from "./semver.js"; + +export const DATA_COLLECTION_DOCS_URL = + "https://docs.sentry.io/platforms/javascript/configuration/options/#dataCollection"; + +/** + * Keys that commonly reveal user identity in HTTP headers, cookies, and URL + * query parameters (forwarding chains, IP addresses, user hints). + */ +const PII_KEY_DENYLIST = ["forwarded", "-ip", "remote-", "via", "-user"]; + +const PII_KEY_DENYLIST_SNIPPET = `[${PII_KEY_DENYLIST.map( + (key) => `"${key}"`, +).join(", ")}]`; + +/** + * `dataCollection` value the wizard writes when the user opts to reduce data + * collection. Kept as an object so magicast-based wizards can insert it as an + * AST node; `getDataCollectionSnippet` renders the same preset for + * template-string-based wizards. + */ +export const DATA_COLLECTION_PII_PRESET = { + userInfo: false, + graphQL: { document: false, variables: false }, + genAI: { inputs: false, outputs: false }, + databaseQueryData: false, + queues: false, + httpBodies: [], + httpHeaders: { deny: [...PII_KEY_DENYLIST] }, + cookies: { deny: [...PII_KEY_DENYLIST] }, + urlQueryParams: { deny: [...PII_KEY_DENYLIST] }, +}; + +export const DATA_COLLECTION_COMMENT_LINES = [ + "Turns off collection of data that could identify users. Adjust per category:", + DATA_COLLECTION_DOCS_URL, +]; + +/** + * Renders the PII preset (with its explanatory comment) as code to embed in a + * generated `Sentry.init` options object. Every line is prefixed with + * `indent`; the result ends without a trailing newline. + */ +export function getDataCollectionSnippet(indent = " "): string { + const lines = [ + ...DATA_COLLECTION_COMMENT_LINES.map((line) => `// ${line}`), + "dataCollection: {", + " userInfo: false,", + " graphQL: { document: false, variables: false },", + " genAI: { inputs: false, outputs: false },", + " databaseQueryData: false,", + " queues: false,", + " httpBodies: [],", + ` httpHeaders: { deny: ${PII_KEY_DENYLIST_SNIPPET} },`, + ` cookies: { deny: ${PII_KEY_DENYLIST_SNIPPET} },`, + ` urlQueryParams: { deny: ${PII_KEY_DENYLIST_SNIPPET} },`, + "},", + ]; + + return lines.map((line) => `${indent}${line}`).join("\n"); +} + +/** + * The `dataCollection` option only makes sense to offer from SDK v11 on, + * where the SDK collects rich context by default. Unknown or unparseable + * installed versions fall back to the major of the range the wizard installs. + */ +export function sdkSupportsDataCollection( + installedSdkVersion: string | undefined, + wizardInstallRange: string, +): boolean { + const sdkMajor = + getMajorVersion(installedSdkVersion) ?? + getMajorVersion(wizardInstallRange) ?? + 0; + + return sdkMajor >= 11; +} + +/** + * Asks whether the wizard should write the PII-reducing `dataCollection` + * preset. Call this only when `sdkSupportsDataCollection` returned `true`. + */ +export async function askShouldReduceDataCollection(): Promise { + return await traceStep("data-collection", async () => { + const reduceDataCollection: boolean = await abortIfCancelled( + clack.select({ + message: + "Sentry collects request data, user info, and other context by default. Do you want to reduce this to avoid sending personally identifiable information (PII)?\n" + + `More info: ${chalk.cyan(DATA_COLLECTION_DOCS_URL)}`, + initialValue: false, + options: [ + { + value: true, + label: "Yes", + hint: "Add a dataCollection config to Sentry.init() that turns off PII-heavy categories", + }, + { + value: false, + label: "No", + hint: "Keep the SDK defaults", + }, + ], + }), + ); + + Sentry.setTag("data-collection-reduced", reduceDataCollection); + + return reduceDataCollection; + }); +} diff --git a/packages/cli/src/lib/wizard/utils/debug.ts b/packages/cli/src/lib/wizard/utils/debug.ts new file mode 100644 index 0000000000..c8668c78ce --- /dev/null +++ b/packages/cli/src/lib/wizard/utils/debug.ts @@ -0,0 +1,32 @@ +/** + * Debug output of the setup wizards, shown with `sentry wizard --debug`. + */ + +import chalk from "chalk"; +import { clack } from "./clack/prompts.js"; + +let debugEnabled = false; + +/** Render one debug argument: strings as-is, errors with their stack. */ +function prepareMessage(msg: unknown): string { + if (typeof msg === "string") { + return msg; + } + if (msg instanceof Error) { + return msg.stack ?? msg.message; + } + return JSON.stringify(msg, null, "\t"); +} + +/** Log `args` in the wizard's output when `--debug` is on. */ +export function debug(...args: unknown[]): void { + if (!debugEnabled) { + return; + } + clack.log.info(chalk.dim(args.map((a) => prepareMessage(a)).join(" "))); +} + +/** Turn on {@link debug} output for the rest of the run. */ +export function enableDebugLogs(): void { + debugEnabled = true; +} diff --git a/packages/cli/src/lib/wizard/utils/git.ts b/packages/cli/src/lib/wizard/utils/git.ts new file mode 100644 index 0000000000..193d67460d --- /dev/null +++ b/packages/cli/src/lib/wizard/utils/git.ts @@ -0,0 +1,75 @@ +/** + * Git checks the wizards run before they change a project's files. + */ + +import { execSync } from "node:child_process"; +import { debug } from "./debug.js"; + +/** + * Checks if the current working directory is a git repository. + * + * @param opts.cwd The directory of the project. If undefined, the current process working directory will be used. + * + * @returns true if the current working directory is a git repository, false otherwise. + */ +export function isInGitRepo(opts: { cwd: string | undefined }) { + try { + execSync("git rev-parse --is-inside-work-tree", { + stdio: "ignore", + cwd: opts.cwd, + }); + return true; + } catch (error) { + debug(error); + return false; + } +} + +/** + * Returns the exact paths of uncommitted or untracked files. + * + * Uses `git status --porcelain=v1 -z` so paths are NUL-terminated and verbatim, + * preserving spaces and unusual characters. Pass results as argv entries to a + * non-shell child process; do not interpolate them into a shell string. + * + * @param opts.cwd The project directory. Defaults to the current working directory. + */ +export function getUncommittedOrUntrackedFilePaths(opts?: { + cwd: string | undefined; +}): string[] { + try { + const gitStatus = execSync("git status --porcelain=v1 -z", { + // we only care about stdout + stdio: ["ignore", "pipe", "ignore"], + cwd: opts?.cwd, + }).toString(); + + const fields = gitStatus.split("\0"); + const files: string[] = []; + + for (let i = 0; i < fields.length; i++) { + const entry = fields[i]; + if (!entry) { + continue; + } + + // Entry is `XY `. Renames/copies (R/C) store the source in the + // next field, which we skip. + const status = entry.slice(0, 2); + const filePath = entry.slice(3); + + if (status[0] === "R" || status[0] === "C") { + i++; + } + + if (filePath) { + files.push(filePath); + } + } + + return files; + } catch (error) { + debug(error); + return []; + } +} diff --git a/packages/cli/src/lib/wizard/utils/node-version.ts b/packages/cli/src/lib/wizard/utils/node-version.ts new file mode 100644 index 0000000000..723b7d17fe --- /dev/null +++ b/packages/cli/src/lib/wizard/utils/node-version.ts @@ -0,0 +1,50 @@ +/** + * Check the Node.js version a framework's SDK needs. + */ + +import { clack } from "./clack/prompts.js"; +import chalk from "chalk"; +import { coerce, satisfies } from "semver"; + +/** + * Node.js versions supported by version 11 of the Sentry JavaScript SDKs. + * See https://docs.sentry.io/platforms/javascript/migration/v10-to-v11/#nodejs + */ +export const NODE_VERSION_RANGE_FOR_SDK_V11 = + ">=20.19.0 <22.0.0 || >=22.12.0 <23.0.0 || >=23.2.0"; + +/** + * Returns `false` when the given Node.js version is definitely not supported by + * SDK v11. Unparseable versions are treated as supported. + */ +export function isNodeVersionSupportedBySdkV11( + version: string = process.version, +): boolean { + const parsed = coerce(version); + if (!parsed) { + return true; + } + return satisfies(parsed, NODE_VERSION_RANGE_FOR_SDK_V11); +} + +/** + * Warns when the wizard runs on a Node.js version that SDK v11 does not + * support. The wizard continues either way: the project may be built and run + * on a different Node.js than the one the wizard runs on. + */ +export function warnIfNodeVersionUnsupportedBySdkV11( + version: string = process.version, +): void { + if (isNodeVersionSupportedBySdkV11(version)) { + return; + } + + clack.log.warn( + `${chalk.yellow( + `Version 11 of the Sentry JavaScript SDKs requires Node.js 20.19.0 or newer (22.12.0 on Node.js 22, 23.2.0 on Node.js 23), but this wizard is running on Node.js ${chalk.bold( + version, + )}.`, + )} +The wizard will continue. Make sure your project builds and runs on a supported Node.js version before moving to SDK v11.`, + ); +} diff --git a/packages/cli/src/lib/wizard/utils/package-json.ts b/packages/cli/src/lib/wizard/utils/package-json.ts new file mode 100644 index 0000000000..1de6728d35 --- /dev/null +++ b/packages/cli/src/lib/wizard/utils/package-json.ts @@ -0,0 +1,186 @@ +/** + * Read dependencies from a project's `package.json`, including versions + * pnpm resolves from a `pnpm-workspace.yaml` catalog. + */ + +import { clack } from "./clack/prompts.js"; +import { existsSync, readFileSync } from "node:fs"; +import path from "node:path"; + +export type PackageDotJson = { + version?: string | undefined; + scripts?: Record; + dependencies?: Record | undefined; + devDependencies?: Record | undefined; + resolutions?: Record | undefined; + overrides?: Record | undefined; + pnpm?: { + overrides?: Record | undefined; + }; +}; + +type NpmPackage = { + name: string; + version: string; +}; + +type PnpmCatalogs = Record>; + +type PnpmWorkspace = { + catalog?: Record | undefined; + catalogs?: PnpmCatalogs | undefined; +}; + +/** Strip quotes and a trailing comment from a YAML scalar. */ +function yamlScalar(raw: string): string { + const value = raw.replace(/\s+#.*$/, "").trim(); + const quoted = /^(['"])(.*)\1$/.exec(value); + return quoted?.[2] ?? value; +} + +/** + * Read the `catalog` and `catalogs` sections of a `pnpm-workspace.yaml`. + * + * Only block mappings are read: `catalog:` with `name: version` entries, and + * `catalogs:` with a mapping of such catalogs. Everything else in the file is + * skipped, so the wizard needs no YAML parser. + */ +export function parsePnpmWorkspaceCatalogs(content: string): PnpmWorkspace { + const workspace: PnpmWorkspace = {}; + let section: "catalog" | "catalogs" | undefined; + let catalogName: string | undefined; + let namedIndent = -1; + + for (const line of content.split(/\r?\n/)) { + if (!line.trim() || line.trim().startsWith("#")) { + continue; + } + const indent = line.length - line.trimStart().length; + const entry = /^\s*(['"]?)([^'":]+)\1\s*:\s*(.*)$/.exec(line); + if (indent === 0) { + section = + entry?.[2] === "catalog" || entry?.[2] === "catalogs" + ? entry[2] + : undefined; + catalogName = undefined; + namedIndent = -1; + continue; + } + if (!(section && entry?.[2])) { + continue; + } + const key = entry[2].trim(); + const value = yamlScalar(entry[3] ?? ""); + if (section === "catalog") { + workspace.catalog = { ...workspace.catalog, [key]: value }; + } else if (namedIndent < 0 || indent <= namedIndent) { + namedIndent = indent; + catalogName = key; + } else if (catalogName) { + const catalogs = workspace.catalogs ?? {}; + catalogs[catalogName] = { ...catalogs[catalogName], [key]: value }; + workspace.catalogs = catalogs; + } + } + return workspace; +} + +/** + * Finds and parses the pnpm-workspace.yaml file to extract catalog definitions. + * Searches up to 10 parent directories from the current working directory. + * Returns null if the file doesn't exist or can't be parsed. + */ +function getPnpmWorkspace(): PnpmWorkspace | null { + let currentDir = process.cwd(); + const maxLevels = 10; + + for (let i = 0; i < maxLevels; i++) { + const workspaceFile = path.join(currentDir, "pnpm-workspace.yaml"); + + if (existsSync(workspaceFile)) { + const content = readFileSync(workspaceFile, "utf-8"); + + return parsePnpmWorkspaceCatalogs(content); + } + + const parentDir = path.dirname(currentDir); + + // Stop if we've reached the root directory + if (parentDir === currentDir) { + break; + } + + currentDir = parentDir; + } + + clack.log.error("Could not find pnpm-workspace.yaml."); + + return null; +} + +/** + * Resolves a catalog reference (e.g., "catalog:" or "catalog:sveltekit") to the actual version. + * - "catalog:" refers to the default catalog (workspace.catalog) + * - "catalog:customcatalog" refers to a named catalog (workspace.catalogs.customcatalog) + * Returns the actual version if found, or undefined if the catalog or package doesn't exist. + */ +function resolveCatalogVersion( + catalogRef: string, + packageName: string, +): string | undefined { + const catalogName = catalogRef.replace(/^catalog:/, ""); + const workspace = getPnpmWorkspace(); + + if (!workspace) { + return undefined; + } + + const catalog = + catalogName === "" ? workspace.catalog : workspace.catalogs?.[catalogName]; + + return catalog?.[packageName]; +} + +/** + * Checks if @param packageJson has any of the @param packageNamesList package names + * listed as a dependency or devDependency. + * If so, it returns the first package name that is found, including the + * version (range) specified in the package.json. + */ +export function findInstalledPackageFromList( + packageNamesList: string[], + packageJson: PackageDotJson, +): NpmPackage | undefined { + return packageNamesList + .map((packageName) => ({ + name: packageName, + version: getPackageVersion(packageName, packageJson), + })) + .find((sdkPackage): sdkPackage is NpmPackage => !!sdkPackage.version); +} + +export function hasPackageInstalled( + packageName: string, + packageJson: PackageDotJson, +): boolean { + return getPackageVersion(packageName, packageJson) !== undefined; +} + +export function getPackageVersion( + packageName: string, + packageJson: PackageDotJson, +): string | undefined { + const rawVersion = + packageJson.dependencies?.[packageName] || + packageJson.devDependencies?.[packageName]; + + if (!rawVersion) { + return undefined; + } + + const version = rawVersion.startsWith("catalog:") + ? resolveCatalogVersion(rawVersion, packageName) + : rawVersion; + + return version; +} diff --git a/packages/cli/src/lib/wizard/utils/package-manager.ts b/packages/cli/src/lib/wizard/utils/package-manager.ts new file mode 100644 index 0000000000..a772f768f6 --- /dev/null +++ b/packages/cli/src/lib/wizard/utils/package-manager.ts @@ -0,0 +1,239 @@ +/** + * Detect the project's package manager and the commands it runs. + */ + +import { existsSync, readFileSync } from "node:fs"; +import path from "node:path"; + +import { Sentry } from "../telemetry.js"; +import { traceStep } from "../telemetry.js"; +import { getPackageDotJson, updatePackageDotJson } from "./clack/index.js"; +import { debug } from "./debug.js"; + +export interface PackageManager { + name: string; + label: string; + installCommand: string; + buildCommand: string; + /* The command that the package manager uses to run a script from package.json */ + runScriptCommand: string; + flags: string; + forceInstallFlag: string; + registry?: string | undefined; + detect: () => boolean; + addOverride: (pkgName: string, pkgVersion: string) => Promise; +} + +export const BUN: PackageManager = { + name: "bun", + label: "Bun", + installCommand: "add", + buildCommand: "bun run build", + runScriptCommand: "bun run", + flags: "", + forceInstallFlag: "--force", + detect: () => + ["bun.lockb", "bun.lock"].some((lockFile) => { + try { + return existsSync(path.join(process.cwd(), lockFile)); + } catch (e) { + debug(e); + return false; + } + }), + addOverride: async (pkgName, pkgVersion): Promise => { + const packageDotJson = await getPackageDotJson(); + const overrides = packageDotJson.overrides || {}; + + await updatePackageDotJson({ + ...packageDotJson, + overrides: { + ...overrides, + [pkgName]: pkgVersion, + }, + }); + }, +}; +export const DENO: PackageManager = { + name: "deno", + label: "Deno", + installCommand: "install", + buildCommand: "deno task build", + runScriptCommand: "deno task", + flags: "", + forceInstallFlag: "--force", + registry: "npm", + detect: () => { + try { + return existsSync(path.join(process.cwd(), "deno.lock")); + } catch (e) { + debug(e); + return false; + } + }, + addOverride: async (pkgName, pkgVersion): Promise => { + const packageDotJson = await getPackageDotJson(); + const overrides = packageDotJson.overrides || {}; + + await updatePackageDotJson({ + ...packageDotJson, + overrides: { + ...overrides, + [pkgName]: pkgVersion, + }, + }); + }, +}; +export const YARN_V1: PackageManager = { + name: "yarn", + label: "Yarn V1", + installCommand: "add", + buildCommand: "yarn build", + runScriptCommand: "yarn", + flags: "--ignore-workspace-root-check", + forceInstallFlag: "--force", + detect: () => { + try { + return readFileSync(path.join(process.cwd(), "yarn.lock"), "utf-8") + .slice(0, 500) + .includes("yarn lockfile v1"); + } catch (e) { + debug(e); + return false; + } + }, + addOverride: async (pkgName, pkgVersion): Promise => { + const packageDotJson = await getPackageDotJson(); + const resolutions = packageDotJson.resolutions || {}; + + await updatePackageDotJson({ + ...packageDotJson, + resolutions: { + ...resolutions, + [pkgName]: pkgVersion, + }, + }); + }, +}; +/** YARN V2/3/4 */ +export const YARN_V2: PackageManager = { + name: "yarn", + label: "Yarn V2/3/4", + installCommand: "add", + buildCommand: "yarn build", + runScriptCommand: "yarn", + flags: "", + forceInstallFlag: "--force", + detect: () => { + try { + return readFileSync(path.join(process.cwd(), "yarn.lock"), "utf-8") + .slice(0, 500) + .includes("__metadata"); + } catch (e) { + debug(e); + return false; + } + }, + addOverride: async (pkgName, pkgVersion): Promise => { + const packageDotJson = await getPackageDotJson(); + const resolutions = packageDotJson.resolutions || {}; + + await updatePackageDotJson({ + ...packageDotJson, + resolutions: { + ...resolutions, + [pkgName]: pkgVersion, + }, + }); + }, +}; +export const PNPM: PackageManager = { + name: "pnpm", + label: "PNPM", + installCommand: "add", + buildCommand: "pnpm build", + runScriptCommand: "pnpm", + flags: "--ignore-workspace-root-check", + forceInstallFlag: "--force", + detect: () => { + try { + return existsSync(path.join(process.cwd(), "pnpm-lock.yaml")); + } catch (e) { + debug(e); + return false; + } + }, + addOverride: async (pkgName, pkgVersion): Promise => { + const packageDotJson = await getPackageDotJson(); + const pnpm = packageDotJson.pnpm || {}; + const overrides = pnpm.overrides || {}; + + await updatePackageDotJson({ + ...packageDotJson, + pnpm: { + ...pnpm, + overrides: { + ...overrides, + [pkgName]: pkgVersion, + }, + }, + }); + }, +}; +export const NPM: PackageManager = { + name: "npm", + label: "NPM", + installCommand: "install", + buildCommand: "npm run build", + runScriptCommand: "npm run", + flags: "", + forceInstallFlag: "--force", + detect: () => { + try { + return existsSync(path.join(process.cwd(), "package-lock.json")); + } catch (e) { + debug(e); + return false; + } + }, + addOverride: async (pkgName, pkgVersion): Promise => { + const packageDotJson = await getPackageDotJson(); + const overrides = packageDotJson.overrides || {}; + + await updatePackageDotJson({ + ...packageDotJson, + overrides: { + ...overrides, + [pkgName]: pkgVersion, + }, + }); + }, +}; + +export const packageManagers = [NPM, YARN_V1, YARN_V2, PNPM, BUN, DENO]; + +/** + * Exported only for testing. + * DO NOT call this function directly! + * Use `getPackageManger` instead. + */ +export function _detectPackageManger( + managers?: PackageManager[], +): PackageManager | null { + return traceStep("detect-package-manager", () => { + const foundPackageMangers = (managers ?? packageManagers).filter( + (packageManager) => packageManager.detect(), + ); + + // Only consider a package manager detected if we found exactly one. + // If we find more than one, we should not make any assumptions. + const [found] = foundPackageMangers; + if (found && foundPackageMangers.length === 1) { + Sentry.setTag("package-manager", found.name); + return found; + } + + Sentry.setTag("package-manager", "not-detected"); + return null; + }); +} diff --git a/packages/cli/src/lib/wizard/utils/project-data.ts b/packages/cli/src/lib/wizard/utils/project-data.ts new file mode 100644 index 0000000000..87718dcbb9 --- /dev/null +++ b/packages/cli/src/lib/wizard/utils/project-data.ts @@ -0,0 +1,479 @@ +/** + * Pick the Sentry project a setup wizard configures, with the CLI's login. + * + * The old wizard opened `account/settings/wizard//` in a browser and + * polled for the projects and an auth token. This module uses what the rest + * of the CLI uses instead: + * + * - The stored `sentry auth login` account, or a new device-flow login (or an + * agent handoff from `SENTRY_HANDOFF`) when there is none. A new login asks + * for `org:tokens` and `org:ci` too, so the auth token below needs no second + * approval. + * - The org from `--org`, the handoff, or a prompt; then the project from + * `--project` or a prompt that can also create one for the wizard's + * platform, like the old browser page could. + * - The project's DSN from its client keys. + * - A new org auth token for the build plugins and `sentry` commands that + * upload source maps and debug files. When the token can't be created, a + * placeholder goes in its place and the user is told where to make one. + */ + +import chalk from "chalk"; +import { completeAgentHandoff } from "../../agent-handoff.js"; +import { + getProject, + getProjectKeys, + listProjects, +} from "../../api/projects.js"; +import { createOrgAuthToken } from "../../api/org-auth-tokens.js"; +import { listOrganizations } from "../../api/organizations.js"; +import { + createProjectWithAutoTeam, + createProjectWithDsn, + MEMBER_PROJECT_CREATION_DISABLED_DETAIL, +} from "../../api/projects.js"; +import { assertAutoLoginHostTrusted } from "../../auto-auth.js"; +import { DEFAULT_SENTRY_URL } from "../../constants.js"; +import { getAuthConfig } from "../../db/auth.js"; +import { getEnv } from "../../env.js"; +import { ApiError } from "../../errors.js"; +import { runInteractiveLogin } from "../../interactive-login.js"; +import { logger } from "../../logger.js"; +import { OAUTH_SCOPES, resolveOAuthScopeString } from "../../oauth.js"; +import { resolveOrCreateTeam } from "../../resolve-team.js"; +import { ensureScopesForAction } from "../../scope-recovery.js"; +import { getSentryBaseUrl, isSentrySaasUrl } from "../../sentry-urls.js"; +import { registerLoginTrustAnchor } from "../../token-host.js"; +import { slugify } from "../../utils.js"; +import { sentry } from "../../app-identity.js"; +import type { + SentryOrganization, + SentryProject, +} from "../../../types/sentry.js"; +import { Sentry, traceStep } from "../telemetry.js"; +import { abort, abortIfCancelled } from "./clack/index.js"; +import { clack } from "./clack/prompts.js"; +import type { SentryProjectData, WizardOptions } from "./types.js"; + +const log = logger.withTag("wizard"); + +/** Written in place of an auth token that couldn't be created. */ +export const DUMMY_AUTH_TOKEN = "_YOUR_SENTRY_AUTH_TOKEN_"; + +/** Scopes an org auth token request needs from the CLI's OAuth grant. */ +const TOKEN_SCOPES = ["org:tokens", "org:read", "org:ci"] as const; + +/** `value` of the project picker's "create a new project" option. */ +const CREATE_PROJECT = Symbol("create-project"); + +/** Sentry platform identifiers of the wizards, used for new projects. */ +export type WizardPlatform = + | "javascript-angular" + | "javascript-nextjs" + | "javascript-nuxt" + | "javascript-react-router" + | "javascript-remix" + | "javascript-sveltekit" + | "node-cloudflare-workers" + | "apple-ios" + | "android" + | "react-native" + | "flutter"; + +/** The project a wizard sets up, or Spotlight mode, which needs none. */ +export type WizardProjectData = + | { + /** Web URL of the Sentry instance, ending in `/`. */ + sentryUrl: string; + selfHosted: boolean; + selectedProject: SentryProjectData; + /** Org auth token, or {@link DUMMY_AUTH_TOKEN}. */ + authToken: string; + spotlight: false; + } + | { + spotlight: true; + }; + +/** + * Get the Sentry project for a wizard run: the one passed in + * `options.preSelectedProject`, or one the user picks (or creates) after + * logging in. + * + * @param options - Wizard options (`--url`, `--saas`, `--org`, `--project`, …) + * @param platform - Platform for a project the user creates + */ +export async function getOrAskForProjectData( + options: WizardOptions, + platform?: WizardPlatform, +): Promise { + if (options.spotlight) { + clack.log.info( + `Spotlight mode enabled! Setting up for local development without Sentry account needed.\n + Note: Your app will only send data to the local Spotlight debugger, not to Sentry.`, + ); + return { spotlight: true }; + } + + if (options.preSelectedProject) { + return { + selfHosted: options.preSelectedProject.selfHosted, + sentryUrl: withTrailingSlash(options.url ?? DEFAULT_SENTRY_URL), + authToken: options.preSelectedProject.authToken, + selectedProject: options.preSelectedProject.project, + spotlight: false, + }; + } + + await traceStep("ask-self-hosted", () => + selectSentryUrl(options.url, options.saas), + ); + const handoffOrg = await traceStep("login", ensureLoggedIn); + + const sentryUrl = withTrailingSlash(getSentryBaseUrl()); + const selfHosted = !isSentrySaasUrl(sentryUrl); + Sentry.setTag("url", sentryUrl); + Sentry.setTag("self-hosted", selfHosted); + + const org = await traceStep("select-org", () => + selectOrganization(options.orgSlug ?? handoffOrg), + ); + const project = await traceStep("select-project", () => + selectProject(org, options.projectSlug, platform), + ); + Sentry.setTag("project", project.slug); + Sentry.setUser({ id: org.slug }); + + const dsn = await getDsn(org.slug, project.slug); + const authToken = await traceStep("create-auth-token", () => + createAuthToken(org.slug, sentryUrl), + ); + + return { + sentryUrl, + selfHosted, + authToken, + selectedProject: { + id: project.id, + slug: project.slug, + organization: { id: org.id, name: org.name, slug: org.slug }, + keys: [{ dsn: { public: dsn } }], + }, + spotlight: false, + }; +} + +/** + * Point this run at the Sentry instance the user chose: SaaS for `--saas`, + * the `--url` instance, or the answer to a SaaS/self-hosted prompt. Without + * any of them and with a stored login, the login's instance is used. + * + * An instance the user names here (flag or prompt) is trusted for login, the + * same as `sentry auth login --url`. + */ +async function selectSentryUrl( + urlFromArgs: string | undefined, + saas: boolean | undefined, +): Promise { + if (saas) { + useSentryUrl(DEFAULT_SENTRY_URL); + return; + } + if (!urlFromArgs && getAuthConfig()) { + return; + } + + if (!urlFromArgs) { + const choice = await abortIfCancelled( + clack.select({ + message: "Are you using Sentry SaaS or self-hosted Sentry?", + options: [ + { value: "saas", label: "Sentry SaaS (sentry.io)" }, + { + value: "self-hosted", + label: "Self-hosted/on-premise/single-tenant", + }, + ], + }), + ); + if (choice === "saas") { + useSentryUrl(DEFAULT_SENTRY_URL); + return; + } + } + + let pending = urlFromArgs; + for (;;) { + const url = + pending || + (await abortIfCancelled( + clack.text({ + message: `Please enter the URL of your ${ + urlFromArgs ? "" : "self-hosted " + }Sentry instance.`, + placeholder: "https://sentry.io/", + }), + )); + pending = undefined; + const origin = parseOrigin(url); + if (origin) { + useSentryUrl(origin); + return; + } + clack.log.error( + `Please enter a valid URL. (It should look something like "https://sentry.mydomain.com/", got ${url})`, + ); + } +} + +/** The origin of `url`, or `undefined` when it isn't an HTTP(S) URL. */ +function parseOrigin(url: string): string | undefined { + try { + const parsed = new URL(url); + return parsed.protocol === "https:" || parsed.protocol === "http:" + ? parsed.origin + : undefined; + } catch (error) { + log.debug(`Invalid Sentry URL ${url}`, error); + return; + } +} + +/** Send this run's API requests and login to `url`, trusted as user input. */ +function useSentryUrl(url: string): void { + const env = getEnv(); + env["SENTRY_HOST"] = url; + env["SENTRY_URL"] = url; + registerLoginTrustAnchor(url); +} + +/** + * Make sure the CLI has a login for the selected instance: claim the agent + * handoff in `SENTRY_HANDOFF`, keep a stored login, or run the device flow. + * + * @returns The org slug of a claimed handoff + */ +async function ensureLoggedIn(): Promise { + const handoffCode = getEnv()["SENTRY_HANDOFF"]?.trim(); + if (handoffCode) { + const handoff = await completeAgentHandoff(handoffCode); + Sentry.setTag("login-method", "handoff"); + return handoff.organizationSlug; + } + + if (getAuthConfig()) { + Sentry.setTag("login-method", "stored"); + return; + } + + assertAutoLoginHostTrusted(); + clack.log.info( + `${chalk.bold("Log in to Sentry")} to pick the project to set up. No account yet? You can sign up on the page that opens.`, + ); + const login = await runInteractiveLogin({ + scope: resolveOAuthScopeString({ + scopes: [...OAUTH_SCOPES, ...TOKEN_SCOPES], + }), + }); + if (!login) { + Sentry.setTag("login-method", "failed"); + return await abort( + `Please restart the wizard and log in to complete the setup. You can also log in first with ${chalk.cyan(sentry`auth login`)}.`, + ); + } + Sentry.setTag("login-method", "device-flow"); + return; +} + +/** + * The organization to set up: `slug` when given, the only one the user + * belongs to, or the one they pick. + */ +async function selectOrganization( + slug: string | undefined, +): Promise>> { + const orgs = await listOrganizations(); + if (slug) { + const match = orgs.find((org) => org.slug === slug); + if (match) { + clack.log.step(`Selected organization ${chalk.cyan(match.slug)}`); + return match; + } + clack.log.warn( + `Could not find an organization with the slug ${chalk.cyan(slug)}.`, + ); + } + + const [only] = orgs; + if (orgs.length === 1 && only) { + clack.log.step(`Selected organization ${chalk.cyan(only.slug)}`); + return only; + } + if (!only) { + Sentry.setTag("no-orgs-found", true); + return await abort( + "Your Sentry account has no organizations. Create one in Sentry and run the wizard again.", + ); + } + + return await abortIfCancelled( + clack.select({ + maxItems: 12, + message: "Select your Sentry organization.", + options: [...orgs] + .sort((a, b) => a.slug.localeCompare(b.slug)) + .map((org) => ({ value: org, label: org.slug, hint: org.name })), + }), + ); +} + +/** + * The project to set up: `slug` when given and found, else the one the user + * picks from the org's projects or creates. + */ +async function selectProject( + org: { slug: string }, + slug: string | undefined, + platform: WizardPlatform | undefined, +): Promise { + if (slug) { + try { + const project = await getProject(org.slug, slug); + clack.log.step( + `Selected project ${chalk.cyan(`${org.slug}/${project.slug}`)}`, + ); + return project; + } catch (error) { + if (!(error instanceof ApiError && error.status === 404)) { + throw error; + } + clack.log.warn("Could not find a project with the provided slugs."); + } + } + + const projects = (await listProjects(org.slug)).sort((a, b) => + a.slug.localeCompare(b.slug), + ); + const selection = await abortIfCancelled( + clack.select({ + maxItems: 12, + message: "Select your Sentry project.", + options: [ + { value: CREATE_PROJECT, label: "Create a new project" }, + ...projects.map((project) => ({ + value: project, + label: `${org.slug}/${project.slug}`, + ...(project.platform ? { hint: project.platform } : {}), + })), + ], + ...(projects.length > 0 ? { initialValue: projects[0] } : {}), + }), + ); + if (typeof selection !== "symbol") { + return selection; + } + Sentry.setTag("created-project", true); + return await createProject(org.slug, platform); +} + +/** + * Ask for a name and create a project for `platform` in `orgSlug`, on the + * team the CLI's `project create` would pick. Members who can't use that + * team get a project on their personal team. + */ +async function createProject( + orgSlug: string, + platform: WizardPlatform | undefined, +): Promise { + const name = await abortIfCancelled( + clack.text({ + message: "What should the new project be called?", + initialValue: slugify(process.cwd().split(/[\\/]/).pop() ?? ""), + validate: (value) => + value.trim() ? undefined : "Please enter a project name.", + }), + ); + const body = { name: name.trim(), ...(platform ? { platform } : {}) }; + + const spinner = clack.spinner(); + spinner.start("Creating your Sentry project"); + try { + const team = await resolveOrCreateTeam(orgSlug, { + usageHint: sentry`wizard --org `, + autoCreateSlug: slugify(body.name), + }); + const { project } = await createProjectWithDsn(orgSlug, team.slug, body); + spinner.stop(`Created project ${chalk.cyan(`${orgSlug}/${project.slug}`)}`); + return project; + } catch (error) { + if ( + !(error instanceof ApiError && error.status === 403) || + error.detail?.includes(MEMBER_PROJECT_CREATION_DISABLED_DETAIL) + ) { + spinner.stop("Could not create the project."); + throw error; + } + log.debug("403 on the team-based flow, using the org-scoped endpoint"); + const { project } = await createProjectWithAutoTeam(orgSlug, body); + spinner.stop(`Created project ${chalk.cyan(`${orgSlug}/${project.slug}`)}`); + return project; + } +} + +/** The public DSN of the project's first active client key. */ +async function getDsn(orgSlug: string, projectSlug: string): Promise { + const keys = await getProjectKeys(orgSlug, projectSlug); + const key = keys.find((k) => k.isActive) ?? keys[0]; + if (!key) { + return await abort( + `The project ${orgSlug}/${projectSlug} has no client keys (DSNs). Create one in its settings and run the wizard again.`, + ); + } + return key.dsn.public; +} + +/** + * Create an org auth token for uploading source maps and debug files, or + * return {@link DUMMY_AUTH_TOKEN} with instructions when that isn't possible + * (an old login without `org:tokens` in a non-interactive run, no permission, + * or a server that can't create tokens). + */ +async function createAuthToken( + orgSlug: string, + sentryUrl: string, +): Promise { + try { + const elevation = await ensureScopesForAction( + TOKEN_SCOPES, + "Creating an auth token for uploading source maps", + runInteractiveLogin, + ); + if (elevation !== "declined" && elevation !== "unavailable") { + const token = await createOrgAuthToken( + orgSlug, + `Sentry Wizard ${new Date().toISOString().slice(0, 10)}`, + ); + if (token.token) { + return token.token; + } + } + } catch (error) { + log.debug("Could not create an org auth token", error); + } + + Sentry.setTag("auth-token-created", false); + const settingsUrl = isSentrySaasUrl(sentryUrl) + ? `https://${orgSlug}.sentry.io/settings/auth-tokens/` + : `${sentryUrl}organizations/${orgSlug}/settings/auth-tokens/`; + clack.log.warn( + `Could not create an auth token for you. We'll add a placeholder (${chalk.cyan( + `"${DUMMY_AUTH_TOKEN}"`, + )}) for you to replace later.\nCreate your auth token here:\n${chalk.cyan(settingsUrl)}`, + ); + return DUMMY_AUTH_TOKEN; +} + +/** `url` with exactly one trailing `/`, the form the wizards expect. */ +function withTrailingSlash(url: string): string { + return url.endsWith("/") ? url : `${url}/`; +} diff --git a/packages/cli/src/lib/wizard/utils/semver.ts b/packages/cli/src/lib/wizard/utils/semver.ts new file mode 100644 index 0000000000..da0fe41424 --- /dev/null +++ b/packages/cli/src/lib/wizard/utils/semver.ts @@ -0,0 +1,65 @@ +/** + * Version range checks for installed SDK and framework versions. + */ + +import { + major, + minVersion, + satisfies, + subset, + valid, + validRange, +} from "semver"; +import { debug } from "./debug.js"; + +/** + * Returns the major version of an exact version or the lowest version that a + * range permits (e.g. `^10` -> 10, `~11.2.0` -> 11). Returns `undefined` for + * missing or unparseable input. + */ +export function getMajorVersion( + version: string | undefined, +): number | undefined { + if (!version) { + return undefined; + } + try { + const minVer = minVersion(version); + return minVer ? major(minVer) : undefined; + } catch (error) { + debug(error); + return undefined; + } +} + +export function fulfillsVersionRange({ + version, + acceptableVersions, + canBeLatest, +}: { + version: string; + acceptableVersions: string; + canBeLatest: boolean; +}): boolean { + if (version === "latest") { + return canBeLatest; + } + + let cleanedUserVersion, isRange; + + if (valid(version)) { + cleanedUserVersion = valid(version); + isRange = false; + } else if (validRange(version)) { + cleanedUserVersion = validRange(version); + isRange = true; + } + + return ( + // If the given version is a bogus format, this will still be undefined and we'll automatically reject it + !!cleanedUserVersion && + (isRange + ? subset(cleanedUserVersion, acceptableVersions) + : satisfies(cleanedUserVersion, acceptableVersions)) + ); +} diff --git a/packages/cli/src/lib/wizard/utils/types.ts b/packages/cli/src/lib/wizard/utils/types.ts new file mode 100644 index 0000000000..b7b267c44e --- /dev/null +++ b/packages/cli/src/lib/wizard/utils/types.ts @@ -0,0 +1,104 @@ +/** + * Types shared by the setup wizards: the options `sentry wizard` passes to a + * flow, the Sentry project a flow sets up, and feature prompts. + */ + +export interface SentryProjectData { + id: string; + slug: string; + organization: { + id: string; + name: string; + slug: string; + }; + keys: [{ dsn: { public: string } }]; +} + +export type PreselectedProject = { + project: SentryProjectData; + authToken: string; + selfHosted: boolean; +}; + +export type WizardOptions = { + /** + * Controls whether the wizard should send telemetry data to Sentry. + */ + telemetryEnabled: boolean; + + /** + * The promo code to use while signing up for Sentry. + * This can be passed via the --promo-code arg. + */ + promoCode?: string | undefined; + + /** + * The url of the Sentry instance to use. + * This can be passed via the `-u` or `--url` arg. + */ + url?: string | undefined; + + /** + * The org to pre-select in the wizard. + * This can be passed via the `--org` arg. + * Example: `--org my-org` + */ + orgSlug?: string | undefined; + + /** + * Project slug to pre-select in the wizard. + * This can be passed via the `--project` arg. + * Example: `--project my-project` + */ + projectSlug?: string | undefined; + + /** + * If this option is set, the wizard will skip the self-hosted or SaaS + * selection step and directly assume that the wizard is used for Sentry SaaS. + */ + saas?: boolean | undefined; + + /** + * If this is set, the wizard will skip the login and project selection step. + */ + preSelectedProject?: PreselectedProject | undefined; + + /** + * Force-install the SDK package to continue with the installation in case + * any package manager checks are failing (e.g. peer dependency versions). + * + * Use with caution and only if you know what you're doing. + * + * Does not apply to all wizard flows (currently NPM only) + */ + forceInstall?: boolean | undefined; + + /** + * Used when the wizard command is copied from partner sites (e.g. Vercel) + * to display login/signup instructions specific to organizations provisioned + * through the partner. + */ + comingFrom?: string | undefined; + + /** + * If this is set, the wizard will ignore any git changes in the project and not prompt for confirmation. + */ + ignoreGitChanges?: boolean | undefined; + + /** + * Enable Spotlight mode for local development without Sentry authentication. + * When enabled: + * - Skips login and project selection + * - Uses empty DSN + * - Skips auth token file creation + * This can be passed via the `--spotlight` arg. + */ + spotlight?: boolean | undefined; +}; + +export interface Feature { + id: string; + prompt: string; + enabledHint?: string | undefined; + disabledHint?: string | undefined; +} diff --git a/packages/cli/src/top-level-briefs.ts b/packages/cli/src/top-level-briefs.ts index e111dd8149..9a4808be84 100644 --- a/packages/cli/src/top-level-briefs.ts +++ b/packages/cli/src/top-level-briefs.ts @@ -52,6 +52,7 @@ export const TOP_LEVEL_BRIEFS = { trace: "View distributed traces", trial: "Manage product trials", init: "Print instructions for a coding agent to set up Sentry", + wizard: "Set up the Sentry SDK in your project interactively", info: "Print configuration and verify authentication", local: "Sentry for local development", api: "Make an authenticated API request", diff --git a/packages/cli/test/commands/wizard.test.ts b/packages/cli/test/commands/wizard.test.ts new file mode 100644 index 0000000000..f320f998b9 --- /dev/null +++ b/packages/cli/test/commands/wizard.test.ts @@ -0,0 +1,131 @@ +/** + * Tests for `sentry wizard`: integration selection, the flags it passes to a + * wizard flow, and how a stopped wizard sets the exit code. + */ + +import { afterEach, beforeEach, describe, expect, test, vi } from "vitest"; + +const { runNextjsWizard } = vi.hoisted(() => ({ + runNextjsWizard: vi.fn<(options: unknown) => Promise>(), +})); +vi.mock("../../src/lib/wizard/nextjs/nextjs-wizard.js", () => ({ + runNextjsWizard, +})); + +import { wizardCommand } from "../../src/commands/wizard.js"; +import type { SentryContext } from "../../src/context.js"; +import { ValidationError, WizardExitError } from "../../src/lib/errors.js"; +import type { Writer } from "../../src/types/index.js"; +import { loadCommand, useTestConfigDir } from "../helpers.js"; + +useTestConfigDir("wizard-test-"); + +const DEFAULT_FLAGS = { + saas: false, + debug: false, + spotlight: false, + "disable-telemetry": false, + "force-install": false, + "ignore-git-changes": false, + signup: false, + "skip-connect": false, + quiet: false, + uninstall: false, +}; + +async function runWizardCommand( + flags: Record = {}, +): Promise { + const context = { + process, + env: process.env, + stdout: { write: vi.fn(() => true) }, + stderr: { write: vi.fn(() => true) }, + stdin: process.stdin, + cwd: "/tmp", + homeDir: "/tmp", + configDir: "/tmp", + } as unknown as SentryContext; + const func = await loadCommand(wizardCommand); + await func.call(context, { ...DEFAULT_FLAGS, ...flags }); +} + +beforeEach(() => { + runNextjsWizard.mockReset(); + runNextjsWizard.mockResolvedValue(undefined); + process.exitCode = undefined; +}); + +afterEach(() => { + vi.unstubAllEnvs(); + process.exitCode = undefined; +}); + +describe("sentry wizard", () => { + test("runs the -i integration with the @sentry/wizard flags", async () => { + await runWizardCommand({ + integration: "nextjs", + org: "acme", + project: "web", + url: "https://sentry.example.com", + spotlight: true, + "force-install": true, + "ignore-git-changes": true, + "disable-telemetry": true, + "coming-from": "vercel", + }); + + expect(runNextjsWizard).toHaveBeenCalledWith({ + telemetryEnabled: false, + promoCode: undefined, + url: "https://sentry.example.com", + orgSlug: "acme", + projectSlug: "web", + saas: false, + forceInstall: true, + comingFrom: "vercel", + ignoreGitChanges: true, + spotlight: true, + }); + }); + + test("reads the integration and URL from SENTRY_WIZARD_* variables", async () => { + vi.stubEnv("SENTRY_WIZARD_INTEGRATION", "nextjs"); + vi.stubEnv("SENTRY_WIZARD_URL", "https://self-hosted.example.com"); + + await runWizardCommand(); + + expect(runNextjsWizard).toHaveBeenCalledWith( + expect.objectContaining({ url: "https://self-hosted.example.com" }), + ); + }); + + test("rejects an unknown SENTRY_WIZARD_INTEGRATION", async () => { + vi.stubEnv("SENTRY_WIZARD_INTEGRATION", "cobol"); + + await expect(runWizardCommand()).rejects.toThrow(ValidationError); + expect(runNextjsWizard).not.toHaveBeenCalled(); + }); + + test("reports an integration this version can't set up yet", async () => { + await expect(runWizardCommand({ integration: "remix" })).rejects.toThrow( + "The remix wizard is not available in this version yet.", + ); + }); + + test("exits with the wizard's code when it stops", async () => { + runNextjsWizard.mockRejectedValue(new WizardExitError(0)); + + await runWizardCommand({ integration: "nextjs" }); + + expect(process.exitCode).toBe(0); + }); + + test("exits with code 1 when the wizard can't continue", async () => { + runNextjsWizard.mockRejectedValue(new WizardExitError(1)); + + await runWizardCommand({ integration: "nextjs" }); + + expect(process.exitCode).toBe(1); + }); +}); diff --git a/packages/cli/test/lib/wizard/nextjs/templates.test.ts b/packages/cli/test/lib/wizard/nextjs/templates.test.ts new file mode 100644 index 0000000000..243b50328c --- /dev/null +++ b/packages/cli/test/lib/wizard/nextjs/templates.test.ts @@ -0,0 +1,963 @@ +import { describe, expect, it } from "vitest"; +import { + getNextjsConfigCjsAppendix, + getNextjsConfigCjsTemplate, + getNextjsConfigEsmCopyPasteSnippet, + getNextjsConfigMjsTemplate, + getRootLayout, + getSentryServersideConfigContents, + getInstrumentationClientFileContents, + getWithSentryConfigOptionsTemplate, + getGenerateMetadataSnippet, + getRootLayoutWithGenerateMetadata, + getSentryExamplePageContents, + getSentryExamplePagesDirApiRoute, + getSentryExampleAppDirApiRoute, +} from "../../../../src/lib/wizard/nextjs/templates.js"; + +describe("Next.js code templates", () => { + describe("getInstrumentationClientFileContents", () => { + it("generates client-side Sentry config with all features enabled", () => { + const template = getInstrumentationClientFileContents( + "my-dsn", + { + performance: true, + replay: true, + }, + false, + ); + + expect(template).toMatchInlineSnapshot(` + "// This file configures the initialization of Sentry on the client. + // The added config here will be used whenever a users loads a page in their browser. + // https://docs.sentry.io/platforms/javascript/guides/nextjs/ + + import * as Sentry from "@sentry/nextjs"; + + Sentry.init({ + dsn: "my-dsn", + + // Add optional integrations for additional features + integrations: [Sentry.replayIntegration()], + + // Define how likely traces are sampled. Adjust this value in production, or use tracesSampler for greater control. + tracesSampleRate: 1, + + // Define how likely Replay events are sampled. + // This sets the sample rate to be 10%. You may want this to be 100% while + // in development and sample at a lower rate in production + replaysSessionSampleRate: 0.1, + + // Define how likely Replay events are sampled when an error occurs. + replaysOnErrorSampleRate: 1.0, + + dataCollection: { + // To disable sending user data and HTTP bodies, uncomment the lines below. For more info visit: + // https://docs.sentry.io/platforms/javascript/guides/nextjs/configuration/options/#dataCollection + // userInfo: false, + // httpBodies: [], + }, + }); + + export const onRouterTransitionStart = Sentry.captureRouterTransitionStart; + " + `); + }); + + it("generates client-side Sentry config with performance monitoring disabled", () => { + const template = getInstrumentationClientFileContents( + "my-dsn", + { + performance: false, + replay: true, + }, + false, + ); + + expect(template).toMatchInlineSnapshot(` + "// This file configures the initialization of Sentry on the client. + // The added config here will be used whenever a users loads a page in their browser. + // https://docs.sentry.io/platforms/javascript/guides/nextjs/ + + import * as Sentry from "@sentry/nextjs"; + + Sentry.init({ + dsn: "my-dsn", + + // Add optional integrations for additional features + integrations: [Sentry.replayIntegration()], + + // Define how likely Replay events are sampled. + // This sets the sample rate to be 10%. You may want this to be 100% while + // in development and sample at a lower rate in production + replaysSessionSampleRate: 0.1, + + // Define how likely Replay events are sampled when an error occurs. + replaysOnErrorSampleRate: 1.0, + + dataCollection: { + // To disable sending user data and HTTP bodies, uncomment the lines below. For more info visit: + // https://docs.sentry.io/platforms/javascript/guides/nextjs/configuration/options/#dataCollection + // userInfo: false, + // httpBodies: [], + }, + }); + + export const onRouterTransitionStart = Sentry.captureRouterTransitionStart; + " + `); + }); + + it("generates client-side Sentry config with session replay disabled", () => { + const template = getInstrumentationClientFileContents( + "my-dsn", + { + performance: true, + replay: false, + }, + false, + ); + + expect(template).toMatchInlineSnapshot(` + "// This file configures the initialization of Sentry on the client. + // The added config here will be used whenever a users loads a page in their browser. + // https://docs.sentry.io/platforms/javascript/guides/nextjs/ + + import * as Sentry from "@sentry/nextjs"; + + Sentry.init({ + dsn: "my-dsn", + + // Define how likely traces are sampled. Adjust this value in production, or use tracesSampler for greater control. + tracesSampleRate: 1, + + dataCollection: { + // To disable sending user data and HTTP bodies, uncomment the lines below. For more info visit: + // https://docs.sentry.io/platforms/javascript/guides/nextjs/configuration/options/#dataCollection + // userInfo: false, + // httpBodies: [], + }, + }); + + export const onRouterTransitionStart = Sentry.captureRouterTransitionStart; + " + `); + }); + it("writes the active dataCollection preset when reduceDataCollection is true", () => { + const template = getInstrumentationClientFileContents( + "my-dsn", + { + performance: true, + replay: true, + }, + true, + ); + + expect(template).toContain("userInfo: false,"); + expect(template).toContain( + 'httpHeaders: { deny: ["forwarded", "-ip", "remote-", "via", "-user"] },', + ); + expect(template).not.toContain("// userInfo: false,"); + expect(template).not.toContain( + "To disable sending user data and HTTP bodies", + ); + }); + + it("uses empty DSN in spotlight mode", () => { + const template = getInstrumentationClientFileContents( + "", + { + performance: true, + replay: false, + }, + false, + true, // spotlight + ); + + // Verify DSN is empty for spotlight + expect(template).toContain('dsn: ""'); + expect(template).toContain("spotlight: true"); + }); + }); + + describe("getSentryServersideConfigContents", () => { + describe("server-side", () => { + it("generates server-side Sentry config with all features enabled", () => { + const template = getSentryServersideConfigContents( + "my-dsn", + "server", + { + performance: true, + replay: true, + }, + false, + ); + + expect(template).toMatchInlineSnapshot(` + "// This file configures the initialization of Sentry on the server. + // The config you add here will be used whenever the server handles a request. + // https://docs.sentry.io/platforms/javascript/guides/nextjs/ + + import * as Sentry from "@sentry/nextjs"; + + Sentry.init({ + dsn: "my-dsn", + + // Define how likely traces are sampled. Adjust this value in production, or use tracesSampler for greater control. + tracesSampleRate: 1, + + dataCollection: { + // To disable sending user data and HTTP bodies, uncomment the lines below. For more info visit: + // https://docs.sentry.io/platforms/javascript/guides/nextjs/configuration/options/#dataCollection + // userInfo: false, + // httpBodies: [], + }, + }); + " + `); + }); + + it("generates server-side Sentry config with performance monitoring disabled", () => { + const template = getSentryServersideConfigContents( + "my-dsn", + "server", + { + performance: false, + replay: true, + }, + false, + ); + + expect(template).toMatchInlineSnapshot(` + "// This file configures the initialization of Sentry on the server. + // The config you add here will be used whenever the server handles a request. + // https://docs.sentry.io/platforms/javascript/guides/nextjs/ + + import * as Sentry from "@sentry/nextjs"; + + Sentry.init({ + dsn: "my-dsn", + + dataCollection: { + // To disable sending user data and HTTP bodies, uncomment the lines below. For more info visit: + // https://docs.sentry.io/platforms/javascript/guides/nextjs/configuration/options/#dataCollection + // userInfo: false, + // httpBodies: [], + }, + }); + " + `); + }); + + it("generates server-side Sentry config with spotlight disabled", () => { + const template = getSentryServersideConfigContents( + "my-dsn", + "server", + { + performance: true, + replay: true, + }, + false, + ); + + expect(template).toMatchInlineSnapshot(` + "// This file configures the initialization of Sentry on the server. + // The config you add here will be used whenever the server handles a request. + // https://docs.sentry.io/platforms/javascript/guides/nextjs/ + + import * as Sentry from "@sentry/nextjs"; + + Sentry.init({ + dsn: "my-dsn", + + // Define how likely traces are sampled. Adjust this value in production, or use tracesSampler for greater control. + tracesSampleRate: 1, + + dataCollection: { + // To disable sending user data and HTTP bodies, uncomment the lines below. For more info visit: + // https://docs.sentry.io/platforms/javascript/guides/nextjs/configuration/options/#dataCollection + // userInfo: false, + // httpBodies: [], + }, + }); + " + `); + }); + + it("writes the active dataCollection preset when reduceDataCollection is true", () => { + const template = getSentryServersideConfigContents( + "my-dsn", + "server", + { + performance: true, + replay: true, + }, + true, + ); + + expect(template).toContain("userInfo: false,"); + expect(template).toContain( + 'httpHeaders: { deny: ["forwarded", "-ip", "remote-", "via", "-user"] },', + ); + expect(template).not.toContain("// userInfo: false,"); + expect(template).not.toContain( + "To disable sending user data and HTTP bodies", + ); + }); + + it("uses empty DSN in spotlight mode", () => { + const template = getSentryServersideConfigContents( + "", + "server", + { + performance: true, + replay: false, + }, + false, + true, // spotlight + ); + + // Verify DSN is empty for spotlight + expect(template).toContain('dsn: ""'); + expect(template).toContain("spotlight: true"); + }); + }); + + describe("edge", () => { + it("generates edge Sentry config with all features enabled", () => { + const template = getSentryServersideConfigContents( + "my-dsn", + "edge", + { + performance: true, + replay: true, + }, + false, + ); + + expect(template).toMatchInlineSnapshot(` + "// This file configures the initialization of Sentry for edge features (middleware, edge routes, and so on). + // The config you add here will be used whenever one of the edge features is loaded. + // Note that this config is unrelated to the Vercel Edge Runtime and is also required when running locally. + // https://docs.sentry.io/platforms/javascript/guides/nextjs/ + + import * as Sentry from "@sentry/nextjs"; + + Sentry.init({ + dsn: "my-dsn", + + // Define how likely traces are sampled. Adjust this value in production, or use tracesSampler for greater control. + tracesSampleRate: 1, + + dataCollection: { + // To disable sending user data and HTTP bodies, uncomment the lines below. For more info visit: + // https://docs.sentry.io/platforms/javascript/guides/nextjs/configuration/options/#dataCollection + // userInfo: false, + // httpBodies: [], + }, + }); + " + `); + }); + + it("generates edge Sentry config with performance monitoring disabled", () => { + const template = getSentryServersideConfigContents( + "my-dsn", + "edge", + { + performance: false, + replay: true, + }, + false, + ); + + expect(template).toMatchInlineSnapshot(` + "// This file configures the initialization of Sentry for edge features (middleware, edge routes, and so on). + // The config you add here will be used whenever one of the edge features is loaded. + // Note that this config is unrelated to the Vercel Edge Runtime and is also required when running locally. + // https://docs.sentry.io/platforms/javascript/guides/nextjs/ + + import * as Sentry from "@sentry/nextjs"; + + Sentry.init({ + dsn: "my-dsn", + + dataCollection: { + // To disable sending user data and HTTP bodies, uncomment the lines below. For more info visit: + // https://docs.sentry.io/platforms/javascript/guides/nextjs/configuration/options/#dataCollection + // userInfo: false, + // httpBodies: [], + }, + }); + " + `); + }); + + it("writes the active dataCollection preset when reduceDataCollection is true", () => { + const template = getSentryServersideConfigContents( + "my-dsn", + "edge", + { + performance: true, + replay: true, + }, + true, + ); + + expect(template).toContain("userInfo: false,"); + expect(template).toContain( + 'httpHeaders: { deny: ["forwarded", "-ip", "remote-", "via", "-user"] },', + ); + expect(template).not.toContain("// userInfo: false,"); + expect(template).not.toContain( + "To disable sending user data and HTTP bodies", + ); + }); + }); + }); + + describe("getWithSentryConfigOptionsTemplate", () => { + it("generates options for SaaS", () => { + const template = getWithSentryConfigOptionsTemplate({ + orgSlug: "my-org", + projectSlug: "my-project", + selfHosted: false, + sentryUrl: "https://dont-use-this-url.com", + tunnelRoute: true, + }); + + expect(template).toMatchInlineSnapshot(` + "{ + // For all available options, see: + // https://docs.sentry.io/platforms/javascript/guides/nextjs/sourcemaps/uploading/bundler-plugin-options/ + + org: "my-org", + project: "my-project", + + // Only print logs for uploading source maps in CI + silent: !process.env.CI, + + // For all available options, see: + // https://docs.sentry.io/platforms/javascript/guides/nextjs/manual-setup/ + + // Upload a larger set of source maps for prettier stack traces (increases build time) + widenClientFileUpload: true, + + // Route browser requests to Sentry through a Next.js rewrite to circumvent ad-blockers. + // This can increase your server load as well as your hosting bill. + // Note: Check that the configured route will not match with your Next.js middleware, otherwise reporting of client- + // side errors will fail. + tunnelRoute: "/monitoring", + + webpack: { + // Enables automatic instrumentation of Vercel Cron Monitors. (Does not yet work with App Router route handlers.) + // See the following for more information: + // https://docs.sentry.io/product/crons/ + // https://vercel.com/docs/cron-jobs + automaticVercelMonitors: true, + + // Tree-shaking options for reducing bundle size + treeshake: { + // Automatically tree-shake Sentry logger statements to reduce bundle size + removeDebugLogging: true, + }, + }, + }" + `); + }); + + it("generates options for self-hosted", () => { + const template = getWithSentryConfigOptionsTemplate({ + orgSlug: "my-org", + projectSlug: "my-project", + selfHosted: true, + sentryUrl: "https://my-sentry.com", + tunnelRoute: true, + }); + + expect(template).toMatchInlineSnapshot(` + "{ + // For all available options, see: + // https://docs.sentry.io/platforms/javascript/guides/nextjs/sourcemaps/uploading/bundler-plugin-options/ + + org: "my-org", + project: "my-project", + sentryUrl: "https://my-sentry.com", + + // Only print logs for uploading source maps in CI + silent: !process.env.CI, + + // For all available options, see: + // https://docs.sentry.io/platforms/javascript/guides/nextjs/manual-setup/ + + // Upload a larger set of source maps for prettier stack traces (increases build time) + widenClientFileUpload: true, + + // Route browser requests to Sentry through a Next.js rewrite to circumvent ad-blockers. + // This can increase your server load as well as your hosting bill. + // Note: Check that the configured route will not match with your Next.js middleware, otherwise reporting of client- + // side errors will fail. + tunnelRoute: "/monitoring", + + webpack: { + // Enables automatic instrumentation of Vercel Cron Monitors. (Does not yet work with App Router route handlers.) + // See the following for more information: + // https://docs.sentry.io/product/crons/ + // https://vercel.com/docs/cron-jobs + automaticVercelMonitors: true, + + // Tree-shaking options for reducing bundle size + treeshake: { + // Automatically tree-shake Sentry logger statements to reduce bundle size + removeDebugLogging: true, + }, + }, + }" + `); + }); + + it("comments out tunnelRoute if `tunnelRoute` option is disabled", () => { + const template = getWithSentryConfigOptionsTemplate({ + orgSlug: "my-org", + projectSlug: "my-project", + selfHosted: false, + sentryUrl: "https://dont-use-this-url.com", + tunnelRoute: false, + }); + + expect(template).toMatchInlineSnapshot(` + "{ + // For all available options, see: + // https://docs.sentry.io/platforms/javascript/guides/nextjs/sourcemaps/uploading/bundler-plugin-options/ + + org: "my-org", + project: "my-project", + + // Only print logs for uploading source maps in CI + silent: !process.env.CI, + + // For all available options, see: + // https://docs.sentry.io/platforms/javascript/guides/nextjs/manual-setup/ + + // Upload a larger set of source maps for prettier stack traces (increases build time) + widenClientFileUpload: true, + + // Uncomment to route browser requests to Sentry through a Next.js rewrite to circumvent ad-blockers. + // This can increase your server load as well as your hosting bill. + // Note: Check that the configured route will not match with your Next.js middleware, otherwise reporting of client- + // side errors will fail. + // tunnelRoute: "/monitoring", + + webpack: { + // Enables automatic instrumentation of Vercel Cron Monitors. (Does not yet work with App Router route handlers.) + // See the following for more information: + // https://docs.sentry.io/product/crons/ + // https://vercel.com/docs/cron-jobs + automaticVercelMonitors: true, + + // Tree-shaking options for reducing bundle size + treeshake: { + // Automatically tree-shake Sentry logger statements to reduce bundle size + removeDebugLogging: true, + }, + }, + }" + `); + }); + }); + + describe("getRootLayout", () => { + it("generates a root layout component with types", () => { + expect(getRootLayout(true)).toMatchInlineSnapshot(` + "// This file was generated by the Sentry wizard because we couldn't find a root layout file. + // You can delete this file at any time. + + export const metadata = { + title: 'Sentry NextJS Example', + description: 'Generated by Sentry', + } + + export default function RootLayout({ + children, + }: { + children: React.ReactNode + }) { + return ( + + {children} + + ) + } + " + `); + }); + it("generates a root layout component without types", () => { + expect(getRootLayout(false)).toMatchInlineSnapshot(` + "// This file was generated by the Sentry wizard because we couldn't find a root layout file. + // You can delete this file at any time. + + export const metadata = { + title: 'Sentry NextJS Example', + description: 'Generated by Sentry', + } + + export default function RootLayout({ + children, + }) { + return ( + + {children} + + ) + } + " + `); + }); + }); + + describe("getGenerateMetadataSnippet", () => { + it("generates metadata snippet with TypeScript types", () => { + const template = getGenerateMetadataSnippet(true); + + expect(template).toMatchInlineSnapshot(` +" + import * as Sentry from '@sentry/nextjs'; + import type { Metadata } from 'next'; + + // Add or edit your "generateMetadata" to include the Sentry trace data: + export function generateMetadata(): Metadata { + return { + // ... your existing metadata + other: { + ...Sentry.getTraceData() + } + }; + } +" +`); + }); + + it("generates metadata snippet without TypeScript types", () => { + const template = getGenerateMetadataSnippet(false); + + expect(template).toMatchInlineSnapshot(` + " + import * as Sentry from '@sentry/nextjs'; + + + // Add or edit your "generateMetadata" to include the Sentry trace data: + export function generateMetadata() { + return { + // ... your existing metadata + other: { + ...Sentry.getTraceData() + } + }; + } + " + `); + }); + }); + + describe("getRootLayoutWithGenerateMetadata", () => { + it("generates root layout with TypeScript types", () => { + const template = getRootLayoutWithGenerateMetadata(true); + + expect(template).toMatchInlineSnapshot(` + "// This file was generated by the Sentry wizard because we couldn't find a root layout file. + import * as Sentry from '@sentry/nextjs'; + import type { Metadata } from 'next'; + + export function generateMetadata(): Metadata { + return { + other: { + ...Sentry.getTraceData(), + } + } + }; + + export default function RootLayout({ + children, + }: { + children: React.ReactNode + }) { + return ( + + {children} + + ) + } + " + `); + }); + + it("generates root layout without TypeScript types", () => { + const template = getRootLayoutWithGenerateMetadata(false); + + expect(template).toMatchInlineSnapshot(` + "// This file was generated by the Sentry wizard because we couldn't find a root layout file. + import * as Sentry from '@sentry/nextjs'; + + + export function generateMetadata() { + return { + other: { + ...Sentry.getTraceData(), + } + } + }; + + export default function RootLayout({ + children, + }) { + return ( + + {children} + + ) + } + " + `); + }); + }); + + describe("getSentryExamplePageContents", () => { + it("generates example page with TypeScript types", () => { + const template = getSentryExamplePageContents({ + selfHosted: false, + sentryUrl: "https://sentry.io", + orgSlug: "my-org", + projectId: "123", + useClient: true, + isTypeScript: true, + }); + + expect(template).toContain('"use client";'); + expect(template).toContain("constructor(message: string | undefined)"); + expect(template).toContain( + "class SentryExampleFrontendError extends Error", + ); + }); + + it("generates example page without TypeScript types", () => { + const template = getSentryExamplePageContents({ + selfHosted: false, + sentryUrl: "https://sentry.io", + orgSlug: "my-org", + projectId: "123", + useClient: true, + isTypeScript: false, + }); + + expect(template).toContain('"use client";'); + expect(template).toContain("constructor(message)"); + expect(template).toContain( + "class SentryExampleFrontendError extends Error", + ); + }); + + it("generates example page without useClient directive", () => { + const template = getSentryExamplePageContents({ + selfHosted: false, + sentryUrl: "https://sentry.io", + orgSlug: "my-org", + projectId: "123", + useClient: false, + isTypeScript: true, + }); + + expect(template).not.toContain('"use client";'); + expect(template).toContain( + "https://my-org.sentry.io/issues/?project=123", + ); + }); + + it("generates example page with logger calls", () => { + const template = getSentryExamplePageContents({ + selfHosted: false, + sentryUrl: "https://sentry.io", + orgSlug: "my-org", + projectId: "123", + useClient: true, + isTypeScript: true, + }); + + expect(template).toContain( + 'Sentry.logger.info("Sentry example page loaded")', + ); + expect(template).toContain( + 'Sentry.logger.info("User clicked the button, throwing a sample error")', + ); + }); + }); + + describe("getSentryExamplePagesDirApiRoute", () => { + it("generates Pages Router API route with TypeScript types", () => { + const template = getSentryExamplePagesDirApiRoute({ + isTypeScript: true, + }); + + expect(template).toContain("constructor(message: string | undefined)"); + expect(template).toContain("class SentryExampleAPIError extends Error"); + expect(template).toContain("export default function handler(_req, res)"); + }); + + it("generates Pages Router API route without TypeScript types", () => { + const template = getSentryExamplePagesDirApiRoute({ + isTypeScript: false, + }); + + expect(template).toContain("constructor(message)"); + expect(template).toContain("class SentryExampleAPIError extends Error"); + expect(template).toContain("export default function handler(_req, res)"); + }); + + it("generates Pages Router API route with logger calls", () => { + const template = getSentryExamplePagesDirApiRoute({ + isTypeScript: true, + }); + + expect(template).toContain('import * as Sentry from "@sentry/nextjs";'); + expect(template).toContain( + 'Sentry.logger.info("Sentry example API called")', + ); + }); + }); + + describe("getSentryExampleAppDirApiRoute", () => { + it("generates App Router API route with TypeScript types", () => { + const template = getSentryExampleAppDirApiRoute({ + isTypeScript: true, + dynamicStrategy: "force-dynamic", + }); + + expect(template).toContain("constructor(message: string | undefined)"); + expect(template).toContain("class SentryExampleAPIError extends Error"); + expect(template).toContain("export function GET()"); + expect(template).toContain('export const dynamic = "force-dynamic";'); + }); + + it("generates App Router API route without TypeScript types", () => { + const template = getSentryExampleAppDirApiRoute({ + isTypeScript: false, + dynamicStrategy: "force-dynamic", + }); + + expect(template).toContain("constructor(message)"); + expect(template).toContain("class SentryExampleAPIError extends Error"); + expect(template).toContain("export function GET()"); + expect(template).toContain('export const dynamic = "force-dynamic";'); + }); + + it("generates App Router API route with logger calls", () => { + const template = getSentryExampleAppDirApiRoute({ + isTypeScript: true, + dynamicStrategy: "force-dynamic", + }); + + expect(template).toContain('import * as Sentry from "@sentry/nextjs";'); + expect(template).toContain( + 'Sentry.logger.info("Sentry example API called")', + ); + }); + + it("uses connection() instead of route segment config for the connection strategy", () => { + // Next.js 16 with `cacheComponents` rejects route segment config and + // prerenders route handlers unless they opt into request-time rendering. + const template = getSentryExampleAppDirApiRoute({ + isTypeScript: true, + dynamicStrategy: "connection", + }); + + expect(template).not.toContain("force-dynamic"); + expect(template).not.toContain("export const dynamic"); + expect(template).toContain('import { connection } from "next/server";'); + expect(template).toContain("export async function GET()"); + expect(template).toContain("await connection();"); + expect(template).toContain( + 'Sentry.logger.info("Sentry example API called")', + ); + }); + }); + + describe("next.config templates", () => { + const options = '{ org: "my-org", project: "my-project" }'; + + it("CJS template imports withSentryConfig from @sentry/nextjs/config", () => { + const template = getNextjsConfigCjsTemplate(options); + expect(template).toContain( + 'const { withSentryConfig } = require("@sentry/nextjs/config");', + ); + expect(template).toContain( + `module.exports = withSentryConfig(nextConfig, ${options});`, + ); + }); + + it("MJS template imports withSentryConfig from @sentry/nextjs/config", () => { + const template = getNextjsConfigMjsTemplate(options); + expect(template).toContain( + 'import { withSentryConfig } from "@sentry/nextjs/config";', + ); + expect(template).toContain( + `export default withSentryConfig(nextConfig, ${options});`, + ); + }); + + it("CJS appendix imports withSentryConfig from @sentry/nextjs/config", () => { + const template = getNextjsConfigCjsAppendix(options); + expect(template).toContain( + 'const { withSentryConfig } = require("@sentry/nextjs/config");', + ); + expect(template).toContain( + `module.exports = withSentryConfig(module.exports, ${options});`, + ); + }); + + it("ESM copy-paste snippet imports withSentryConfig from @sentry/nextjs/config", () => { + const template = getNextjsConfigEsmCopyPasteSnippet(options); + expect(template).toContain( + 'import { withSentryConfig } from "@sentry/nextjs/config";', + ); + expect(template).toContain( + `export default withSentryConfig(yourNextConfig, ${options});`, + ); + }); + + it("uses the root export when an older SDK requires it", () => { + const cjs = getNextjsConfigCjsTemplate(options, "@sentry/nextjs"); + const mjs = getNextjsConfigMjsTemplate(options, "@sentry/nextjs"); + const appendix = getNextjsConfigCjsAppendix(options, "@sentry/nextjs"); + const snippet = getNextjsConfigEsmCopyPasteSnippet( + options, + "@sentry/nextjs", + ); + + expect(cjs).toContain( + 'const { withSentryConfig } = require("@sentry/nextjs");', + ); + expect(mjs).toContain( + 'import { withSentryConfig } from "@sentry/nextjs";', + ); + expect(appendix).toContain( + 'const { withSentryConfig } = require("@sentry/nextjs");', + ); + expect(snippet).toContain( + 'import { withSentryConfig } from "@sentry/nextjs";', + ); + for (const template of [cjs, mjs, appendix, snippet]) { + expect(template).not.toContain("@sentry/nextjs/config"); + } + }); + + it("never references the root @sentry/nextjs export for withSentryConfig by default", () => { + for (const template of [ + getNextjsConfigCjsTemplate(options), + getNextjsConfigMjsTemplate(options), + getNextjsConfigCjsAppendix(options), + getNextjsConfigEsmCopyPasteSnippet(options), + ]) { + expect(template).not.toMatch(/["']@sentry\/nextjs["']/); + } + }); + }); +}); diff --git a/packages/cli/test/lib/wizard/nextjs/utils.test.ts b/packages/cli/test/lib/wizard/nextjs/utils.test.ts new file mode 100644 index 0000000000..df026e57ed --- /dev/null +++ b/packages/cli/test/lib/wizard/nextjs/utils.test.ts @@ -0,0 +1,232 @@ +import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"; +import type { Mock } from "vitest"; +// oxlint-disable-next-line sentry-cli/no-namespace-import -- needed for spyOn mocking +import * as fs from "node:fs"; +import { parseModule } from "magicast"; +import { + addWithSentryConfigImport, + getNextJsVersionBucket, + getMaybeAppDirLocation, + hasRootLayoutFile, + getExampleApiRouteDynamicStrategy, + getWithSentryConfigImportPath, + isNextJsVersionSupported, +} from "../../../../src/lib/wizard/nextjs/utils.js"; + +vi.mock("node:fs", async (importOriginal) => ({ + ...(await importOriginal()), + existsSync: vi.fn(), + lstatSync: vi.fn(), +})); + +describe("Next.js Utils", () => { + describe("getNextJsVersionBucket", () => { + it('returns "none" for undefined version', () => { + expect(getNextJsVersionBucket(undefined)).toBe("none"); + }); + + it('returns "<11.0.0" for versions below 11', () => { + expect(getNextJsVersionBucket("10.0.0")).toBe("<11.0.0"); + }); + + it("returns major version for versions 11 and above", () => { + expect(getNextJsVersionBucket("11.0.0")).toBe("11.x"); + expect(getNextJsVersionBucket("11.2.5")).toBe("11.x"); + expect(getNextJsVersionBucket("13.5.2")).toBe("13.x"); + expect(getNextJsVersionBucket("14.0.0")).toBe("14.x"); + }); + }); + + describe("getMaybeAppDirLocation", () => { + const mockCwd = "/mock/cwd"; + let originalCwd: () => string; + + beforeEach(() => { + originalCwd = process.cwd; + process.cwd = vi.fn(() => mockCwd); + vi.clearAllMocks(); + }); + + afterEach(() => { + process.cwd = originalCwd; + }); + + it('returns ["app"] when app directory exists in root', () => { + (fs.existsSync as Mock).mockImplementation((filePath: string) => { + return filePath === "/mock/cwd/app"; + }); + (fs.lstatSync as Mock).mockImplementation((filePath: string) => ({ + isDirectory: () => filePath === "/mock/cwd/app", + })); + + expect(getMaybeAppDirLocation()).toEqual(["app"]); + }); + + it('returns ["src", "app"] when app directory exists in src', () => { + (fs.existsSync as Mock).mockImplementation((filePath: string) => { + return filePath === "/mock/cwd/src/app"; + }); + (fs.lstatSync as Mock).mockImplementation((filePath: string) => ({ + isDirectory: () => filePath === "/mock/cwd/src/app", + })); + + expect(getMaybeAppDirLocation()).toEqual(["src", "app"]); + }); + + it("returns undefined when no app directory exists", () => { + (fs.existsSync as Mock).mockReturnValue(false); + + expect(getMaybeAppDirLocation()).toBeUndefined(); + }); + }); + + describe("hasRootLayoutFile", () => { + beforeEach(() => { + vi.clearAllMocks(); + }); + + it("returns true when layout file exists with any supported extension", () => { + const mockAppFolderPath = "/mock/app"; + const supportedExtensions = ["jsx", "tsx", "js"]; + + supportedExtensions.forEach((ext) => { + (fs.existsSync as Mock).mockImplementation((filePath: string) => { + return filePath === `/mock/app/layout.${ext}`; + }); + + expect(hasRootLayoutFile(mockAppFolderPath)).toBe(true); + }); + }); + + it("returns false when no layout file exists", () => { + const mockAppFolderPath = "/mock/app"; + (fs.existsSync as Mock).mockReturnValue(false); + + expect(hasRootLayoutFile(mockAppFolderPath)).toBe(false); + }); + }); + + describe("isNextJsVersionSupported", () => { + it.each(["14.0.0", "^14.2.0", "15.5.21", "~16.2.0", "17.0.0-canary.1"])( + "returns true for %s", + (version) => { + expect(isNextJsVersionSupported(version)).toBe(true); + }, + ); + + it.each(["13.5.6", "^13.0.0", "12.3.4", "11.0.0"])( + "returns false for %s", + (version) => { + expect(isNextJsVersionSupported(version)).toBe(false); + }, + ); + + it.each([undefined, "latest", "not-a-version"])( + "returns true when the version is unknown (%s)", + (version) => { + expect(isNextJsVersionSupported(version)).toBe(true); + }, + ); + }); + + describe("getExampleApiRouteDynamicStrategy", () => { + it.each(["14.2.35", "^14.0.0", "13.5.6"])( + "returns force-dynamic for %s", + (version) => { + expect(getExampleApiRouteDynamicStrategy(version)).toBe( + "force-dynamic", + ); + }, + ); + + it.each(["15.0.0", "^15.5.0", "16.2.11", "~16.0.0", "17.0.0-canary.1"])( + "returns connection for %s", + (version) => { + expect(getExampleApiRouteDynamicStrategy(version)).toBe("connection"); + }, + ); + + it.each([undefined, "latest", "not-a-version"])( + "falls back to force-dynamic when the version is unknown (%s)", + (version) => { + expect(getExampleApiRouteDynamicStrategy(version)).toBe( + "force-dynamic", + ); + }, + ); + }); + + describe("getWithSentryConfigImportPath", () => { + it.each(["10.73.0", "^10.73.0", "10.74.0", "^11.0.0", "11.0.0-beta.2"])( + "returns the /config subpath for %s", + (version) => { + expect(getWithSentryConfigImportPath(version)).toBe( + "@sentry/nextjs/config", + ); + }, + ); + + it.each(["10.72.0", "^10.0.0", "~10.50.0", "9.47.1", "8.55.2"])( + "falls back to the root export for %s", + (version) => { + expect(getWithSentryConfigImportPath(version)).toBe("@sentry/nextjs"); + }, + ); + + it.each([undefined, "latest", "not-a-version", "workspace:*"])( + "returns the /config subpath when the version is unknown (%s)", + (version) => { + expect(getWithSentryConfigImportPath(version)).toBe( + "@sentry/nextjs/config", + ); + }, + ); + }); + + describe("addWithSentryConfigImport", () => { + it("uses the given import path", () => { + const mod = parseModule("export default {};"); + + addWithSentryConfigImport(mod, "@sentry/nextjs"); + + expect(mod.generate().code).toContain( + 'import {withSentryConfig} from "@sentry/nextjs";', + ); + }); + + it("adds the import from @sentry/nextjs/config when none exists", () => { + const mod = parseModule("export default {};"); + + addWithSentryConfigImport(mod); + + expect(mod.generate().code).toContain( + 'import {withSentryConfig} from "@sentry/nextjs/config";', + ); + }); + + it("rewrites an existing import from the root @sentry/nextjs export", () => { + const mod = parseModule( + 'import { withSentryConfig } from "@sentry/nextjs";\nexport default withSentryConfig({});', + ); + + addWithSentryConfigImport(mod); + + const code = mod.generate().code; + expect(code.match(/withSentryConfig.*from/g)).toHaveLength(1); + expect(code).toContain('from "@sentry/nextjs/config"'); + expect(code).not.toContain('from "@sentry/nextjs"'); + }); + + it("leaves an existing import from @sentry/nextjs/config untouched", () => { + const mod = parseModule( + 'import { withSentryConfig } from "@sentry/nextjs/config";\nexport default withSentryConfig({});', + ); + + addWithSentryConfigImport(mod); + + expect(mod.generate().code.match(/withSentryConfig.*from/g)).toHaveLength( + 1, + ); + }); + }); +}); diff --git a/packages/cli/test/lib/wizard/nextjs/wizard-double-wrap-prevention.test.ts b/packages/cli/test/lib/wizard/nextjs/wizard-double-wrap-prevention.test.ts new file mode 100644 index 0000000000..fd2a2c67ed --- /dev/null +++ b/packages/cli/test/lib/wizard/nextjs/wizard-double-wrap-prevention.test.ts @@ -0,0 +1,300 @@ +import { describe, it, expect, vi } from "vitest"; +import { generateCode, parseModule } from "magicast"; +import { getWithSentryConfigOptionsTemplate } from "../../../../src/lib/wizard/nextjs/templates.js"; +import { + unwrapSentryConfigAst, + wrapWithSentryConfig, +} from "../../../../src/lib/wizard/nextjs/utils.js"; + +vi.mock("../../../../src/lib/wizard/utils/clack/mcp-config.js", () => ({ + offerProjectScopedMcpConfig: vi.fn().mockResolvedValue(undefined), +})); + +describe("Next.js wizard double wrap prevention", () => { + const mockWithSentryConfigOptionsTemplate = + getWithSentryConfigOptionsTemplate({ + orgSlug: "test-org", + projectSlug: "test-project", + selfHosted: false, + sentryUrl: "https://sentry.io", + tunnelRoute: false, + }); + + describe("unwrapSentryConfigAst utility function", () => { + describe("AST-based expression unwrapping", () => { + it("keeps code without withSentryConfig", () => { + const mod = parseModule("export default nextConfig"); + const originalAST = mod.exports["default"].$ast; + const resultAST = unwrapSentryConfigAst(originalAST); + expect(resultAST).toBe(originalAST); + const { code: exportDefaultCode } = generateCode({ $ast: resultAST }); + expect(exportDefaultCode).toMatchInlineSnapshot(`"nextConfig"`); + }); + + it("should handle plain object literal exports", () => { + const mod = parseModule( + `export default { nextConfig: { randomValue: true } }`, + ); + const originalAST = mod.exports["default"].$ast; + const resultAST = unwrapSentryConfigAst(originalAST); + + expect(resultAST).toBe(originalAST); + expect(resultAST.type).toBe("ObjectExpression"); + expect(resultAST).toHaveProperty("properties.length", 1); + }); + + it("should unwrap withSentryConfig with options", () => { + const mod = parseModule( + 'export default withSentryConfig(nextConfig, { org: "test" })', + ); + const wrappedAst = mod.exports["default"].$ast; + const resultAST = unwrapSentryConfigAst(wrappedAst); + const { code: exportDefaultCode } = generateCode({ $ast: resultAST }); + + expect(exportDefaultCode).toMatchInlineSnapshot(`"nextConfig"`); + }); + + it("should unwrap withSentryConfig without options", () => { + const mod = parseModule("export default withSentryConfig(nextConfig)"); + const wrappedAst = mod.exports["default"].$ast; + const resultAST = unwrapSentryConfigAst(wrappedAst); + const { code: exportDefaultCode } = generateCode({ $ast: resultAST }); + + expect(exportDefaultCode).toMatchInlineSnapshot(`"nextConfig"`); + }); + + it("should handle nested withSentryConfig calls", () => { + const mod = parseModule( + 'export default withSentryConfig(withSentryConfig(nextConfig, { org: "inner" }), { org: "outer" })', + ); + const wrappedAst = mod.exports["default"].$ast; + const resultAST = unwrapSentryConfigAst(wrappedAst); + + // Should unwrap one level and return the inner withSentryConfig call + expect(resultAST.type).toBe("CallExpression"); + expect(resultAST).toHaveProperty("callee.name", "withSentryConfig"); + const { code: exportDefaultCode } = generateCode({ $ast: resultAST }); + + expect(exportDefaultCode).toMatchInlineSnapshot( + `"withSentryConfig(nextConfig, { org: "inner" })"`, + ); + }); + + it("should handle complex expressions", () => { + const mod = parseModule( + "export default withSentryConfig(someComplexExpression.withMethods())", + ); + const wrappedAst = mod.exports["default"].$ast; + const resultAST = unwrapSentryConfigAst(wrappedAst); + const { code: exportDefaultCode } = generateCode({ $ast: resultAST }); + + expect(exportDefaultCode).toMatchInlineSnapshot( + `"someComplexExpression.withMethods()"`, + ); + }); + + it("should handle object literals", () => { + const mod = parseModule( + 'export default withSentryConfig({ next: "config", obj: { next: "nested" } }, { org: "test" })', + ); + const wrappedAst = mod.exports["default"].$ast; + const resultAST = unwrapSentryConfigAst(wrappedAst); + const { code: exportDefaultCode } = generateCode({ $ast: resultAST }); + + expect(exportDefaultCode).toMatchInlineSnapshot( + `"{ next: "config", obj: { next: "nested" } }"`, + ); + }); + + it("should return unchanged if not a withSentryConfig call", () => { + const mod = parseModule("export default someOtherFunction(nextConfig)"); + const originalAST = mod.exports["default"].$ast; + const resultAST = unwrapSentryConfigAst(originalAST); + + expect(resultAST).toBe(originalAST); + }); + }); + }); + + describe("MJS/TS files", () => { + it("should unwrap existing withSentryConfig and re-wrap with new config using AST", () => { + const existingMjsContent = `import { withSentryConfig } from "@sentry/nextjs"; + +const nextConfig = {}; + +export default withSentryConfig(nextConfig, { + org: "old-org", + project: "old-project", +});`; + + const mod = parseModule(existingMjsContent); + const originalAST = mod.exports["default"].$ast; + const unwrappedAst = unwrapSentryConfigAst(originalAST); + // Verify it returns the first argument (nextConfig identifier) + expect(unwrappedAst.type).toBe("Identifier"); + expect(unwrappedAst).toHaveProperty("name", "nextConfig"); + + // Create a fresh module to simulate the re-wrapping process + const freshMod = + parseModule(`import { withSentryConfig } from "@sentry/nextjs"; + +const nextConfig = {}; + +export default nextConfig;`); + + // Apply wrapping + freshMod.exports["default"] = wrapWithSentryConfig( + freshMod.exports["default"], + mockWithSentryConfigOptionsTemplate, + ); + + const newCode = freshMod.generate().code; + + // Verify only one withSentryConfig call exists + const withSentryConfigMatches = newCode.match(/withSentryConfig\s*\(/g); + expect(withSentryConfigMatches).toHaveLength(1); + + expect(newCode).toContain("test-org"); + expect(newCode).toContain("test-project"); + expect(newCode).not.toContain("old-org"); + expect(newCode).not.toContain("old-project"); + }); + + it("should handle complex nested configurations using AST", () => { + const existingMjsContent = `import { withSentryConfig } from "@sentry/nextjs"; + +const nextConfig = { experimental: { appDir: true } }; + +export default withSentryConfig( + withSentryConfig(nextConfig, { org: "nested-org" }), + { org: "outer-org" } +);`; + + const mod = parseModule(existingMjsContent); + + // First unwrap ---- + const firstUnwrapAST = unwrapSentryConfigAst(mod.exports["default"].$ast); + expect(firstUnwrapAST.type).toBe("CallExpression"); + expect(firstUnwrapAST).toHaveProperty("callee.name", "withSentryConfig"); + + const { code: exportDefaultCode1 } = generateCode({ + $ast: firstUnwrapAST, + }); + expect(exportDefaultCode1).toMatchInlineSnapshot( + `"withSentryConfig(nextConfig, { org: "nested-org" })"`, + ); + + // Second unwrap ---- + const secondUnwrapAST = unwrapSentryConfigAst(firstUnwrapAST); + expect(secondUnwrapAST.type).toBe("Identifier"); + expect(secondUnwrapAST).toHaveProperty("name", "nextConfig"); + + const { code: exportDefaultCode2 } = generateCode({ + $ast: secondUnwrapAST, + }); + + expect(exportDefaultCode2).toMatchInlineSnapshot(`"nextConfig"`); + }); + + it("should handle simple export without existing withSentryConfig using AST", () => { + const simpleMjsContent = `const nextConfig = {}; + +export default nextConfig;`; + + const mod = parseModule(simpleMjsContent); + const originalAST = mod.exports["default"].$ast; + const unwrappedAst = unwrapSentryConfigAst(originalAST); + expect(unwrappedAst).toBe(originalAST); + mod.exports["default"] = wrapWithSentryConfig( + mod.exports["default"], + mockWithSentryConfigOptionsTemplate, + ); + + const newCode = mod.generate().code; + + // Should have exactly one withSentryConfig call + const withSentryConfigMatches = newCode.match(/withSentryConfig\s*\(/g); + expect(withSentryConfigMatches).toHaveLength(1); + + // Not an inline snapshot: interpolating a shared constant defeats + // vitest's indentation detection for inline snapshots. + expect(newCode).toBe(`const nextConfig = {}; + +export default withSentryConfig(nextConfig, ${sentryOptionsSnapshot});`); + }); + + it("should handle withSentryConfig(nextConfig) without options using AST", () => { + const existingMjsContent = `import { withSentryConfig } from "@sentry/nextjs"; + +const nextConfig = {}; + +export default withSentryConfig(nextConfig);`; + + const mod = parseModule(existingMjsContent); + const originalAST = mod.exports["default"].$ast; + const unwrappedAst = unwrapSentryConfigAst(originalAST); + // Verify it returns the first argument (nextConfig identifier) + expect(unwrappedAst.type).toBe("Identifier"); + expect(unwrappedAst).toHaveProperty("name", "nextConfig"); + + // Simulate the re-wrapping process + const freshMod = + parseModule(`import { withSentryConfig } from "@sentry/nextjs"; + +const nextConfig = {}; + +export default nextConfig;`); + freshMod.exports["default"] = wrapWithSentryConfig( + freshMod.exports["default"], + mockWithSentryConfigOptionsTemplate, + ); + + const newCode = freshMod.generate().code; + + // Should have exactly one withSentryConfig call + const withSentryConfigMatches = newCode.match(/withSentryConfig\s*\(/g); + expect(withSentryConfigMatches).toHaveLength(1); + + expect(newCode).not.toContain("withSentryConfig(withSentryConfig("); + expect(newCode).toMatch(/withSentryConfig\s*\(\s*nextConfig\s*,/); + }); + }); +}); + +const sentryOptionsSnapshot = `{ + // For all available options, see: + // https://docs.sentry.io/platforms/javascript/guides/nextjs/sourcemaps/uploading/bundler-plugin-options/ + + org: "test-org", + + project: "test-project", + + // Only print logs for uploading source maps in CI + silent: !process.env.CI, + + // For all available options, see: + // https://docs.sentry.io/platforms/javascript/guides/nextjs/manual-setup/ + + // Upload a larger set of source maps for prettier stack traces (increases build time) + widenClientFileUpload: true, + + // Uncomment to route browser requests to Sentry through a Next.js rewrite to circumvent ad-blockers. + // This can increase your server load as well as your hosting bill. + // Note: Check that the configured route will not match with your Next.js middleware, otherwise reporting of client- + // side errors will fail. + // tunnelRoute: "/monitoring", + + webpack: { + // Enables automatic instrumentation of Vercel Cron Monitors. (Does not yet work with App Router route handlers.) + // See the following for more information: + // https://docs.sentry.io/product/crons/ + // https://vercel.com/docs/cron-jobs + automaticVercelMonitors: true, + + // Tree-shaking options for reducing bundle size + treeshake: { + // Automatically tree-shake Sentry logger statements to reduce bundle size + removeDebugLogging: true, + }, + } +}`; diff --git a/packages/cli/test/lib/wizard/utils/clack/index.test.ts b/packages/cli/test/lib/wizard/utils/clack/index.test.ts new file mode 100644 index 0000000000..cf8b7c62b8 --- /dev/null +++ b/packages/cli/test/lib/wizard/utils/clack/index.test.ts @@ -0,0 +1,719 @@ +import { + abort, + askForToolConfigPath, + confirmContinueIfNoOrDirtyGitRepo, + createNewConfigFile, + getPackageManager, + installPackage, + printSdkV11MigrationGuideIfOutdated, +} from "../../../../../src/lib/wizard/utils/clack/index.js"; +import { WizardExitError } from "../../../../../src/lib/errors.js"; + +// oxlint-disable-next-line sentry-cli/no-namespace-import -- needed for spyOn mocking +import * as fs from "node:fs"; +// oxlint-disable-next-line sentry-cli/no-namespace-import -- needed for spyOn mocking +import * as ChildProcess from "node:child_process"; +import type { PackageManager } from "../../../../../src/lib/wizard/utils/package-manager.js"; +// oxlint-disable-next-line sentry-cli/no-namespace-import -- needed for spyOn mocking +import * as PackageManagerUtils from "../../../../../src/lib/wizard/utils/package-manager.js"; +// oxlint-disable-next-line sentry-cli/no-namespace-import -- needed for spyOn mocking +import * as GitUtils from "../../../../../src/lib/wizard/utils/git.js"; + +import { + NPM, + PNPM, + YARN_V1, + YARN_V2, +} from "../../../../../src/lib/wizard/utils/package-manager.js"; + +// oxlint-disable-next-line sentry-cli/no-namespace-import -- needed for spyOn mocking +import * as clack from "@clack/prompts"; + +// oxlint-disable-next-line sentry-cli/no-namespace-import -- needed for spyOn mocking +import * as Sentry from "@sentry/node"; + +import { + vi, + it, + describe, + expect, + beforeEach, + type Mocked, + type Mock, + type MockInstance, + afterEach, +} from "vitest"; + +vi.mock("node:child_process", async () => ({ + __esModule: true, + ...(await vi.importActual("node:child_process")), +})); + +vi.mock("node:fs", async () => ({ + __esModule: true, + ...(await vi.importActual("node:fs")), +})); + +vi.mock("@clack/prompts", () => ({ + log: { + info: vi.fn(), + success: vi.fn(), + warn: vi.fn(), + error: vi.fn(), + }, + outro: vi.fn(), + text: vi.fn(), + confirm: vi.fn(), + cancel: vi.fn(), + // passthrough for abortIfCancelled + isCancel: vi.fn().mockReturnValue(false), + spinner: vi + .fn() + .mockImplementation(() => ({ start: vi.fn(), stop: vi.fn() })), + select: vi.fn(), +})); +const clackMock = clack as Mocked; + +vi.mock("../../../../../src/lib/wizard/utils/git.js", () => ({ + isInGitRepo: vi.fn(), + getUncommittedOrUntrackedFilePaths: vi.fn(), +})); + +vi.mock("@sentry/node", async () => { + const actual = + await vi.importActual("@sentry/node"); + return { + ...actual, + setTag: vi.fn(), + captureException: vi.fn(() => "id"), + }; +}); + +function mockUserResponse(fn: Mock, response: unknown) { + fn.mockReturnValueOnce(response); +} + +describe("askForToolConfigPath", () => { + afterEach(() => { + vi.clearAllMocks(); + }); + + it("returns undefined if users have no config file", async () => { + mockUserResponse(clack.confirm as Mock, false); + + const result = await askForToolConfigPath("Webpack", "webpack.config.js"); + + expect(clack.confirm).toHaveBeenCalledWith( + expect.objectContaining({ + message: expect.stringContaining("have a Webpack config file"), + }), + ); + + expect(result).toBeUndefined(); + }); + + it("returns the path if users have a config file and the entered path is valid", async () => { + mockUserResponse(clack.confirm as Mock, true); + mockUserResponse(clack.text as Mock, "my.webpack.config.js"); + + const result = await askForToolConfigPath("Webpack", "webpack.config.js"); + + expect(clack.confirm).toHaveBeenCalledWith( + expect.objectContaining({ + message: expect.stringContaining("have a Webpack config file"), + }), + ); + + expect(clack.text).toHaveBeenCalledWith( + expect.objectContaining({ + message: expect.stringContaining( + "enter the path to your Webpack config file", + ), + }), + ); + + expect(result).toBe("my.webpack.config.js"); + }); +}); + +describe("createNewConfigFile", () => { + afterEach(() => { + vi.clearAllMocks(); + }); + + it("writes the file to disk and returns true if the file was created successfully", async () => { + const writeFileSpy = vi + .spyOn(fs.promises, "writeFile") + .mockImplementation(vi.fn()); + + const filename = "/webpack.config.js"; + const code = "module.exports = {/*config...*/}"; + + const result = await createNewConfigFile(filename, code); + + expect(result).toBe(true); + expect(writeFileSpy).toHaveBeenCalledWith(filename, code); + }); + + it("logs more information if provided as an argument", async () => { + vi.spyOn(fs.promises, "writeFile").mockImplementation(vi.fn()); + + const filename = "/webpack.config.js"; + const code = "module.exports = {/*config...*/}"; + const moreInfo = "More information..."; + + await createNewConfigFile(filename, code, moreInfo); + + expect(clack.log.info).toHaveBeenCalledTimes(1); + expect(clack.log.info).toHaveBeenCalledWith( + expect.stringContaining(moreInfo), + ); + }); + + it("returns false and logs a warning if the file could not be created", async () => { + const writeFileSpy = vi + .spyOn(fs.promises, "writeFile") + .mockImplementation(() => Promise.reject(new Error("Could not write"))); + + const filename = "/webpack.config.js"; + const code = "module.exports = {/*config...*/}"; + + const result = await createNewConfigFile(filename, code); + + expect(result).toBe(false); + expect(writeFileSpy).toHaveBeenCalledWith(filename, code); + expect(clack.log.warn).toHaveBeenCalledTimes(1); + }); + + it("returns false if the passed path is not absolute", async () => { + const result = await createNewConfigFile( + "./relative/webpack.config.js", + "", + ); + + expect(result).toBe(false); + }); +}); + +describe("installPackage", () => { + afterEach(() => { + vi.clearAllMocks(); + }); + + const spawnSpy = vi.spyOn(ChildProcess, "spawn").mockImplementation(() => ({ + // @ts-expect-error - not passing the full object but directly resolving + // to simulate a successful install + on: vi.fn((evt: string, cb: (args) => void) => { + if (evt === "close") { + cb(0); + } + }), + // @ts-expect-error - this is fine + stdout: { on: vi.fn() }, + // @ts-expect-error - this is fine + stderr: { on: vi.fn() }, + })); + + it("force-installs a package if the forceInstall flag is set", async () => { + const packageManagerMock: PackageManager = { + name: "npm", + label: "NPM", + installCommand: "install", + buildCommand: "npm run build", + runScriptCommand: "npm run", + flags: "", + forceInstallFlag: "--force", + detect: vi.fn(), + addOverride: vi.fn(), + }; + + await installPackage({ + alreadyInstalled: false, + packageName: "@some/package", + packageNameDisplayLabel: "@some/package", + forceInstall: true, + askBeforeUpdating: false, + packageManager: packageManagerMock, + }); + + expect(spawnSpy).toHaveBeenCalledWith( + "npm", + ["install", "@some/package", "--force"], + { shell: true, stdio: ["pipe", "pipe", "pipe"] }, + ); + }); + + it.each([false, undefined])( + "doesn't force-install a package if the forceInstall flag is %s", + async (flag) => { + const packageManagerMock: PackageManager = { + name: "npm", + label: "NPM", + installCommand: "install", + buildCommand: "npm run build", + runScriptCommand: "npm run", + flags: "", + forceInstallFlag: "--force", + detect: vi.fn(), + addOverride: vi.fn(), + }; + + await installPackage({ + alreadyInstalled: false, + packageName: "@sentry/sveltekit", + packageNameDisplayLabel: "@sentry/sveltekit", + forceInstall: flag, + askBeforeUpdating: false, + packageManager: packageManagerMock, + }); + + expect(spawnSpy).toHaveBeenCalledWith( + "npm", + ["install", "@sentry/sveltekit"], + { shell: true, stdio: ["pipe", "pipe", "pipe"] }, + ); + }, + ); + + it("adds install flags if defined", async () => { + const packageManagerMock: PackageManager = { + name: "npm", + label: "NPM", + installCommand: "install", + buildCommand: "npm run build", + runScriptCommand: "npm run", + flags: "--ignore-workspace-root-check", + forceInstallFlag: "--force", + detect: vi.fn(), + addOverride: vi.fn(), + }; + + await installPackage({ + alreadyInstalled: false, + packageName: "@some/package", + packageNameDisplayLabel: "@some/package", + forceInstall: true, + askBeforeUpdating: false, + packageManager: packageManagerMock, + }); + + expect(spawnSpy).toHaveBeenCalledWith( + "npm", + + ["install", "@some/package", "--ignore-workspace-root-check", "--force"], + { shell: true, stdio: ["pipe", "pipe", "pipe"] }, + ); + }); + + it("irgnores stdout when installing with Yarn", async () => { + await installPackage({ + alreadyInstalled: false, + packageName: "@sentry/nextjs", + askBeforeUpdating: false, + packageManager: YARN_V2, + }); + + expect(spawnSpy).toHaveBeenCalledWith("yarn", ["add", "@sentry/nextjs"], { + shell: true, + stdio: ["pipe", "ignore", "pipe"], + }); + }); + + it("shows pnpm 11 build approval guidance before installation", async () => { + await installPackage({ + alreadyInstalled: false, + packageName: "@sentry/nextjs", + askBeforeUpdating: false, + packageManager: PNPM, + }); + + expect(clack.log.info).toHaveBeenCalledWith( + expect.stringContaining("pnpm approve-builds"), + ); + }); + + it("writes package manager stdout to the error log file", async () => { + const output = "ERR_PNPM_IGNORED_BUILDS Ignored build scripts: sharp"; + const writeFileSpy = vi + .spyOn(fs, "writeFileSync") + .mockImplementation(vi.fn()); + const dateSpy = vi.spyOn(Date, "now").mockReturnValue(123); + const cwdSpy = vi.spyOn(process, "cwd").mockReturnValue("/project"); + const exitSpy = vi.spyOn(process, "exit").mockImplementation(() => { + throw new Error("exit"); + }); + spawnSpy.mockImplementationOnce(() => ({ + stdout: { + on: vi.fn( + ( + _event: string, + callback: ((data: string) => void) | (() => void), + ) => { + callback(output); + }, + ), + } as unknown as ChildProcess.ChildProcess["stdout"], + // @ts-expect-error - not passing the full ChildProcess object + stderr: { on: vi.fn() }, + // @ts-expect-error - not passing the full ChildProcess object + on: vi.fn( + (event: "error" | "close", callback: (code: number) => void) => { + if (event === "close") { + callback(1); + } + }, + ), + })); + + await expect( + installPackage({ + alreadyInstalled: false, + packageName: "@sentry/nextjs@^10", + askBeforeUpdating: false, + packageManager: PNPM, + }), + ).rejects.toThrow(WizardExitError); + + expect(writeFileSpy).toHaveBeenCalledWith( + "/project/sentry-wizard-installation-error-123.log", + output, + { encoding: "utf8" }, + ); + expect(clack.log.error).toHaveBeenCalledWith( + expect.not.stringContaining(output), + ); + expect(clack.log.error).toHaveBeenCalledWith( + expect.stringContaining("sentry-wizard-installation-error-*.log"), + ); + + writeFileSpy.mockRestore(); + dateSpy.mockRestore(); + cwdSpy.mockRestore(); + exitSpy.mockRestore(); + }); +}); + +describe("printSdkV11MigrationGuideIfOutdated", () => { + afterEach(() => { + vi.clearAllMocks(); + }); + + it.each(["^10.0.0", "10.5.2", "~9.1.0", ">=8.0.0 <11.0.0"])( + "warns and links the migration guide for the installed range %s", + (version) => { + printSdkV11MigrationGuideIfOutdated("@sentry/nextjs", { + dependencies: { "@sentry/nextjs": version }, + }); + + expect(clackMock.log.warn).toHaveBeenCalledTimes(1); + expect(clackMock.log.warn).toHaveBeenCalledWith( + expect.stringContaining( + "https://docs.sentry.io/platforms/javascript/guides/nextjs/migration/v10-to-v11/", + ), + ); + }, + ); + + it.each([ + ["@sentry/angular", "angular"], + ["@sentry/cloudflare", "cloudflare"], + ["@sentry/nextjs", "nextjs"], + ["@sentry/nuxt", "nuxt"], + ["@sentry/react-router", "react-router"], + ["@sentry/remix", "remix"], + ["@sentry/sveltekit", "sveltekit"], + ])("links the %s migration guide", (packageName, guide) => { + printSdkV11MigrationGuideIfOutdated(packageName, { + dependencies: { [packageName]: "^10.2.0" }, + }); + + expect(clackMock.log.warn).toHaveBeenCalledWith( + expect.stringContaining( + `https://docs.sentry.io/platforms/javascript/guides/${guide}/migration/v10-to-v11/`, + ), + ); + }); + + it("falls back to the generic migration guide for other SDKs", () => { + printSdkV11MigrationGuideIfOutdated("@sentry/browser", { + dependencies: { "@sentry/browser": "^10.0.0" }, + }); + + expect(clackMock.log.warn).toHaveBeenCalledWith( + expect.stringContaining( + "https://docs.sentry.io/platforms/javascript/migration/v10-to-v11/", + ), + ); + }); + + it.each([ + ["the SDK is not installed", {}], + [ + "the SDK is already on v11", + { dependencies: { "@sentry/nextjs": "^11.0.0" } }, + ], + [ + "the installed range is not a valid semver range", + { + dependencies: { "@sentry/nextjs": "workspace:*" }, + }, + ], + ])("stays silent when %s", (_case, packageJson) => { + printSdkV11MigrationGuideIfOutdated("@sentry/nextjs", packageJson); + + expect(clackMock.log.warn).not.toHaveBeenCalled(); + }); +}); + +describe("abort", () => { + beforeEach(() => { + vi.clearAllMocks(); + }); + + it("stops the wizard with an error exit code by default", async () => { + const error = await abort().catch((e: unknown) => e); + + expect(error).toBeInstanceOf(WizardExitError); + expect((error as WizardExitError).exitCode).toBe(1); + expect(clackMock.outro).toHaveBeenCalledTimes(1); + expect(clackMock.outro).toHaveBeenCalledWith("Wizard setup cancelled."); + expect(Sentry.setTag).toHaveBeenCalledWith("wizard.outcome", "aborted"); + }); + + it("stops the wizard with a custom exit code and message if provided", async () => { + const error = await abort("Bye", 0).catch((e: unknown) => e); + + expect((error as WizardExitError).exitCode).toBe(0); + expect(clackMock.outro).toHaveBeenCalledTimes(1); + expect(clackMock.outro).toHaveBeenCalledWith("Bye"); + expect(Sentry.setTag).toHaveBeenCalledWith("wizard.outcome", "cancelled"); + }); +}); + +describe("getPackageManager", () => { + afterEach(() => { + vi.clearAllMocks(); + // @ts-expect-error - this variable is set by the wizard + delete global.__sentry_wizard_cached_package_manager; + }); + + it("returns the auto-detected package manager", async () => { + const detectPacManSpy = vi + .spyOn(PackageManagerUtils, "_detectPackageManger") + .mockReturnValueOnce(YARN_V1); + + const packageManager = await getPackageManager(); + + expect(detectPacManSpy).toHaveBeenCalledTimes(1); + + expect(packageManager).toBe(YARN_V1); + }); + + it("caches the auto-detected package manager", async () => { + const detectPacManSpy = vi + .spyOn(PackageManagerUtils, "_detectPackageManger") + .mockReturnValueOnce(YARN_V1); + + const packageManager1 = await getPackageManager(); + const packageManager2 = await getPackageManager(); + + expect(detectPacManSpy).toHaveBeenCalledTimes(1); + + expect(packageManager1).toBe(YARN_V1); + expect(packageManager2).toBe(YARN_V1); + }); + + describe("when auto detection fails", () => { + it("returns a fallback package manager if fallback is specified", async () => { + const detectPacManSpy = vi + .spyOn(PackageManagerUtils, "_detectPackageManger") + .mockReturnValueOnce(null); + + const packageManager = await getPackageManager(YARN_V2); + + expect(detectPacManSpy).toHaveBeenCalledTimes(1); + + expect(packageManager).toBe(YARN_V2); + }); + + it("doesn't cache the fallback package manager", async () => { + const detectPacManSpy = vi + .spyOn(PackageManagerUtils, "_detectPackageManger") + .mockReturnValue(null); + + const packageManager1 = await getPackageManager(YARN_V2); + const packageManager2 = await getPackageManager(NPM); + + expect(detectPacManSpy).toHaveBeenCalledTimes(2); + + expect(packageManager1).toBe(YARN_V2); + expect(packageManager2).toBe(NPM); + }); + + it("returns the user-selected package manager if no fallback is provided", async () => { + const detectPacManSpy = vi + .spyOn(PackageManagerUtils, "_detectPackageManger") + .mockReturnValueOnce(null); + + clackMock.select.mockReturnValueOnce(Promise.resolve(PNPM)); + + const packageManager = await getPackageManager(); + + expect(detectPacManSpy).toHaveBeenCalledTimes(1); + expect(packageManager).toBe(PNPM); + }); + + it("caches the user-selected package manager", async () => { + const detectPacManSpy = vi + .spyOn(PackageManagerUtils, "_detectPackageManger") + .mockReturnValueOnce(null); + + clackMock.select.mockReturnValueOnce(Promise.resolve(PNPM)); + + const packageManager1 = await getPackageManager(); + const packageManager2 = await getPackageManager(); + + expect(detectPacManSpy).toHaveBeenCalledTimes(1); + expect(clackMock.select).toHaveBeenCalledTimes(1); + + expect(packageManager1).toBe(PNPM); + expect(packageManager2).toBe(PNPM); + }); + }); +}); + +describe("confirmContinueIfNoOrDirtyGitRepo", () => { + // process.exit is mocked to throw so that abort() halts execution the same + // way it would terminate the process in production, instead of falling + // through to the interactive prompt. + let exitSpy: MockInstance; + + beforeEach(() => { + vi.clearAllMocks(); + // Drain any leftover `mockReturnValueOnce` values queued by earlier + // suites; `clearAllMocks` clears call history but not the once-queue. + clackMock.confirm.mockReset(); + exitSpy = vi.spyOn(process, "exit").mockImplementation(() => { + throw new Error("exit"); + }); + }); + + afterEach(() => { + exitSpy.mockRestore(); + }); + + describe("non-interactive mode", () => { + it("aborts without prompting when the project is not a git repository", async () => { + (GitUtils.isInGitRepo as Mock).mockReturnValue(false); + + await expect( + confirmContinueIfNoOrDirtyGitRepo({ + ignoreGitChanges: undefined, + cwd: undefined, + nonInteractive: true, + }), + ).rejects.toThrow(WizardExitError); + + expect(clack.log.error).toHaveBeenCalledWith( + expect.stringContaining( + "not inside a git repository in non-interactive mode", + ), + ); + expect(Sentry.setTag).toHaveBeenCalledWith("continue-without-git", false); + expect(clack.confirm).not.toHaveBeenCalled(); + }); + + it("aborts without prompting when the repository has uncommitted or untracked files", async () => { + (GitUtils.isInGitRepo as Mock).mockReturnValue(true); + (GitUtils.getUncommittedOrUntrackedFilePaths as Mock).mockReturnValue([ + "src/index.ts", + ]); + + await expect( + confirmContinueIfNoOrDirtyGitRepo({ + ignoreGitChanges: false, + cwd: undefined, + nonInteractive: true, + }), + ).rejects.toThrow(WizardExitError); + + expect(clack.log.warn).toHaveBeenCalledWith( + expect.stringContaining("uncommitted or untracked files"), + ); + expect(clack.log.error).toHaveBeenCalledWith( + expect.stringContaining( + "uncommitted or untracked files in non-interactive mode", + ), + ); + expect(Sentry.setTag).toHaveBeenCalledWith( + "continue-with-dirty-repo", + false, + ); + expect(clack.confirm).not.toHaveBeenCalled(); + }); + }); + + describe("interactive mode (default)", () => { + it("prompts to continue when the project is not a git repository", async () => { + (GitUtils.isInGitRepo as Mock).mockReturnValue(false); + mockUserResponse(clack.confirm as Mock, true); + + await confirmContinueIfNoOrDirtyGitRepo({ + ignoreGitChanges: undefined, + cwd: undefined, + }); + + expect(clack.confirm).toHaveBeenCalledWith( + expect.objectContaining({ + message: expect.stringContaining("not inside a git repository"), + }), + ); + expect(clack.log.error).not.toHaveBeenCalled(); + expect(exitSpy).not.toHaveBeenCalled(); + expect(Sentry.setTag).toHaveBeenCalledWith("continue-without-git", true); + }); + + it("prompts to continue when the repository has uncommitted or untracked files", async () => { + (GitUtils.isInGitRepo as Mock).mockReturnValue(true); + (GitUtils.getUncommittedOrUntrackedFilePaths as Mock).mockReturnValue([ + "src/index.ts", + ]); + mockUserResponse(clack.confirm as Mock, true); + + await confirmContinueIfNoOrDirtyGitRepo({ + ignoreGitChanges: false, + cwd: undefined, + nonInteractive: false, + }); + + expect(clack.log.warn).toHaveBeenCalledWith( + expect.stringContaining("uncommitted or untracked files"), + ); + expect(clack.confirm).toHaveBeenCalledWith( + expect.objectContaining({ + message: expect.stringContaining("continue anyway"), + }), + ); + expect(clack.log.error).not.toHaveBeenCalled(); + expect(exitSpy).not.toHaveBeenCalled(); + expect(Sentry.setTag).toHaveBeenCalledWith( + "continue-with-dirty-repo", + true, + ); + }); + + it("does not prompt or abort for a clean git repository", async () => { + (GitUtils.isInGitRepo as Mock).mockReturnValue(true); + (GitUtils.getUncommittedOrUntrackedFilePaths as Mock).mockReturnValue([]); + + await confirmContinueIfNoOrDirtyGitRepo({ + ignoreGitChanges: undefined, + cwd: undefined, + }); + + expect(clack.confirm).not.toHaveBeenCalled(); + expect(clack.log.warn).not.toHaveBeenCalled(); + expect(exitSpy).not.toHaveBeenCalled(); + }); + }); +}); diff --git a/packages/cli/test/lib/wizard/utils/clack/mcp-config.test.ts b/packages/cli/test/lib/wizard/utils/clack/mcp-config.test.ts new file mode 100644 index 0000000000..af614d9793 --- /dev/null +++ b/packages/cli/test/lib/wizard/utils/clack/mcp-config.test.ts @@ -0,0 +1,1049 @@ +import { + describe, + expect, + it, + vi, + beforeEach, + afterEach, + type Mock, +} from "vitest"; +// oxlint-disable-next-line sentry-cli/no-namespace-import -- needed for spyOn mocking +import * as fs from "node:fs"; +// oxlint-disable-next-line sentry-cli/no-namespace-import -- needed for spyOn mocking +import * as path from "node:path"; +// oxlint-disable-next-line sentry-cli/no-namespace-import -- needed for spyOn mocking +import * as childProcess from "node:child_process"; +import { offerProjectScopedMcpConfig } from "../../../../../src/lib/wizard/utils/clack/mcp-config.js"; + +// Mock types for better type safety +type ConfigContent = { + mcpServers?: Record; + servers?: Record; + mcp?: Record; + $schema?: string; + otherProperty?: string; +}; + +// Mock the clack utils which wrap the prompts +vi.mock("../../../../../src/lib/wizard/utils/clack/index.js", () => ({ + abortIfCancelled: vi.fn((value: unknown) => Promise.resolve(value)), + showCopyPasteInstructions: vi.fn(), +})); + +// Mock the external dependencies +vi.mock("@clack/prompts", () => ({ + confirm: vi.fn(), + select: vi.fn(), + multiselect: vi.fn(), + isCancel: vi.fn(() => false), + cancel: vi.fn(), + log: { + success: vi.fn(), + info: vi.fn(), + warn: vi.fn(), + }, +})); + +vi.mock("node:fs"); +vi.mock("node:child_process"); + +describe("mcp-config", () => { + // Helper to get mocked modules with proper typing + type ClackMocks = { + select: ReturnType; + multiselect: ReturnType; + log: { + success: ReturnType; + info: ReturnType; + warn: ReturnType; + }; + }; + + type ClackUtilsMocks = { + abortIfCancelled: Mock<(value: unknown) => Promise>; + showCopyPasteInstructions: ReturnType; + }; + + const getMocks = async () => { + const clack = await vi.importMock("@clack/prompts"); + const clackUtils = await vi.importMock( + "../../../../../src/lib/wizard/utils/clack/index.js", + ); + return { clack, clackUtils }; + }; + + beforeEach(() => { + vi.clearAllMocks(); + }); + + afterEach(() => { + vi.restoreAllMocks(); + }); + + describe("offerProjectScopedMcpConfig", () => { + it("should return early if user declines MCP config", async () => { + const { clack, clackUtils } = await getMocks(); + + vi.mocked(clack.select).mockResolvedValue("no"); + vi.mocked(clackUtils.abortIfCancelled).mockImplementation( + (value: unknown) => Promise.resolve(value), + ); + + await offerProjectScopedMcpConfig(); + + expect(clack.select).toHaveBeenCalledWith( + expect.objectContaining({ + message: expect.stringContaining( + "Optionally add a project-scoped MCP server configuration", + ) as string, + options: expect.arrayContaining([ + expect.objectContaining({ value: "yes" }), + expect.objectContaining({ value: "no" }), + expect.objectContaining({ value: "explain" }), + ]) as unknown[], + initialValue: "yes", + }), + ); + }); + + it("should configure for Cursor when selected", async () => { + const { clack, clackUtils } = await getMocks(); + + vi.mocked(clack.select).mockResolvedValueOnce("yes"); + vi.mocked(clack.multiselect).mockResolvedValueOnce(["cursor"]); + vi.mocked(clackUtils.abortIfCancelled).mockImplementation( + (value: unknown) => Promise.resolve(value), + ); + + const mockReadFile = vi + .fn() + .mockRejectedValue(new Error("File not found")); + const mockWriteFile = vi.fn().mockResolvedValue(undefined); + const mockMkdirSync = vi.fn(); + + vi.spyOn(fs.promises, "readFile").mockImplementation(mockReadFile); + vi.spyOn(fs.promises, "writeFile").mockImplementation(mockWriteFile); + vi.spyOn(fs, "mkdirSync").mockImplementation(mockMkdirSync); + + await offerProjectScopedMcpConfig(); + + expect(clack.multiselect).toHaveBeenCalledWith( + expect.objectContaining({ + message: "Which editor(s) do you want to configure?", + options: expect.arrayContaining([ + expect.objectContaining({ value: "cursor" }), + expect.objectContaining({ value: "vscode" }), + expect.objectContaining({ value: "claudeCode" }), + ]) as unknown[], + }), + ); + + expect(mockWriteFile).toHaveBeenCalledWith( + expect.stringContaining(".cursor/mcp.json"), + expect.stringContaining('"mcpServers"'), + "utf8", + ); + + expect(clack.log.success).toHaveBeenCalledWith( + expect.stringContaining(".cursor/mcp.json"), + ); + expect(clack.log.success).toHaveBeenCalledWith( + "Added project-scoped Sentry MCP configuration for Cursor.", + ); + expect(clack.log.info).toHaveBeenCalledWith( + expect.stringContaining("reload your editor"), + ); + }); + + it("should configure for VS Code when selected", async () => { + const { clack, clackUtils } = await getMocks(); + + vi.mocked(clack.select).mockResolvedValueOnce("yes"); + vi.mocked(clack.multiselect).mockResolvedValueOnce(["vscode"]); + vi.mocked(clackUtils.abortIfCancelled).mockImplementation( + (value: unknown) => Promise.resolve(value), + ); + + const mockReadFile = vi + .fn() + .mockRejectedValue(new Error("File not found")); + const mockWriteFile = vi.fn().mockResolvedValue(undefined); + const mockMkdirSync = vi.fn(); + + vi.spyOn(fs.promises, "readFile").mockImplementation(mockReadFile); + vi.spyOn(fs.promises, "writeFile").mockImplementation(mockWriteFile); + vi.spyOn(fs, "mkdirSync").mockImplementation(mockMkdirSync); + + await offerProjectScopedMcpConfig(); + + expect(mockWriteFile).toHaveBeenCalledWith( + expect.stringContaining(".vscode/mcp.json"), + expect.stringContaining('"servers"'), + "utf8", + ); + + expect(clack.log.success).toHaveBeenCalledWith( + expect.stringContaining(".vscode/mcp.json"), + ); + }); + + it("should configure for Claude Code when selected", async () => { + const { clack, clackUtils } = await getMocks(); + + vi.mocked(clack.select).mockResolvedValueOnce("yes"); + vi.mocked(clack.multiselect).mockResolvedValueOnce(["claudeCode"]); + vi.mocked(clackUtils.abortIfCancelled).mockImplementation( + (value: unknown) => Promise.resolve(value), + ); + + const mockReadFile = vi + .fn() + .mockRejectedValue(new Error("File not found")); + const mockWriteFile = vi.fn().mockResolvedValue(undefined); + const mockMkdirSync = vi.fn(); + + vi.spyOn(fs.promises, "readFile").mockImplementation(mockReadFile); + vi.spyOn(fs.promises, "writeFile").mockImplementation(mockWriteFile); + vi.spyOn(fs, "mkdirSync").mockImplementation(mockMkdirSync); + + await offerProjectScopedMcpConfig(); + + expect(mockWriteFile).toHaveBeenCalledWith( + expect.stringContaining(".mcp.json"), + expect.stringContaining('"mcpServers"'), + "utf8", + ); + + expect(clack.log.success).toHaveBeenCalledWith( + expect.stringContaining(".mcp.json"), + ); + }); + + it("should update existing Cursor config file", async () => { + const { clack, clackUtils } = await getMocks(); + + vi.mocked(clack.select).mockResolvedValueOnce("yes"); + vi.mocked(clack.multiselect).mockResolvedValueOnce(["cursor"]); + vi.mocked(clackUtils.abortIfCancelled).mockImplementation( + (value: unknown) => Promise.resolve(value), + ); + + const existingConfig = JSON.stringify({ + mcpServers: { + OtherServer: { + url: "https://other.example.com", + }, + }, + }); + + const mockReadFile = vi.fn().mockResolvedValue(existingConfig); + const mockWriteFile = vi.fn().mockResolvedValue(undefined); + const mockMkdirSync = vi.fn(); + + vi.spyOn(fs.promises, "readFile").mockImplementation(mockReadFile); + vi.spyOn(fs.promises, "writeFile").mockImplementation(mockWriteFile); + vi.spyOn(fs, "mkdirSync").mockImplementation(mockMkdirSync); + + await offerProjectScopedMcpConfig(); + + expect(mockReadFile).toHaveBeenCalled(); + expect(mockWriteFile).toHaveBeenCalledWith( + expect.stringContaining(".cursor/mcp.json"), + expect.stringContaining("Sentry"), + "utf8", + ); + + const writtenContent = JSON.parse( + mockWriteFile.mock.calls[0]?.[1] as string, + ) as ConfigContent; + expect(writtenContent.mcpServers).toHaveProperty("OtherServer"); + expect(writtenContent.mcpServers).toHaveProperty("Sentry"); + + expect(clack.log.success).toHaveBeenCalledWith( + "Updated .cursor/mcp.json", + ); + }); + + it("should update existing VS Code config file", async () => { + const { clack, clackUtils } = await getMocks(); + + vi.mocked(clack.select).mockResolvedValueOnce("yes"); + vi.mocked(clack.multiselect).mockResolvedValueOnce(["vscode"]); + vi.mocked(clackUtils.abortIfCancelled).mockImplementation( + (value: unknown) => Promise.resolve(value), + ); + + const existingConfig = JSON.stringify({ + servers: { + OtherServer: { + url: "https://other.example.com", + type: "http", + }, + }, + }); + + const mockReadFile = vi.fn().mockResolvedValue(existingConfig); + const mockWriteFile = vi.fn().mockResolvedValue(undefined); + const mockMkdirSync = vi.fn(); + + vi.spyOn(fs.promises, "readFile").mockImplementation(mockReadFile); + vi.spyOn(fs.promises, "writeFile").mockImplementation(mockWriteFile); + vi.spyOn(fs, "mkdirSync").mockImplementation(mockMkdirSync); + + await offerProjectScopedMcpConfig(); + + const writtenContent = JSON.parse( + mockWriteFile.mock.calls[0]?.[1] as string, + ) as ConfigContent; + expect(writtenContent.servers).toHaveProperty("OtherServer"); + expect(writtenContent.servers).toHaveProperty("Sentry"); + expect(writtenContent.servers?.["Sentry"]).toHaveProperty("type", "http"); + + expect(clack.log.success).toHaveBeenCalledWith( + "Updated .vscode/mcp.json", + ); + }); + + it("should update existing Claude Code config file", async () => { + const { clack, clackUtils } = await getMocks(); + + vi.mocked(clack.select).mockResolvedValueOnce("yes"); + vi.mocked(clack.multiselect).mockResolvedValueOnce(["claudeCode"]); + vi.mocked(clackUtils.abortIfCancelled).mockImplementation( + (value: unknown) => Promise.resolve(value), + ); + + const existingConfig = JSON.stringify({ + mcpServers: { + OtherServer: { + url: "https://other.example.com", + }, + }, + }); + + const mockReadFile = vi.fn().mockResolvedValue(existingConfig); + const mockWriteFile = vi.fn().mockResolvedValue(undefined); + const mockMkdirSync = vi.fn(); + + vi.spyOn(fs.promises, "readFile").mockImplementation(mockReadFile); + vi.spyOn(fs.promises, "writeFile").mockImplementation(mockWriteFile); + vi.spyOn(fs, "mkdirSync").mockImplementation(mockMkdirSync); + + await offerProjectScopedMcpConfig(); + + const writtenContent = JSON.parse( + mockWriteFile.mock.calls[0]?.[1] as string, + ) as ConfigContent; + expect(writtenContent.mcpServers).toHaveProperty("OtherServer"); + expect(writtenContent.mcpServers).toHaveProperty("Sentry"); + + expect(clack.log.success).toHaveBeenCalledWith("Updated .mcp.json"); + }); + + it("should configure for OpenCode when selected", async () => { + const { clack, clackUtils } = await getMocks(); + + vi.mocked(clack.select).mockResolvedValueOnce("yes"); + vi.mocked(clack.multiselect).mockResolvedValueOnce(["openCode"]); + vi.mocked(clackUtils.abortIfCancelled).mockImplementation( + (value: unknown) => Promise.resolve(value), + ); + + const mockReadFile = vi + .fn() + .mockRejectedValue(new Error("File not found")); + const mockWriteFile = vi.fn().mockResolvedValue(undefined); + const mockMkdirSync = vi.fn(); + + vi.spyOn(fs.promises, "readFile").mockImplementation(mockReadFile); + vi.spyOn(fs.promises, "writeFile").mockImplementation(mockWriteFile); + vi.spyOn(fs, "mkdirSync").mockImplementation(mockMkdirSync); + + await offerProjectScopedMcpConfig(); + + expect(mockWriteFile).toHaveBeenCalledWith( + expect.stringContaining("opencode.json"), + expect.stringContaining('"mcp"'), + "utf8", + ); + + // Verify the written content has the correct structure for OpenCode + const writtenContent = JSON.parse( + mockWriteFile.mock.calls[0]?.[1] as string, + ) as ConfigContent; + expect(writtenContent.$schema).toBe("https://opencode.ai/config.json"); + expect(writtenContent.mcp).toHaveProperty("Sentry"); + expect(writtenContent.mcp?.["Sentry"]).toHaveProperty("type", "remote"); + expect(writtenContent.mcp?.["Sentry"]).toHaveProperty("url"); + expect(writtenContent.mcp?.["Sentry"]?.oauth).toEqual({}); + + expect(clack.log.success).toHaveBeenCalledWith( + expect.stringContaining("opencode.json"), + ); + expect(clack.log.success).toHaveBeenCalledWith( + "Added project-scoped Sentry MCP configuration for OpenCode.", + ); + expect(clack.log.info).toHaveBeenCalledWith( + expect.stringContaining("restart OpenCode"), + ); + }); + + it("should update existing OpenCode config file", async () => { + const { clack, clackUtils } = await getMocks(); + + vi.mocked(clack.select).mockResolvedValueOnce("yes"); + vi.mocked(clack.multiselect).mockResolvedValueOnce(["openCode"]); + vi.mocked(clackUtils.abortIfCancelled).mockImplementation( + (value: unknown) => Promise.resolve(value), + ); + + const existingConfig = JSON.stringify({ + mcp: { + OtherServer: { + type: "remote", + url: "https://other.example.com", + }, + }, + }); + + const mockReadFile = vi.fn().mockResolvedValue(existingConfig); + const mockWriteFile = vi.fn().mockResolvedValue(undefined); + const mockMkdirSync = vi.fn(); + + vi.spyOn(fs.promises, "readFile").mockImplementation(mockReadFile); + vi.spyOn(fs.promises, "writeFile").mockImplementation(mockWriteFile); + vi.spyOn(fs, "mkdirSync").mockImplementation(mockMkdirSync); + + await offerProjectScopedMcpConfig(); + + const writtenContent = JSON.parse( + mockWriteFile.mock.calls[0]?.[1] as string, + ) as ConfigContent; + expect(writtenContent.mcp).toHaveProperty("OtherServer"); + expect(writtenContent.mcp).toHaveProperty("Sentry"); + expect(writtenContent.mcp?.["Sentry"]).toHaveProperty("type", "remote"); + + expect(clack.log.success).toHaveBeenCalledWith("Updated opencode.json"); + }); + + it("should handle file write errors gracefully for OpenCode", async () => { + const { clack, clackUtils } = await getMocks(); + + vi.mocked(clack.select).mockResolvedValueOnce("yes"); + vi.mocked(clack.multiselect).mockResolvedValueOnce(["openCode"]); + vi.mocked(clackUtils.abortIfCancelled).mockImplementation( + (value: unknown) => Promise.resolve(value), + ); + + const mockReadFile = vi + .fn() + .mockRejectedValue(new Error("File not found")); + const mockWriteFile = vi + .fn() + .mockRejectedValue(new Error("Permission denied")); + const mockMkdirSync = vi.fn(); + + vi.spyOn(fs.promises, "readFile").mockImplementation(mockReadFile); + vi.spyOn(fs.promises, "writeFile").mockImplementation(mockWriteFile); + vi.spyOn(fs, "mkdirSync").mockImplementation(mockMkdirSync); + + await expect(offerProjectScopedMcpConfig()).resolves.toBeUndefined(); + + expect(clack.log.warn).toHaveBeenCalledWith( + expect.stringContaining("Failed to write MCP config for openCode"), + ); + + expect(clackUtils.showCopyPasteInstructions).toHaveBeenCalledWith( + expect.objectContaining({ + filename: "opencode.json", + codeSnippet: expect.stringContaining('"mcp"') as string, + hint: "create the file if it does not exist", + }), + ); + }); + + it("should handle file write errors gracefully for Cursor", async () => { + const { clack, clackUtils } = await getMocks(); + + vi.mocked(clack.select).mockResolvedValueOnce("yes"); + vi.mocked(clack.multiselect).mockResolvedValueOnce(["cursor"]); + vi.mocked(clackUtils.abortIfCancelled).mockImplementation( + (value: unknown) => Promise.resolve(value), + ); + + const mockReadFile = vi + .fn() + .mockRejectedValue(new Error("File not found")); + const mockWriteFile = vi + .fn() + .mockRejectedValue(new Error("Permission denied")); + const mockMkdirSync = vi.fn(); + + vi.spyOn(fs.promises, "readFile").mockImplementation(mockReadFile); + vi.spyOn(fs.promises, "writeFile").mockImplementation(mockWriteFile); + vi.spyOn(fs, "mkdirSync").mockImplementation(mockMkdirSync); + + await expect(offerProjectScopedMcpConfig()).resolves.toBeUndefined(); + + expect(clack.log.warn).toHaveBeenCalledWith( + expect.stringContaining("Failed to write MCP config"), + ); + + expect(clackUtils.showCopyPasteInstructions).toHaveBeenCalledWith( + expect.objectContaining({ + filename: path.join(".cursor", "mcp.json"), + codeSnippet: expect.stringContaining("mcpServers") as string, + hint: "create the file if it does not exist", + }), + ); + }); + + it("should handle file write errors gracefully for VS Code", async () => { + const { clack, clackUtils } = await getMocks(); + + vi.mocked(clack.select).mockResolvedValueOnce("yes"); + vi.mocked(clack.multiselect).mockResolvedValueOnce(["vscode"]); + vi.mocked(clackUtils.abortIfCancelled).mockImplementation( + (value: unknown) => Promise.resolve(value), + ); + + const mockReadFile = vi + .fn() + .mockRejectedValue(new Error("File not found")); + const mockWriteFile = vi + .fn() + .mockRejectedValue(new Error("Permission denied")); + const mockMkdirSync = vi.fn(); + + vi.spyOn(fs.promises, "readFile").mockImplementation(mockReadFile); + vi.spyOn(fs.promises, "writeFile").mockImplementation(mockWriteFile); + vi.spyOn(fs, "mkdirSync").mockImplementation(mockMkdirSync); + + await expect(offerProjectScopedMcpConfig()).resolves.toBeUndefined(); + + expect(clackUtils.showCopyPasteInstructions).toHaveBeenCalledWith( + expect.objectContaining({ + filename: path.join(".vscode", "mcp.json"), + codeSnippet: expect.stringContaining("servers") as string, + hint: "create the file if it does not exist", + }), + ); + }); + + it("should handle file write errors gracefully for Claude Code", async () => { + const { clack, clackUtils } = await getMocks(); + + vi.mocked(clack.select).mockResolvedValueOnce("yes"); + vi.mocked(clack.multiselect).mockResolvedValueOnce(["claudeCode"]); + vi.mocked(clackUtils.abortIfCancelled).mockImplementation( + (value: unknown) => Promise.resolve(value), + ); + + const mockReadFile = vi + .fn() + .mockRejectedValue(new Error("File not found")); + const mockWriteFile = vi + .fn() + .mockRejectedValue(new Error("Permission denied")); + const mockMkdirSync = vi.fn(); + + vi.spyOn(fs.promises, "readFile").mockImplementation(mockReadFile); + vi.spyOn(fs.promises, "writeFile").mockImplementation(mockWriteFile); + vi.spyOn(fs, "mkdirSync").mockImplementation(mockMkdirSync); + + await expect(offerProjectScopedMcpConfig()).resolves.toBeUndefined(); + + expect(clackUtils.showCopyPasteInstructions).toHaveBeenCalledWith( + expect.objectContaining({ + filename: ".mcp.json", + codeSnippet: expect.stringContaining("mcpServers") as string, + hint: "create the file if it does not exist", + }), + ); + }); + + it("should handle update errors and show copy-paste instructions", async () => { + const { clack, clackUtils } = await getMocks(); + + vi.mocked(clack.select).mockResolvedValueOnce("yes"); + vi.mocked(clack.multiselect).mockResolvedValueOnce(["cursor"]); + vi.mocked(clackUtils.abortIfCancelled).mockImplementation( + (value: unknown) => Promise.resolve(value), + ); + + // Mock existing file and simulate write error during update + const existingConfig = JSON.stringify({ + mcpServers: { + OtherServer: { + url: "https://other.example.com", + }, + }, + }); + + const mockReadFile = vi.fn().mockResolvedValue(existingConfig); + const mockWriteFile = vi + .fn() + .mockRejectedValue(new Error("Write failed during update")); + const mockMkdirSync = vi.fn(); + + vi.spyOn(fs.promises, "readFile").mockImplementation(mockReadFile); + vi.spyOn(fs.promises, "writeFile").mockImplementation(mockWriteFile); + vi.spyOn(fs, "mkdirSync").mockImplementation(mockMkdirSync); + + await expect(offerProjectScopedMcpConfig()).resolves.toBeUndefined(); + + expect(clack.log.warn).toHaveBeenCalledWith( + expect.stringContaining("Failed to write MCP config"), + ); + + expect(clackUtils.showCopyPasteInstructions).toHaveBeenCalled(); + }); + + it("should handle mkdirSync errors", async () => { + const { clack, clackUtils } = await getMocks(); + + vi.mocked(clack.select).mockResolvedValueOnce("yes"); + vi.mocked(clack.multiselect).mockResolvedValueOnce(["cursor"]); + vi.mocked(clackUtils.abortIfCancelled).mockImplementation( + (value: unknown) => Promise.resolve(value), + ); + + const mockReadFile = vi + .fn() + .mockRejectedValue(new Error("File not found")); + const mockWriteFile = vi.fn().mockResolvedValue(undefined); + const mockMkdirSync = vi.fn().mockImplementation(() => { + throw new Error("Permission denied"); + }); + + vi.spyOn(fs.promises, "readFile").mockImplementation(mockReadFile); + vi.spyOn(fs.promises, "writeFile").mockImplementation(mockWriteFile); + vi.spyOn(fs, "mkdirSync").mockImplementation(mockMkdirSync); + + await expect(offerProjectScopedMcpConfig()).resolves.toBeUndefined(); + + expect(clack.log.warn).toHaveBeenCalledWith( + expect.stringContaining("Failed to write MCP config"), + ); + + expect(clackUtils.showCopyPasteInstructions).toHaveBeenCalled(); + }); + + it("should create config with empty servers/mcpServers when existing config lacks them", async () => { + const { clack, clackUtils } = await getMocks(); + + vi.mocked(clack.select).mockResolvedValueOnce("yes"); + vi.mocked(clack.multiselect).mockResolvedValueOnce(["vscode"]); + vi.mocked(clackUtils.abortIfCancelled).mockImplementation( + (value: unknown) => Promise.resolve(value), + ); + + const existingConfig = JSON.stringify({ + otherProperty: "value", + }); + + const mockReadFile = vi.fn().mockResolvedValue(existingConfig); + const mockWriteFile = vi.fn().mockResolvedValue(undefined); + const mockMkdirSync = vi.fn(); + + vi.spyOn(fs.promises, "readFile").mockImplementation(mockReadFile); + vi.spyOn(fs.promises, "writeFile").mockImplementation(mockWriteFile); + vi.spyOn(fs, "mkdirSync").mockImplementation(mockMkdirSync); + + await offerProjectScopedMcpConfig(); + + const writtenContent = JSON.parse( + mockWriteFile.mock.calls[0]?.[1] as string, + ) as ConfigContent; + expect(writtenContent).toHaveProperty("otherProperty", "value"); + expect(writtenContent).toHaveProperty("servers"); + expect(writtenContent.servers).toHaveProperty("Sentry"); + + expect(clack.log.success).toHaveBeenCalledWith( + "Updated .vscode/mcp.json", + ); + }); + + it("should show config for JetBrains IDEs with clipboard copy", async () => { + const { clack, clackUtils } = await getMocks(); + + vi.mocked(clack.select) + .mockResolvedValueOnce("yes") + .mockResolvedValueOnce(true); // For the clipboard copy prompt + vi.mocked(clack.multiselect).mockResolvedValueOnce(["jetbrains"]); + + vi.mocked(clackUtils.abortIfCancelled).mockImplementation( + (value: unknown) => Promise.resolve(value), + ); + + // Mock clipboard copy + const mockSpawn = vi.fn().mockReturnValue({ + stdin: { + write: vi.fn(), + end: vi.fn(), + }, + on: vi.fn((event, callback: (code?: number) => void) => { + if (event === "close") callback(0); + }), + }); + vi.spyOn(childProcess, "spawn").mockImplementation(mockSpawn); + + // Mock console.log to capture output + const consoleSpy = vi + .spyOn(process.stdout, "write") + .mockImplementation(() => true); + + await offerProjectScopedMcpConfig(); + + expect(clack.log.info).toHaveBeenCalledWith( + expect.stringContaining("JetBrains IDEs"), + ); + + expect(consoleSpy).toHaveBeenCalledWith( + expect.stringContaining("mcpServers"), + ); + + // Should ask to copy to clipboard + expect(clack.select).toHaveBeenCalledWith( + expect.objectContaining({ + message: "Copy configuration to clipboard?", + }), + ); + + expect(clack.log.success).toHaveBeenCalledWith( + "Configuration copied to clipboard!", + ); + + consoleSpy.mockRestore(); + }); + + it("should show generic config for unsupported IDEs with clipboard copy", async () => { + const { clack, clackUtils } = await getMocks(); + + vi.mocked(clack.select) + .mockResolvedValueOnce("yes") + .mockResolvedValueOnce(true); // For the clipboard copy prompt + vi.mocked(clack.multiselect).mockResolvedValueOnce(["other"]); + + vi.mocked(clackUtils.abortIfCancelled).mockImplementation( + (value: unknown) => Promise.resolve(value), + ); + + // Mock clipboard copy failure to test fallback + const mockSpawn = vi.fn().mockReturnValue({ + stdin: { + write: vi.fn(), + end: vi.fn(), + }, + on: vi.fn((event, callback: () => void) => { + if (event === "error") callback(); + }), + }); + vi.spyOn(childProcess, "spawn").mockImplementation(mockSpawn); + + // Mock console.log to capture output + const consoleSpy = vi + .spyOn(process.stdout, "write") + .mockImplementation(() => true); + + await offerProjectScopedMcpConfig(); + + expect(clack.log.info).toHaveBeenCalledWith( + expect.stringContaining("Generic MCP configuration"), + ); + + expect(consoleSpy).toHaveBeenCalledWith( + expect.stringContaining("mcpServers"), + ); + + // Should ask to copy to clipboard + expect(clack.select).toHaveBeenCalledWith( + expect.objectContaining({ + message: "Copy configuration to clipboard?", + }), + ); + + // Since clipboard copy failed, should show warning + expect(clack.log.warn).toHaveBeenCalledWith( + expect.stringContaining("Failed to copy to clipboard"), + ); + + consoleSpy.mockRestore(); + }); + + it("should handle clipboard copy failure gracefully for JetBrains", async () => { + const { clack, clackUtils } = await getMocks(); + + vi.mocked(clack.select) + .mockResolvedValueOnce("yes") + .mockResolvedValueOnce(true); // For clipboard copy prompt + vi.mocked(clack.multiselect).mockResolvedValueOnce(["jetbrains"]); + + vi.mocked(clackUtils.abortIfCancelled).mockImplementation( + (value: unknown) => Promise.resolve(value), + ); + + // Mock clipboard copy to throw error + const mockSpawn = vi.fn().mockImplementation(() => { + throw new Error("Clipboard not available"); + }); + vi.spyOn(childProcess, "spawn").mockImplementation(mockSpawn); + + // Mock console.log to capture output + const consoleSpy = vi + .spyOn(process.stdout, "write") + .mockImplementation(() => true); + + await offerProjectScopedMcpConfig(); + + // Should ask to copy to clipboard + expect(clack.select).toHaveBeenCalledWith( + expect.objectContaining({ + message: "Copy configuration to clipboard?", + }), + ); + + // Should show warning when clipboard fails + expect(clack.log.warn).toHaveBeenCalledWith( + expect.stringContaining("Failed to copy to clipboard"), + ); + + consoleSpy.mockRestore(); + }); + + it('should show MCP explanation when user selects "What is MCP?"', async () => { + const { clack, clackUtils } = await getMocks(); + + vi.mocked(clack.select) + .mockResolvedValueOnce("explain") // User selects "What is MCP?" + .mockResolvedValueOnce(true); // User selects "Yes" after explanation + vi.mocked(clack.multiselect).mockResolvedValueOnce(["cursor"]); // User selects Cursor + + vi.mocked(clackUtils.abortIfCancelled).mockImplementation( + (value: unknown) => Promise.resolve(value), + ); + + const mockReadFile = vi + .fn() + .mockRejectedValue(new Error("File not found")); + const mockWriteFile = vi.fn().mockResolvedValue(undefined); + const mockMkdirSync = vi.fn(); + + vi.spyOn(fs.promises, "readFile").mockImplementation(mockReadFile); + vi.spyOn(fs.promises, "writeFile").mockImplementation(mockWriteFile); + vi.spyOn(fs, "mkdirSync").mockImplementation(mockMkdirSync); + + await offerProjectScopedMcpConfig(); + + // Should show MCP explanation + expect(clack.log.info).toHaveBeenCalledWith( + expect.stringContaining("What is MCP"), + ); + + expect(clack.log.info).toHaveBeenCalledWith( + expect.stringContaining("AI assistants"), + ); + + expect(clack.log.info).toHaveBeenCalledWith( + expect.stringContaining("https://docs.sentry.io/product/sentry-mcp/"), + ); + + // Should ask again after explanation + expect(clack.select).toHaveBeenCalledWith( + expect.objectContaining({ + message: "Would you like to configure MCP for your IDE now?", + }), + ); + + // Should proceed with normal flow + expect(mockWriteFile).toHaveBeenCalled(); + }); + + it("should respect user choice not to copy to clipboard", async () => { + const { clack, clackUtils } = await getMocks(); + + vi.mocked(clack.select) + .mockResolvedValueOnce("yes") + .mockResolvedValueOnce(false); // User declines to copy to clipboard + vi.mocked(clack.multiselect).mockResolvedValueOnce(["jetbrains"]); + + vi.mocked(clackUtils.abortIfCancelled).mockImplementation( + (value: unknown) => Promise.resolve(value), + ); + + const mockSpawn = vi.fn(); + vi.spyOn(childProcess, "spawn").mockImplementation(mockSpawn); + + // Mock console.log to capture output + const consoleSpy = vi + .spyOn(process.stdout, "write") + .mockImplementation(() => true); + + await offerProjectScopedMcpConfig(); + + // Should ask to copy to clipboard + expect(clack.select).toHaveBeenCalledWith( + expect.objectContaining({ + message: "Copy configuration to clipboard?", + }), + ); + + // Should NOT attempt to copy when user declines + expect(mockSpawn).not.toHaveBeenCalled(); + + // Should NOT show success or warning messages + expect(clack.log.success).not.toHaveBeenCalledWith( + "Configuration copied to clipboard!", + ); + expect(clack.log.warn).not.toHaveBeenCalledWith( + expect.stringContaining("Failed to copy to clipboard"), + ); + + consoleSpy.mockRestore(); + }); + + it("should exit if user declines after MCP explanation", async () => { + const { clack, clackUtils } = await getMocks(); + + vi.mocked(clack.select) + .mockResolvedValueOnce("explain") // User selects "What is MCP?" + .mockResolvedValueOnce(false); // User selects "No" after explanation + + vi.mocked(clackUtils.abortIfCancelled).mockImplementation( + (value: unknown) => Promise.resolve(value), + ); + + await offerProjectScopedMcpConfig(); + + // Should show MCP explanation + expect(clack.log.info).toHaveBeenCalledWith( + expect.stringContaining("What is MCP"), + ); + + // Should ask again after explanation + expect(clack.select).toHaveBeenCalledWith( + expect.objectContaining({ + message: "Would you like to configure MCP for your IDE now?", + }), + ); + + // Should NOT proceed with editor selection + expect(clack.multiselect).not.toHaveBeenCalled(); + }); + + it("should configure multiple editors when selected", async () => { + const { clack, clackUtils } = await getMocks(); + + vi.mocked(clack.select).mockResolvedValueOnce("yes"); + vi.mocked(clack.multiselect).mockResolvedValueOnce([ + "cursor", + "vscode", + "claudeCode", + ]); + vi.mocked(clackUtils.abortIfCancelled).mockImplementation( + (value: unknown) => Promise.resolve(value), + ); + + const mockReadFile = vi + .fn() + .mockRejectedValue(new Error("File not found")); + const mockWriteFile = vi.fn().mockResolvedValue(undefined); + const mockMkdirSync = vi.fn(); + + vi.spyOn(fs.promises, "readFile").mockImplementation(mockReadFile); + vi.spyOn(fs.promises, "writeFile").mockImplementation(mockWriteFile); + vi.spyOn(fs, "mkdirSync").mockImplementation(mockMkdirSync); + + await offerProjectScopedMcpConfig(); + + // Should write config for all three editors + expect(mockWriteFile).toHaveBeenCalledTimes(3); + expect(mockWriteFile).toHaveBeenCalledWith( + expect.stringContaining(".cursor/mcp.json"), + expect.stringContaining('"mcpServers"'), + "utf8", + ); + expect(mockWriteFile).toHaveBeenCalledWith( + expect.stringContaining(".vscode/mcp.json"), + expect.stringContaining('"servers"'), + "utf8", + ); + expect(mockWriteFile).toHaveBeenCalledWith( + expect.stringContaining(".mcp.json"), + expect.stringContaining('"mcpServers"'), + "utf8", + ); + + // Should show success messages for each (twice per editor: filename + editor-specific message) + expect(clack.log.success).toHaveBeenCalledWith( + "Added project-scoped Sentry MCP configuration for Cursor.", + ); + expect(clack.log.success).toHaveBeenCalledWith( + "Added project-scoped Sentry MCP configuration for VS Code.", + ); + expect(clack.log.success).toHaveBeenCalledWith( + "Added project-scoped Sentry MCP configuration for Claude Code.", + ); + }); + + it("should return early when no editors are selected", async () => { + const { clack, clackUtils } = await getMocks(); + + vi.mocked(clack.select).mockResolvedValueOnce("yes"); + vi.mocked(clack.multiselect).mockResolvedValueOnce([]); + vi.mocked(clackUtils.abortIfCancelled).mockImplementation( + (value: unknown) => Promise.resolve(value), + ); + + const mockWriteFile = vi.fn(); + vi.spyOn(fs.promises, "writeFile").mockImplementation(mockWriteFile); + + await offerProjectScopedMcpConfig(); + + expect(clack.log.info).toHaveBeenCalledWith( + "No editors selected. You can add MCP configuration later.", + ); + expect(mockWriteFile).not.toHaveBeenCalled(); + }); + + it("should handle mixed success and failure for multiple editors", async () => { + const { clack, clackUtils } = await getMocks(); + + vi.mocked(clack.select).mockResolvedValueOnce("yes"); + vi.mocked(clack.multiselect).mockResolvedValueOnce(["cursor", "vscode"]); + vi.mocked(clackUtils.abortIfCancelled).mockImplementation( + (value: unknown) => Promise.resolve(value), + ); + + const mockReadFile = vi + .fn() + .mockRejectedValue(new Error("File not found")); + const mockWriteFile = vi + .fn() + .mockResolvedValueOnce(undefined) // Cursor succeeds + .mockRejectedValueOnce(new Error("Permission denied")); // VS Code fails + const mockMkdirSync = vi.fn(); + + vi.spyOn(fs.promises, "readFile").mockImplementation(mockReadFile); + vi.spyOn(fs.promises, "writeFile").mockImplementation(mockWriteFile); + vi.spyOn(fs, "mkdirSync").mockImplementation(mockMkdirSync); + + await offerProjectScopedMcpConfig(); + + // Cursor should succeed + expect(clack.log.success).toHaveBeenCalledWith( + expect.stringContaining(".cursor/mcp.json"), + ); + + // VS Code should fail and show fallback + expect(clack.log.warn).toHaveBeenCalledWith( + expect.stringContaining("Failed to write MCP config for vscode"), + ); + expect(clackUtils.showCopyPasteInstructions).toHaveBeenCalledWith( + expect.objectContaining({ + filename: path.join(".vscode", "mcp.json"), + }), + ); + }); + }); +}); diff --git a/packages/cli/test/lib/wizard/utils/data-collection.test.ts b/packages/cli/test/lib/wizard/utils/data-collection.test.ts new file mode 100644 index 0000000000..6f68c33bf0 --- /dev/null +++ b/packages/cli/test/lib/wizard/utils/data-collection.test.ts @@ -0,0 +1,92 @@ +import { describe, expect, it } from "vitest"; + +import { + getDataCollectionSnippet, + sdkSupportsDataCollection, +} from "../../../../src/lib/wizard/utils/data-collection.js"; +import { getMajorVersion } from "../../../../src/lib/wizard/utils/semver.js"; + +describe("getMajorVersion", () => { + it.each([ + ["^10", 10], + ["^10.73.0", 10], + ["~11.2.0", 11], + ["11.0.0", 11], + // Prerelease versions keep their major, so v11 rc/beta installs pass the gate + ["11.0.0-rc.1", 11], + ["^11.0.0-rc.0", 11], + ["~11.0.0-beta.2", 11], + [">=10.57.0 <12", 10], + ])("returns the lowest permitted major for %s", (version, expected) => { + expect(getMajorVersion(version)).toBe(expected); + }); + + it.each([undefined, "", "not-a-version", "workspace:*"])( + "returns undefined for %s", + (version) => { + expect(getMajorVersion(version)).toBeUndefined(); + }, + ); +}); + +describe("sdkSupportsDataCollection", () => { + it.each([ + ["^11.0.0", "^10"], + ["11.2.3", "^10"], + ["^12", "^10"], + ["11.0.0-rc.1", "^10"], + ["^11.0.0-beta.0", "^10"], + ])("returns true for installed version %s", (installed, range) => { + expect(sdkSupportsDataCollection(installed, range)).toBe(true); + }); + + it.each([ + ["^10.73.0", "^10"], + ["10.99.0", "^10"], + ["^9", "^10"], + ["10.99.0-rc.1", "^10"], + ])("returns false for installed version %s", (installed, range) => { + expect(sdkSupportsDataCollection(installed, range)).toBe(false); + }); + + it("falls back to the wizard install range when the installed version is missing", () => { + expect(sdkSupportsDataCollection(undefined, "^11")).toBe(true); + expect(sdkSupportsDataCollection(undefined, "^10")).toBe(false); + }); + + it("falls back to the wizard install range when the installed version is unparseable", () => { + expect(sdkSupportsDataCollection("workspace:*", "^11")).toBe(true); + expect(sdkSupportsDataCollection("workspace:*", "^10")).toBe(false); + }); + + it("returns false when neither version is parseable", () => { + expect(sdkSupportsDataCollection(undefined, "not-a-version")).toBe(false); + }); +}); + +describe("getDataCollectionSnippet", () => { + it("renders the preset with the default indentation", () => { + expect(getDataCollectionSnippet()).toMatchInlineSnapshot(` + " // Turns off collection of data that could identify users. Adjust per category: + // https://docs.sentry.io/platforms/javascript/configuration/options/#dataCollection + dataCollection: { + userInfo: false, + graphQL: { document: false, variables: false }, + genAI: { inputs: false, outputs: false }, + databaseQueryData: false, + queues: false, + httpBodies: [], + httpHeaders: { deny: ["forwarded", "-ip", "remote-", "via", "-user"] }, + cookies: { deny: ["forwarded", "-ip", "remote-", "via", "-user"] }, + urlQueryParams: { deny: ["forwarded", "-ip", "remote-", "via", "-user"] }, + }," + `); + }); + + it("prefixes every line with the given indent", () => { + const snippet = getDataCollectionSnippet(" "); + for (const line of snippet.split("\n")) { + expect(line.startsWith(" ")).toBe(true); + } + }); +}); diff --git a/packages/cli/test/lib/wizard/utils/git.test.ts b/packages/cli/test/lib/wizard/utils/git.test.ts new file mode 100644 index 0000000000..4daaffda1c --- /dev/null +++ b/packages/cli/test/lib/wizard/utils/git.test.ts @@ -0,0 +1,126 @@ +import { beforeEach, describe, it, vi, expect } from "vitest"; + +import { + getUncommittedOrUntrackedFilePaths, + isInGitRepo, +} from "../../../../src/lib/wizard/utils/git.js"; + +const { mockedExecSync } = vi.hoisted(() => { + return { mockedExecSync: vi.fn() }; +}); + +vi.mock("node:child_process", async () => { + return { + default: {}, + ...(await vi.importActual("node:child_process")), + execSync: mockedExecSync, + }; +}); + +beforeEach(() => { + vi.clearAllMocks(); +}); + +describe("isInGitRepo", () => { + it("returns true if the git command process exits with 0", () => { + mockedExecSync.mockImplementationOnce(() => { + return "true"; + }); + expect(isInGitRepo({ cwd: undefined })).toBe(true); + }); + + it("returns false if the git command process exits with non-zero", () => { + mockedExecSync.mockImplementationOnce(() => { + throw new Error("Command failed"); + }); + expect(isInGitRepo({ cwd: undefined })).toBe(false); + }); + + it("forwards cwd if provided", () => { + mockedExecSync.mockImplementationOnce(() => { + return "true"; + }); + isInGitRepo({ cwd: "/path/to/dir" }); + expect(mockedExecSync).toHaveBeenCalledWith( + "git rev-parse --is-inside-work-tree", + { + stdio: "ignore", + cwd: "/path/to/dir", + }, + ); + }); +}); + +describe("getUncommittedOrUntrackedFilePaths", () => { + it("returns the verbatim paths of uncommitted or untracked files", () => { + mockedExecSync.mockImplementationOnce(() => { + return ( + " M file1.txt\0" + + "?? file2.txt\0" + + "?? file3.txt\0" + + "?? file4.txt\0" + ); + }); + expect(getUncommittedOrUntrackedFilePaths()).toEqual([ + "file1.txt", + "file2.txt", + "file3.txt", + "file4.txt", + ]); + }); + + it("uses the NUL-delimited porcelain format", () => { + mockedExecSync.mockImplementationOnce(() => ""); + + getUncommittedOrUntrackedFilePaths({ cwd: "/path/to/dir" }); + + expect(mockedExecSync).toHaveBeenCalledWith( + "git status --porcelain=v1 -z", + { + stdio: ["ignore", "pipe", "ignore"], + cwd: "/path/to/dir", + }, + ); + }); + + it("preserves file names containing spaces and shell metacharacters", () => { + mockedExecSync.mockImplementationOnce(() => { + return ( + "?? $(touch pwned).js\0" + + "?? a;id;b.js\0" + + "?? with space.txt\0" + + " M `whoami`.ts\0" + ); + }); + expect(getUncommittedOrUntrackedFilePaths()).toEqual([ + "$(touch pwned).js", + "a;id;b.js", + "with space.txt", + "`whoami`.ts", + ]); + }); + + it("returns the destination path of a rename and skips the source field", () => { + mockedExecSync.mockImplementationOnce(() => { + return "R renamed.txt\0orig.txt\0?? other.txt\0"; + }); + expect(getUncommittedOrUntrackedFilePaths()).toEqual([ + "renamed.txt", + "other.txt", + ]); + }); + + it("returns an empty list if there are no uncommitted or untracked files", () => { + mockedExecSync.mockImplementationOnce(() => ""); + + expect(getUncommittedOrUntrackedFilePaths()).toEqual([]); + }); + + it("returns an empty list if the git command fails", () => { + mockedExecSync.mockImplementationOnce(() => { + throw new Error("Command failed"); + }); + + expect(getUncommittedOrUntrackedFilePaths()).toEqual([]); + }); +}); diff --git a/packages/cli/test/lib/wizard/utils/node-version.test.ts b/packages/cli/test/lib/wizard/utils/node-version.test.ts new file mode 100644 index 0000000000..f7084d0253 --- /dev/null +++ b/packages/cli/test/lib/wizard/utils/node-version.test.ts @@ -0,0 +1,69 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; + +const clackMocks = vi.hoisted(() => ({ warn: vi.fn() })); + +vi.mock("@clack/prompts", () => ({ + log: { warn: clackMocks.warn }, +})); + +import { + isNodeVersionSupportedBySdkV11, + warnIfNodeVersionUnsupportedBySdkV11, +} from "../../../../src/lib/wizard/utils/node-version.js"; + +describe("isNodeVersionSupportedBySdkV11", () => { + it.each([ + "v20.19.0", + "v20.20.2", + "20.19.5", + "v22.12.0", + "v22.23.2", + "v23.2.0", + "v24.0.0", + "v26.8.1", + // Node.js 21 is EOL but inside the documented `>=20.19.0 <22.0.0` range + "v21.7.0", + ])("returns true for %s", (version) => { + expect(isNodeVersionSupportedBySdkV11(version)).toBe(true); + }); + + it.each(["v18.20.6", "v20.18.3", "v22.11.0", "v23.1.0", "16.20.2"])( + "returns false for %s", + (version) => { + expect(isNodeVersionSupportedBySdkV11(version)).toBe(false); + }, + ); + + it.each(["", "not-a-version"])( + "treats an unparseable version (%s) as supported", + (version) => { + expect(isNodeVersionSupportedBySdkV11(version)).toBe(true); + }, + ); + + it("defaults to the running Node.js version", () => { + expect(isNodeVersionSupportedBySdkV11()).toBe( + isNodeVersionSupportedBySdkV11(process.version), + ); + }); +}); + +describe("warnIfNodeVersionUnsupportedBySdkV11", () => { + beforeEach(() => { + vi.clearAllMocks(); + }); + + it("warns on an unsupported version and names it", () => { + warnIfNodeVersionUnsupportedBySdkV11("v18.20.6"); + + expect(clackMocks.warn).toHaveBeenCalledTimes(1); + expect(clackMocks.warn.mock.calls[0]?.[0]).toContain("v18.20.6"); + expect(clackMocks.warn.mock.calls[0]?.[0]).toContain("20.19.0"); + }); + + it("stays silent on a supported version", () => { + warnIfNodeVersionUnsupportedBySdkV11("v22.18.0"); + + expect(clackMocks.warn).not.toHaveBeenCalled(); + }); +}); diff --git a/packages/cli/test/lib/wizard/utils/package-json.test.ts b/packages/cli/test/lib/wizard/utils/package-json.test.ts new file mode 100644 index 0000000000..f04f2f9fd4 --- /dev/null +++ b/packages/cli/test/lib/wizard/utils/package-json.test.ts @@ -0,0 +1,594 @@ +import { beforeEach, describe, it, vi, expect, afterEach } from "vitest"; +// oxlint-disable-next-line sentry-cli/no-namespace-import -- needed for spyOn mocking +import * as path from "node:path"; + +import { + findInstalledPackageFromList, + hasPackageInstalled, + getPackageVersion, + type PackageDotJson, +} from "../../../../src/lib/wizard/utils/package-json.js"; + +const { mockedFs, mockedClack } = vi.hoisted(() => { + return { + mockedFs: { + existsSync: vi.fn(), + readFileSync: vi.fn(), + }, + mockedClack: { + log: { + error: vi.fn(), + }, + }, + }; +}); + +vi.mock(import("node:fs"), async (importOriginal) => ({ + ...(await importOriginal()), + existsSync: mockedFs.existsSync, + readFileSync: mockedFs.readFileSync, +})); + +vi.mock(import("@clack/prompts"), async (importOriginal) => ({ + ...(await importOriginal()), + log: { + ...(await importOriginal()).log, + error: mockedClack.log.error, + }, +})); + +describe("package-json utils", () => { + beforeEach(() => { + vi.clearAllMocks(); + }); + + describe("getPackageVersion", () => { + it("returns version from dependencies", () => { + const packageJson: PackageDotJson = { + dependencies: { + "@sentry/node": "^7.0.0", + }, + }; + + expect(getPackageVersion("@sentry/node", packageJson)).toBe("^7.0.0"); + }); + + it("returns version from devDependencies", () => { + const packageJson: PackageDotJson = { + devDependencies: { + "@sentry/cli": "^2.0.0", + }, + }; + + expect(getPackageVersion("@sentry/cli", packageJson)).toBe("^2.0.0"); + }); + + it("prioritizes dependencies over devDependencies", () => { + const packageJson: PackageDotJson = { + dependencies: { + "@sentry/node": "^7.0.0", + }, + devDependencies: { + "@sentry/node": "^6.0.0", + }, + }; + + expect(getPackageVersion("@sentry/node", packageJson)).toBe("^7.0.0"); + }); + + it("returns undefined if package is not found", () => { + const packageJson: PackageDotJson = { + dependencies: {}, + }; + + expect(getPackageVersion("@sentry/node", packageJson)).toBeUndefined(); + }); + + it("returns undefined if packageJson has no dependencies", () => { + const packageJson: PackageDotJson = {}; + + expect(getPackageVersion("@sentry/node", packageJson)).toBeUndefined(); + }); + + describe("pnpm catalog resolution", () => { + beforeEach(() => { + vi.spyOn(process, "cwd").mockReturnValue( + "/test/workspace/packages/app", + ); + }); + + afterEach(() => { + vi.clearAllMocks(); + }); + + it("resolves default catalog reference", () => { + mockedFs.existsSync.mockImplementation((filepath: string) => { + return ( + filepath === path.join("/test/workspace", "pnpm-workspace.yaml") + ); + }); + + mockedFs.readFileSync.mockReturnValue(` +catalog: + '@sentry/node': ^7.100.0 + '@sentry/react': ^7.100.0 +`); + + const packageJson: PackageDotJson = { + dependencies: { + "@sentry/node": "catalog:", + }, + }; + + expect(getPackageVersion("@sentry/node", packageJson)).toBe("^7.100.0"); + }); + + it("resolves named catalog reference", () => { + mockedFs.existsSync.mockImplementation((filepath: string) => { + return ( + filepath === path.join("/test/workspace", "pnpm-workspace.yaml") + ); + }); + + mockedFs.readFileSync.mockReturnValue(` +catalogs: + sveltekit: + '@sentry/sveltekit': ^7.100.0 + '@sentry/node': ^7.100.0 +`); + + const packageJson: PackageDotJson = { + dependencies: { + "@sentry/sveltekit": "catalog:sveltekit", + }, + }; + + expect(getPackageVersion("@sentry/sveltekit", packageJson)).toBe( + "^7.100.0", + ); + }); + + it("searches parent directories for pnpm-workspace.yaml", () => { + const mockCwd = "/test/workspace/packages/app/src"; + vi.spyOn(process, "cwd").mockReturnValue(mockCwd); + + mockedFs.existsSync.mockImplementation((filepath: string) => { + return ( + filepath === path.join("/test/workspace", "pnpm-workspace.yaml") + ); + }); + + mockedFs.readFileSync.mockReturnValue(` +catalog: + '@sentry/node': ^7.100.0 +`); + + const packageJson: PackageDotJson = { + dependencies: { + "@sentry/node": "catalog:", + }, + }; + + expect(getPackageVersion("@sentry/node", packageJson)).toBe("^7.100.0"); + }); + + it("returns undefined if catalog does not contain the package", () => { + mockedFs.existsSync.mockImplementation((filepath: string) => { + return ( + filepath === path.join("/test/workspace", "pnpm-workspace.yaml") + ); + }); + + mockedFs.readFileSync.mockReturnValue(` +catalog: + '@sentry/react': ^7.100.0 +`); + + const packageJson: PackageDotJson = { + dependencies: { + "@sentry/node": "catalog:", + }, + }; + + expect(getPackageVersion("@sentry/node", packageJson)).toBeUndefined(); + }); + + it("returns undefined if named catalog does not exist", () => { + mockedFs.existsSync.mockImplementation((filepath: string) => { + return ( + filepath === path.join("/test/workspace", "pnpm-workspace.yaml") + ); + }); + + mockedFs.readFileSync.mockReturnValue(` +catalog: + '@sentry/node': ^7.100.0 +`); + + const packageJson: PackageDotJson = { + dependencies: { + "@sentry/sveltekit": "catalog:sveltekit", + }, + }; + + expect( + getPackageVersion("@sentry/sveltekit", packageJson), + ).toBeUndefined(); + }); + + it("returns undefined if pnpm-workspace.yaml is not found", () => { + mockedFs.existsSync.mockReturnValue(false); + + const packageJson: PackageDotJson = { + dependencies: { + "@sentry/node": "catalog:", + }, + }; + + expect(getPackageVersion("@sentry/node", packageJson)).toBeUndefined(); + expect(mockedClack.log.error).toHaveBeenCalledWith( + "Could not find pnpm-workspace.yaml.", + ); + }); + + it("stops searching at root directory", () => { + const mockCwd = "/test"; + vi.spyOn(process, "cwd").mockReturnValue(mockCwd); + + mockedFs.existsSync.mockReturnValue(false); + + const packageJson: PackageDotJson = { + dependencies: { + "@sentry/node": "catalog:", + }, + }; + + expect(getPackageVersion("@sentry/node", packageJson)).toBeUndefined(); + }); + + it("handles both default catalog and named catalogs together", () => { + mockedFs.existsSync.mockImplementation((filepath: string) => { + return ( + filepath === path.join("/test/workspace", "pnpm-workspace.yaml") + ); + }); + + mockedFs.readFileSync.mockReturnValue(` +catalog: + '@sentry/node': ^7.100.0 +catalogs: + sveltekit: + '@sentry/sveltekit': ^7.200.0 +`); + + const packageJson: PackageDotJson = { + dependencies: { + "@sentry/node": "catalog:", + "@sentry/sveltekit": "catalog:sveltekit", + }, + }; + + expect(getPackageVersion("@sentry/node", packageJson)).toBe("^7.100.0"); + expect(getPackageVersion("@sentry/sveltekit", packageJson)).toBe( + "^7.200.0", + ); + }); + + it("handles the correct catalog namespace", () => { + mockedFs.existsSync.mockImplementation((filepath: string) => { + return ( + filepath === path.join("/test/workspace", "pnpm-workspace.yaml") + ); + }); + + mockedFs.readFileSync.mockReturnValue(` +catalog: + '@sveltejs/kit': ^1.0.0 +catalogs: + sveltekit: + '@sveltejs/kit': ^2.31.0 +`); + + const packageJson: PackageDotJson = { + dependencies: { + "@sveltejs/kit": "catalog:sveltekit", + }, + }; + + expect(getPackageVersion("@sveltejs/kit", packageJson)).toBe("^2.31.0"); + }); + + it("ignores pnpm-workspace.yaml content that is not a catalog mapping", () => { + mockedFs.existsSync.mockImplementation((filepath: string) => { + return ( + filepath === path.join("/test/workspace", "pnpm-workspace.yaml") + ); + }); + + mockedFs.readFileSync.mockReturnValue("invalid: yaml: content: ["); + + const packageJson: PackageDotJson = { + dependencies: { + "@sentry/node": "catalog:", + }, + }; + + expect(getPackageVersion("@sentry/node", packageJson)).toBeUndefined(); + }); + + it("reads quoted names, inline comments, and catalogs of other packages", () => { + mockedFs.existsSync.mockImplementation((filepath: string) => { + return ( + filepath === path.join("/test/workspace", "pnpm-workspace.yaml") + ); + }); + + mockedFs.readFileSync.mockReturnValue(`packages: + - 'apps/*' + +# Versions shared across the workspace +catalog: + "@sentry/node": "^8.0.0" # keep in sync + react: ^18.2.0 + +catalogs: + legacy: + '@sentry/node': ~7.120.0 + next: + "@sentry/nextjs": 9.0.0 +onlyBuiltDependencies: + - esbuild +`); + + expect( + getPackageVersion("@sentry/node", { + dependencies: { "@sentry/node": "catalog:" }, + }), + ).toBe("^8.0.0"); + expect( + getPackageVersion("@sentry/node", { + dependencies: { "@sentry/node": "catalog:legacy" }, + }), + ).toBe("~7.120.0"); + expect( + getPackageVersion("@sentry/nextjs", { + dependencies: { "@sentry/nextjs": "catalog:next" }, + }), + ).toBe("9.0.0"); + }); + + it("handles regular version strings without catalog lookup", () => { + const packageJson: PackageDotJson = { + dependencies: { + "@sentry/node": "^7.0.0", + "@sentry/react": "~7.1.0", + "@sentry/cli": "2.0.0", + }, + }; + + expect(getPackageVersion("@sentry/node", packageJson)).toBe("^7.0.0"); + expect(getPackageVersion("@sentry/react", packageJson)).toBe("~7.1.0"); + expect(getPackageVersion("@sentry/cli", packageJson)).toBe("2.0.0"); + expect(mockedFs.existsSync).not.toHaveBeenCalled(); + }); + }); + }); + + describe("hasPackageInstalled", () => { + it("returns true if package is in dependencies", () => { + const packageJson: PackageDotJson = { + dependencies: { + "@sentry/node": "^7.0.0", + }, + }; + + expect(hasPackageInstalled("@sentry/node", packageJson)).toBe(true); + }); + + it("returns true if package is in devDependencies", () => { + const packageJson: PackageDotJson = { + devDependencies: { + "@sentry/cli": "^2.0.0", + }, + }; + + expect(hasPackageInstalled("@sentry/cli", packageJson)).toBe(true); + }); + + it("returns false if package is not installed", () => { + const packageJson: PackageDotJson = { + dependencies: {}, + }; + + expect(hasPackageInstalled("@sentry/node", packageJson)).toBe(false); + }); + + it("returns true if package uses catalog reference", () => { + const mockCwd = "/test/workspace/packages/app"; + vi.spyOn(process, "cwd").mockReturnValue(mockCwd); + + mockedFs.existsSync.mockImplementation((filepath: string) => { + return filepath === path.join("/test/workspace", "pnpm-workspace.yaml"); + }); + + mockedFs.readFileSync.mockReturnValue(` +catalog: + '@sentry/node': ^7.100.0 +`); + + const packageJson: PackageDotJson = { + dependencies: { + "@sentry/node": "catalog:", + }, + }; + + expect(hasPackageInstalled("@sentry/node", packageJson)).toBe(true); + }); + + it("returns false if package uses catalog reference but catalog does not have it", () => { + const mockCwd = "/test/workspace/packages/app"; + vi.spyOn(process, "cwd").mockReturnValue(mockCwd); + + mockedFs.existsSync.mockImplementation((filepath: string) => { + return filepath === path.join("/test/workspace", "pnpm-workspace.yaml"); + }); + + mockedFs.readFileSync.mockReturnValue(` +catalog: + '@sentry/react': ^7.100.0 +`); + + const packageJson: PackageDotJson = { + dependencies: { + "@sentry/node": "catalog:", + }, + }; + + expect(hasPackageInstalled("@sentry/node", packageJson)).toBe(false); + }); + }); + + describe("findInstalledPackageFromList", () => { + it("returns the first installed package from the list", () => { + const packageJson: PackageDotJson = { + dependencies: { + "@sentry/node": "^7.0.0", + }, + }; + + const result = findInstalledPackageFromList( + ["@sentry/cli", "@sentry/node", "@sentry/react"], + packageJson, + ); + + expect(result).toEqual({ + name: "@sentry/node", + version: "^7.0.0", + }); + }); + + it("returns undefined if no packages are installed", () => { + const packageJson: PackageDotJson = { + dependencies: {}, + }; + + const result = findInstalledPackageFromList( + ["@sentry/cli", "@sentry/node", "@sentry/react"], + packageJson, + ); + + expect(result).toBeUndefined(); + }); + + it("checks both dependencies and devDependencies", () => { + const packageJson: PackageDotJson = { + devDependencies: { + "@sentry/cli": "^2.0.0", + }, + }; + + const result = findInstalledPackageFromList( + ["@sentry/node", "@sentry/cli"], + packageJson, + ); + + expect(result).toEqual({ + name: "@sentry/cli", + version: "^2.0.0", + }); + }); + + it("returns first match in order provided", () => { + const packageJson: PackageDotJson = { + dependencies: { + "@sentry/node": "^7.0.0", + "@sentry/react": "^7.0.0", + }, + }; + + const result = findInstalledPackageFromList( + ["@sentry/react", "@sentry/node"], + packageJson, + ); + + expect(result).toEqual({ + name: "@sentry/react", + version: "^7.0.0", + }); + }); + + it("works with catalog references", () => { + const mockCwd = "/test/workspace/packages/app"; + vi.spyOn(process, "cwd").mockReturnValue(mockCwd); + + mockedFs.existsSync.mockImplementation((filepath: string) => { + return filepath === path.join("/test/workspace", "pnpm-workspace.yaml"); + }); + + mockedFs.readFileSync.mockReturnValue(` +catalog: + '@sentry/node': ^7.100.0 +`); + + const packageJson: PackageDotJson = { + dependencies: { + "@sentry/node": "catalog:", + }, + }; + + const result = findInstalledPackageFromList( + ["@sentry/cli", "@sentry/node"], + packageJson, + ); + + expect(result).toEqual({ + name: "@sentry/node", + version: "^7.100.0", + }); + }); + + it("returns undefined for empty package list", () => { + const packageJson: PackageDotJson = { + dependencies: { + "@sentry/node": "^7.0.0", + }, + }; + + const result = findInstalledPackageFromList([], packageJson); + + expect(result).toBeUndefined(); + }); + + it("skips packages with unresolvable catalog references", () => { + const mockCwd = "/test/workspace/packages/app"; + vi.spyOn(process, "cwd").mockReturnValue(mockCwd); + + mockedFs.existsSync.mockImplementation((filepath: string) => { + return filepath === path.join("/test/workspace", "pnpm-workspace.yaml"); + }); + + mockedFs.readFileSync.mockReturnValue(` +catalog: + '@sentry/react': ^7.100.0 +`); + + const packageJson: PackageDotJson = { + dependencies: { + "@sentry/node": "catalog:", + "@sentry/react": "catalog:", + }, + }; + + const result = findInstalledPackageFromList( + ["@sentry/node", "@sentry/react"], + packageJson, + ); + + // Should skip @sentry/node (unresolvable) and return @sentry/react + expect(result).toEqual({ + name: "@sentry/react", + version: "^7.100.0", + }); + }); + }); +}); diff --git a/packages/cli/test/lib/wizard/utils/package-manager.test.ts b/packages/cli/test/lib/wizard/utils/package-manager.test.ts new file mode 100644 index 0000000000..2eaec28053 --- /dev/null +++ b/packages/cli/test/lib/wizard/utils/package-manager.test.ts @@ -0,0 +1,37 @@ +import { describe, expect, it } from "vitest"; +import { + _detectPackageManger, + NPM, + PNPM, + YARN_V1, +} from "../../../../src/lib/wizard/utils/package-manager.js"; + +describe("_detectPackageManager", () => { + it("returns the detected package manager if exactly one is found", () => { + const pnpm = { ...PNPM, detect: () => true }; + + const packageManager = _detectPackageManger([ + { ...NPM, detect: () => false }, + { ...YARN_V1, detect: () => false }, + pnpm, + ]); + + expect(packageManager).toBe(pnpm); + }); + + it("returns null if no package manager is found", () => { + const packageManager = _detectPackageManger([ + { ...NPM, detect: () => false }, + { ...YARN_V1, detect: () => false }, + ]); + expect(packageManager).toBeNull(); + }); + + it("returns null if multiple package managers are found", () => { + const packageManager = _detectPackageManger([ + { ...NPM, detect: () => true }, + { ...YARN_V1, detect: () => true }, + ]); + expect(packageManager).toBeNull(); + }); +}); diff --git a/packages/cli/test/lib/wizard/utils/project-data.test.ts b/packages/cli/test/lib/wizard/utils/project-data.test.ts new file mode 100644 index 0000000000..a691410ee2 --- /dev/null +++ b/packages/cli/test/lib/wizard/utils/project-data.test.ts @@ -0,0 +1,252 @@ +/** + * Tests for the wizards' project selection on top of the CLI's login. + */ + +import { beforeEach, describe, expect, it, vi } from "vitest"; + +const mocks = vi.hoisted(() => ({ + getAuthConfig: vi.fn(), + runInteractiveLogin: vi.fn(), + completeAgentHandoff: vi.fn(), + ensureScopesForAction: vi.fn(), + listOrganizations: vi.fn(), + listProjects: vi.fn(), + getProject: vi.fn(), + getProjectKeys: vi.fn(), + createProjectWithDsn: vi.fn(), + createProjectWithAutoTeam: vi.fn(), + resolveOrCreateTeam: vi.fn(), + createOrgAuthToken: vi.fn(), + select: vi.fn(), + text: vi.fn(), +})); + +vi.mock("@clack/prompts", () => ({ + isCancel: vi.fn(() => false), + cancel: vi.fn(), + outro: vi.fn(), + select: mocks.select, + text: mocks.text, + spinner: vi.fn(() => ({ start: vi.fn(), stop: vi.fn() })), + log: { + info: vi.fn(), + step: vi.fn(), + warn: vi.fn(), + error: vi.fn(), + }, +})); +vi.mock("../../../../src/lib/db/auth.js", async (importOriginal) => ({ + ...(await importOriginal()), + getAuthConfig: mocks.getAuthConfig, +})); +vi.mock("../../../../src/lib/interactive-login.js", () => ({ + runInteractiveLogin: mocks.runInteractiveLogin, +})); +vi.mock("../../../../src/lib/agent-handoff.js", () => ({ + completeAgentHandoff: mocks.completeAgentHandoff, +})); +vi.mock("../../../../src/lib/auto-auth.js", () => ({ + assertAutoLoginHostTrusted: vi.fn(), +})); +vi.mock("../../../../src/lib/scope-recovery.js", () => ({ + ensureScopesForAction: mocks.ensureScopesForAction, +})); +vi.mock("../../../../src/lib/api/organizations.js", () => ({ + listOrganizations: mocks.listOrganizations, +})); +vi.mock("../../../../src/lib/api/org-auth-tokens.js", () => ({ + createOrgAuthToken: mocks.createOrgAuthToken, +})); +vi.mock("../../../../src/lib/resolve-team.js", () => ({ + resolveOrCreateTeam: mocks.resolveOrCreateTeam, +})); +vi.mock("../../../../src/lib/api/projects.js", async (importOriginal) => ({ + ...(await importOriginal< + typeof import("../../../../src/lib/api/projects.js") + >()), + listProjects: mocks.listProjects, + getProject: mocks.getProject, + getProjectKeys: mocks.getProjectKeys, + createProjectWithDsn: mocks.createProjectWithDsn, + createProjectWithAutoTeam: mocks.createProjectWithAutoTeam, +})); + +import { ApiError, WizardExitError } from "../../../../src/lib/errors.js"; +import { + DUMMY_AUTH_TOKEN, + getOrAskForProjectData, +} from "../../../../src/lib/wizard/utils/project-data.js"; +import type { SentryProjectData } from "../../../../src/lib/wizard/utils/types.js"; + +const ORG = { id: "1", slug: "acme", name: "Acme" }; +const PROJECT = { id: "42", slug: "web", name: "web", platform: "javascript" }; +const KEY = { + id: "k1", + name: "Default", + isActive: true, + dsn: { public: "https://abc@o1.ingest.sentry.io/42", secret: "" }, +}; + +beforeEach(() => { + vi.clearAllMocks(); + vi.stubEnv("SENTRY_HANDOFF", ""); + mocks.getAuthConfig.mockReturnValue({ token: "stored" }); + mocks.listOrganizations.mockResolvedValue([ORG]); + mocks.getProject.mockResolvedValue(PROJECT); + mocks.getProjectKeys.mockResolvedValue([KEY]); + mocks.ensureScopesForAction.mockResolvedValue("ready"); + mocks.createOrgAuthToken.mockResolvedValue({ token: "sntrys_new" }); +}); + +describe("getOrAskForProjectData", () => { + it("needs no login in Spotlight mode", async () => { + const result = await getOrAskForProjectData({ + telemetryEnabled: false, + spotlight: true, + }); + + expect(result).toEqual({ spotlight: true }); + expect(mocks.listOrganizations).not.toHaveBeenCalled(); + }); + + it("returns a preselected project without asking", async () => { + const project: SentryProjectData = { + id: "7", + slug: "app", + organization: { id: "1", name: "Acme", slug: "acme" }, + keys: [{ dsn: { public: "https://k@sentry.io/7" } }], + }; + + const result = await getOrAskForProjectData({ + telemetryEnabled: false, + preSelectedProject: { project, authToken: "tok", selfHosted: false }, + }); + + expect(result).toEqual({ + spotlight: false, + selfHosted: false, + sentryUrl: "https://sentry.io/", + authToken: "tok", + selectedProject: project, + }); + expect(mocks.listOrganizations).not.toHaveBeenCalled(); + }); + + it("uses the stored login and the --org and --project slugs", async () => { + const result = await getOrAskForProjectData({ + telemetryEnabled: false, + saas: true, + orgSlug: "acme", + projectSlug: "web", + }); + + expect(mocks.runInteractiveLogin).not.toHaveBeenCalled(); + expect(mocks.select).not.toHaveBeenCalled(); + expect(mocks.getProject).toHaveBeenCalledWith("acme", "web"); + expect(result).toEqual({ + spotlight: false, + selfHosted: false, + sentryUrl: "https://sentry.io/", + authToken: "sntrys_new", + selectedProject: { + id: "42", + slug: "web", + organization: ORG, + keys: [{ dsn: { public: KEY.dsn.public } }], + }, + }); + }); + + it("asks for the project when the --project slug is not found", async () => { + mocks.getProject.mockRejectedValue(new ApiError("Not found", 404)); + mocks.listProjects.mockResolvedValue([PROJECT]); + mocks.select.mockResolvedValueOnce(PROJECT); + + const result = await getOrAskForProjectData({ + telemetryEnabled: false, + saas: true, + orgSlug: "acme", + projectSlug: "missing", + }); + + expect(mocks.listProjects).toHaveBeenCalledWith("acme"); + expect(result).toMatchObject({ selectedProject: { slug: "web" } }); + }); + + it("creates a project for the wizard's platform", async () => { + mocks.listProjects.mockResolvedValue([]); + mocks.select.mockImplementationOnce( + (options: { options: { value: unknown }[] }) => + Promise.resolve(options.options[0]?.value), + ); + mocks.text.mockResolvedValueOnce("my app"); + mocks.resolveOrCreateTeam.mockResolvedValue({ slug: "acme" }); + mocks.createProjectWithDsn.mockResolvedValue({ + project: { ...PROJECT, slug: "my-app" }, + }); + + const result = await getOrAskForProjectData( + { telemetryEnabled: false, saas: true, orgSlug: "acme" }, + "javascript-nextjs", + ); + + expect(mocks.createProjectWithDsn).toHaveBeenCalledWith("acme", "acme", { + name: "my app", + platform: "javascript-nextjs", + }); + expect(result).toMatchObject({ selectedProject: { slug: "my-app" } }); + }); + + it("writes a placeholder token when no auth token can be created", async () => { + mocks.ensureScopesForAction.mockResolvedValue("unavailable"); + + const result = await getOrAskForProjectData({ + telemetryEnabled: false, + saas: true, + orgSlug: "acme", + projectSlug: "web", + }); + + expect(mocks.createOrgAuthToken).not.toHaveBeenCalled(); + expect(result).toMatchObject({ authToken: DUMMY_AUTH_TOKEN }); + }); + + it("logs in with the device flow when there is no stored login", async () => { + mocks.getAuthConfig.mockReturnValue(undefined); + mocks.runInteractiveLogin.mockResolvedValue({ method: "oauth" }); + + await getOrAskForProjectData({ + telemetryEnabled: false, + saas: true, + orgSlug: "acme", + projectSlug: "web", + }); + + expect(mocks.runInteractiveLogin).toHaveBeenCalledWith({ + scope: expect.stringContaining("org:tokens"), + }); + }); + + it("stops when the login fails", async () => { + mocks.getAuthConfig.mockReturnValue(undefined); + mocks.runInteractiveLogin.mockResolvedValue(null); + + await expect( + getOrAskForProjectData({ telemetryEnabled: false, saas: true }), + ).rejects.toThrow(WizardExitError); + }); + + it("claims an agent handoff and uses its org", async () => { + vi.stubEnv("SENTRY_HANDOFF", "handoff-code"); + mocks.completeAgentHandoff.mockResolvedValue({ organizationSlug: "acme" }); + + await getOrAskForProjectData({ + telemetryEnabled: false, + saas: true, + projectSlug: "web", + }); + + expect(mocks.completeAgentHandoff).toHaveBeenCalledWith("handoff-code"); + expect(mocks.getProject).toHaveBeenCalledWith("acme", "web"); + }); +}); diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index d31e4395bb..363032cd0d 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -792,6 +792,9 @@ importers: jpeg-js: specifier: ^0.4.4 version: 0.4.4 + magicast: + specifier: 0.2.11 + version: 0.2.11 marked: specifier: 'catalog:' version: 15.0.12 @@ -5483,6 +5486,10 @@ packages: asciinema-player@3.18.1: resolution: {integrity: sha512-H3blHwZYerDkjUVNABB0zjIzZhZu+JT0/FXT7Skc+4cpa2i7bDab49uOztsIguej4Ppfw6JS0V8J5/6VNqIIkQ==} + ast-types@0.16.3: + resolution: {integrity: sha512-FvWoWYfSCM6kRxCSH+MGLHIKKGRL6A6AW7Zek2O32REPQRdg131428uRTKMBYAeRd3XXAaHDS60Wpri7CdKDrA==} + engines: {node: '>=4'} + ast-v8-to-istanbul@1.0.7: resolution: {integrity: sha512-kFL68AG6ajd8fg248zwM9GQrUWEp79gsmjum34OEXjs4yHuUMZfYKwOLW9GMmB4oNvVrj+EAGxsP7ye2UR9UlA==} @@ -6095,6 +6102,11 @@ packages: resolution: {integrity: sha512-/veY75JbMK4j1yjvuUxuVsiS/hr/4iHs9FTT6cgTexxdE0Ly/glccBAkloH/DofkjRbZU3bnoj38mOmhkZ0lHw==} engines: {node: '>=12'} + esprima@4.0.1: + resolution: {integrity: sha512-eGuFFw7Upda+g4p+QHvnW0RyTX/SVeJBDM/gCtMARO0cLuT2HcEKnTPvhjV6aGeqrCB/sbNop0Kszm0jsaWU4A==} + engines: {node: '>=4'} + hasBin: true + estree-util-attach-comments@3.0.0: resolution: {integrity: sha512-cKUwm/HUcTDsYh/9FgnuFqpfquUbwIqwKM26BVCGDPVgvaCl/nDCCjUfiLlx6lsEZ3Z4RFxNbOQ60pkaEwFxGw==} @@ -6835,6 +6847,9 @@ packages: magic-string@1.4.5: resolution: {integrity: sha512-oLLC2+YvQUfAa+vxoufE/yc1icb87M9iXIRqAoR/2EhE/8cb3SF/+Gi0c2By1B+5Vz2e2vQtUvHiu1+63Znh+w==} + magicast@0.2.11: + resolution: {integrity: sha512-6saXbRDA1HMkqbsvHOU6HBjCVgZT460qheRkLhJQHWAbhXoWESI3Kn/dGGXyKs15FFKR85jsUqFx2sMK0wy/5g==} + magicast@0.5.5: resolution: {integrity: sha512-UicdXN8zQ3JHlxVq+28afMXPr1z7WNY6+7EJnzTdQWkTAlMLF5fNCCKxJHBQwGaNGR11581EiQmQzx73+MvszA==} @@ -7599,6 +7614,10 @@ packages: resolution: {integrity: sha512-Kko+Y5XQ6fM+Ce3dq3m9YGxnacYZYl9cA1wZjaF3Vbry2L3i1qVg8+CAgNPsXRArPMUMCaOR7oa9Nqntc43JKA==} engines: {node: '>= 20.19.0'} + recast@0.23.21: + resolution: {integrity: sha512-mFAyJq9vUbSTARLZUvAEf1z3YxlvAwswbmxMx2mPA/MSm4KmpwvwvhsH/NIrZhyOuwD60Lzyw2qh83uCbgTPYw==} + engines: {node: '>= 4'} + recma-build-jsx@1.0.0: resolution: {integrity: sha512-8GtdyqaBcDfva+GUKDr3nev3VpKAhup1+RvkMvUxURHpW7QyIvk9F5wz7Vzo06CEMSilw6uArgRqhpiUcWp8ew==} @@ -7926,6 +7945,10 @@ packages: resolution: {integrity: sha512-LbrmJOMUSdEVxIKvdcJzQC+nQhe8FUZQTXQy6+I75skNgn3OoQ0DZA8YnFa7gp8tqtL3KPf1kmo0R5DoApeSGQ==} engines: {node: '>=0.10.0'} + source-map@0.6.1: + resolution: {integrity: sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==} + engines: {node: '>=0.10.0'} + source-map@0.7.6: resolution: {integrity: sha512-i5uvt8C3ikiWeNZSVZNWcfZPItFQOsYTUAOkcUPGd8DqDy1uOUikjt5dG+uRlwyvR108Fb9DOd4GvXfT0N2/uQ==} engines: {node: '>= 12'} @@ -8050,6 +8073,9 @@ packages: tiny-inflate@1.0.3: resolution: {integrity: sha512-pkY1fj1cKHb2seWDy0B16HeWyczlJA9/WW3u3c4z/NiWDsO3DOU5D7nhTLE9CF0yXv/QZFY7sEJmj24dK+Rrqw==} + tiny-invariant@1.3.3: + resolution: {integrity: sha512-+FbBPE1o9QAYvviau/qC5SE3caw21q3xkvWKBtja5vgqOWIHHJ3ioaq1VPfn/Szqctz2bU/oYeKd9/z5BL+PVg==} + tinybench@6.2.2: resolution: {integrity: sha512-nIZ2N2dFpjBsg2hgitKu7mA+FvsIJuGJOwysRngmVRRmWgR/UyPjwJj8c/fT/dhm8EkHnF5EOogRf+0Z2qrimA==} engines: {node: '>=20.0.0'} @@ -12410,6 +12436,10 @@ snapshots: dependencies: solid-js: 1.9.19 + ast-types@0.16.3: + dependencies: + tslib: 2.8.1 + ast-v8-to-istanbul@1.0.7: dependencies: '@jridgewell/trace-mapping': 0.3.31 @@ -13092,6 +13122,8 @@ snapshots: escape-string-regexp@5.0.0: {} + esprima@4.0.1: {} + estree-util-attach-comments@3.0.0: dependencies: '@types/estree': 1.0.9 @@ -13944,6 +13976,12 @@ snapshots: dependencies: '@jridgewell/sourcemap-codec': 1.6.0 + magicast@0.2.11: + dependencies: + '@babel/parser': 7.29.14 + '@babel/types': 7.29.14 + recast: 0.23.21 + magicast@0.5.5: dependencies: '@babel/parser': 7.29.14 @@ -15013,6 +15051,14 @@ snapshots: readdirp@5.1.1: {} + recast@0.23.21: + dependencies: + ast-types: 0.16.3 + esprima: 4.0.1 + source-map: 0.6.1 + tiny-invariant: 1.3.3 + tslib: 2.8.1 + recma-build-jsx@1.0.0: dependencies: '@types/estree': 1.0.9 @@ -15575,6 +15621,8 @@ snapshots: source-map@0.5.7: {} + source-map@0.6.1: {} + source-map@0.7.6: {} space-separated-tokens@2.0.2: {} @@ -15710,6 +15758,8 @@ snapshots: tiny-inflate@1.0.3: {} + tiny-invariant@1.3.3: {} + tinybench@6.2.2: {} tinyclip@1.0.3: {} From 76e162b5171220390d3222e30bee02e44b79c6ba Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Thu, 26 Nov 2026 11:52:16 +0000 Subject: [PATCH 02/17] feat(cli): add the wizard's shared AST and URL helpers Port `ast-utils` and `url` from getsentry/sentry-wizard into `src/lib/wizard/utils/`. The SvelteKit, Remix, React Router, Angular, Nuxt, source maps, Cloudflare, React Native and Android wizards all use them, so they land once here and the platform PRs that follow build on them in parallel. `ast-utils` edits recast ASTs, so recast and ast-types become direct dev dependencies; both already came in through magicast. Co-Authored-By: BYK <126780+BYK@users.noreply.github.com> --- packages/cli/package.json | 2 + .../cli/src/lib/wizard/utils/ast-utils.ts | 365 ++++++++++++++++++ packages/cli/src/lib/wizard/utils/url.ts | 29 ++ .../test/lib/wizard/utils/ast-utils.test.ts | 297 ++++++++++++++ pnpm-lock.yaml | 6 + 5 files changed, 699 insertions(+) create mode 100644 packages/cli/src/lib/wizard/utils/ast-utils.ts create mode 100644 packages/cli/src/lib/wizard/utils/url.ts create mode 100644 packages/cli/test/lib/wizard/utils/ast-utils.test.ts diff --git a/packages/cli/package.json b/packages/cli/package.json index ebda846304..0e1e679f24 100644 --- a/packages/cli/package.json +++ b/packages/cli/package.json @@ -120,6 +120,7 @@ "@types/yauzl": "3.4.0", "@typescript/typescript6": "catalog:", "@vitest/coverage-v8": "catalog:", + "ast-types": "^0.16.3", "binpatch": "^0.4.2", "chalk": "^5.6.2", "cli-highlight": "^2.1.11", @@ -141,6 +142,7 @@ "pngjs": "^7.0.0", "pretty-ms": "^9.3.0", "qrcode-terminal": "^0.12.0", + "recast": "^0.23.21", "semver": "^7.8.5", "shell-quote": "^1.11.0", "string-width": "^8.2.1", diff --git a/packages/cli/src/lib/wizard/utils/ast-utils.ts b/packages/cli/src/lib/wizard/utils/ast-utils.ts new file mode 100644 index 0000000000..05929e5203 --- /dev/null +++ b/packages/cli/src/lib/wizard/utils/ast-utils.ts @@ -0,0 +1,365 @@ +/** + * Helpers that find and change nodes in a recast AST, shared by the wizards + * that edit JavaScript and TypeScript config files. + */ + +import { existsSync } from "node:fs"; + +import recast from "recast"; + +import { debug } from "./debug.js"; +import type { namedTypes as t } from "ast-types"; + +const b = recast.types.builders; + +/** + * Checks if a file where we don't know its concrete file type yet exists + * and returns the full path to the file with the correct file type. + */ +export function findFile( + filePath: string, + fileTypes: string[] = [".js", ".ts", ".mjs", ".cjs"], +): string | undefined { + return fileTypes + .map((type) => `${filePath}${type}`) + .find((file) => existsSync(file)); +} + +/** + * checks for require('@sentry/*') syntax + */ +export function hasSentryContent(program: t.Program): boolean { + let foundSentry: boolean | undefined = false; + recast.visit(program, { + visitStringLiteral(path) { + foundSentry = foundSentry || path.node.value.startsWith("@sentry/"); + this.traverse(path); + }, + visitLiteral(path) { + foundSentry = + foundSentry || path.node.value?.toString().startsWith("@sentry/"); + this.traverse(path); + }, + }); + + return !!foundSentry; +} + +/** + * Searches for a property of an ObjectExpression by name + * + * @param object the ObjectExpression to search in + * @param name the name of the property to search for + * + * @returns the property if it exists + */ +export function getObjectProperty( + object: t.ObjectExpression, + name: string, +): t.Property | undefined { + return object.properties.find((p): p is t.Property => { + const isObjectProp = p.type === "Property" || p.type === "ObjectProperty"; + + if (!isObjectProp) { + return false; + } + + const hasMatchingLiteralKey = + (p.key.type === "Literal" || p.key.type === "StringLiteral") && + p.key.value === name; + + if (hasMatchingLiteralKey) { + return true; + } + + // has matching identifier key + return p.key.type === "Identifier" && p.key.name === name; + }); +} + +/** + * Attempts to find a property of an ObjectExpression by name. If it doesn't exist, + * the property will be added to the ObjectExpression with the provided default value. + * + * @param object the parent object expression to search in + * @param name the name of the property to search for + * @param defaultValue the default value to set if the property doesn't exist + * + * @returns the + */ +export function getOrSetObjectProperty( + object: t.ObjectExpression, + name: string, + defaultValue: + | t.Literal + | t.BooleanLiteral + | t.StringLiteral + | t.ObjectExpression, +): t.Property { + const existingProperty = getObjectProperty(object, name); + + if (existingProperty) { + return existingProperty; + } + + const newProperty = b.property.from({ + kind: "init", + key: b.stringLiteral(name), + value: defaultValue, + }); + + object.properties.push(newProperty); + + return newProperty; +} + +/** + * Sets a property of an ObjectExpression if it exists, otherwise adds it + * to the ObjectExpression. Optionally, a comment can be added to the + * property. + * + * @param object the ObjectExpression to set the property on + * @param name the name of the property to set + * @param value the value of the property to set + * @param comment (optional) a comment to add to the property + */ +export function setOrUpdateObjectProperty( + object: t.ObjectExpression, + name: string, + value: + | t.Literal + | t.BooleanLiteral + | t.StringLiteral + | t.ObjectExpression + | t.ArrayExpression, + comment?: string, +): void { + const newComments = comment + ?.split("\n") + .map((c) => b.commentLine(` ${c}`, true, false)); + + const existingProperty = getObjectProperty(object, name); + + if (existingProperty) { + existingProperty.value = value; + if (newComments) { + existingProperty.comments = [ + ...(existingProperty.comments ?? []), + ...newComments, + ]; + } + } else { + object.properties.push( + b.objectProperty.from({ + key: b.stringLiteral(name), + value, + ...(newComments && { + comments: newComments, + }), + }), + ); + } +} + +type JsonCParseResult = + | { + jsonObject: t.ObjectExpression; + ast: t.Program; + } + | { + jsonObject: undefined; + ast: undefined; + }; + +/** + * Parses a JSON string with (potential) comments (JSON-C) and returns the JS AST + * that can be walked and modified with recast like a normal JS AST. + * + * This is done by wrapping the JSON-C string in parentheses, thereby making it + * a JS `Program` with an `ExpressionStatement` as its body. The expression is then + * extracted from the AST and returned alongside the AST. + * + * To preserve as much original formatting as possible, the returned `ast` + * property should be passed to {@link `printJsonC`} to get the JSON-C string back. + * + * If the input is not valid JSON-C, the result will be undefined. + * + * @see {@link JsonCParseResult} + * + * @param jsonString a JSON-C string + * + * @returns a {@link JsonCParseResult}, containing either the JSON-C object and the AST or undefined in both cases + */ +export function parseJsonC(jsonString: string): JsonCParseResult { + try { + const jsTsConfig = `(${jsonString})`; + // no idea why recast returns any here, this is dumb :/ + const ast = recast.parse(jsTsConfig.toString()).program as t.Program; + + const statement = ast.body[0]; + const jsonObject = + statement?.type === "ExpressionStatement" && + statement.expression.type === "ObjectExpression" + ? statement.expression + : undefined; + + if (jsonObject) { + return { jsonObject, ast }; + } + } catch (error) { + // Not valid JSON-C: the caller handles the undefined result. + debug(error); + return { jsonObject: undefined, ast: undefined }; + } + return { jsonObject: undefined, ast: undefined }; +} + +/** + * Takes the AST of a parsed JSON-C "program" and returns the JSON-C string without + * any of the temporary JS wrapper code that was previously applied. + * + * Only use this in conjunction with {@link `parseJsonC`} + * + * @param ast the `ast` returned from {@link `parseJsonC`} + * + * @returns the JSON-C string + */ +export function printJsonC(ast: t.Program): string { + const js = recast.print(ast).code; + return js.substring(1, js.length - 1); +} + +/** + * Walks the program body and returns index of the last variable assignment initialized by require statement. + * Only counts top level require statements. + * + * @returns index of the last `const foo = require('bar');` statement or -1 if none was found. + */ +export function getLastRequireIndex(program: t.Program): number { + let lastRequireIdex = -1; + program.body.forEach((s, i) => { + const declaration = + s.type === "VariableDeclaration" ? s.declarations[0] : undefined; + if ( + declaration?.type === "VariableDeclarator" && + declaration.init?.type === "CallExpression" && + declaration.init.callee.type === "Identifier" && + declaration.init.callee.name === "require" + ) { + lastRequireIdex = i; + } + }); + return lastRequireIdex; +} + +/** + * Safely checks if a callee is an identifier with the given name + * Prevents crashes when accessing callee.name on non-identifier nodes + */ +export function safeCalleeIdentifierMatch( + callee: unknown, + name: string, +): boolean { + return Boolean( + callee && + typeof callee === "object" && + "type" in callee && + (callee as { type: string }).type === "Identifier" && + "name" in callee && + (callee as { name: string }).name === name, + ); +} + +/** + * Safely gets the name of an identifier node + * Returns null if the node is not an identifier or is undefined + */ +export function safeGetIdentifierName(node: unknown): string | null { + return node && + typeof node === "object" && + "type" in node && + node.type === "Identifier" && + "name" in node + ? String(node.name) + : null; +} + +/** + * Safely access function body array with proper validation + * Prevents crashes when accessing body.body on nodes that don't have a body + */ +export function safeGetFunctionBody(node: unknown): t.Statement[] | null { + if (!node || typeof node !== "object" || !("body" in node)) { + return null; + } + + const nodeBody = node.body; + if (!nodeBody || typeof nodeBody !== "object" || !("body" in nodeBody)) { + return null; + } + + const bodyArray = nodeBody.body; + return Array.isArray(bodyArray) ? (bodyArray as t.Statement[]) : null; +} + +/** + * Safely insert statement before last statement in function body + * Typically used to insert code before a return statement + * Returns true if insertion was successful, false otherwise + */ +export function safeInsertBeforeReturn( + body: t.Statement[], + statement: t.Statement, +): boolean { + if (body.length === 0) { + return false; + } + + // Insert before the last statement (typically a return statement) + const insertIndex = Math.max(0, body.length - 1); + body.splice(insertIndex, 0, statement); + return true; +} + +/** + * Finds a property in an ObjectExpression by name. + * Commonly used for traversing Vite/React Router config objects. + * + * @param configObj - The ObjectExpression to search + * @param name - The property name to find + * @returns The matching ObjectProperty, or undefined if not found + */ +export function findProperty( + configObj: t.ObjectExpression, + name: string, +): t.ObjectProperty | undefined { + return configObj.properties.find( + (p) => + p.type === "ObjectProperty" && + p.key.type === "Identifier" && + p.key.name === name, + ) as t.ObjectProperty | undefined; // Safe: predicate guarantees type +} + +/** + * Preserves trailing newline from original content if present. + * Code generators like magicast/recast don't preserve trailing newlines, + * so this ensures we don't unnecessarily modify user files. + * + * @param originalContent - The original file content + * @param generatedCode - The code generated by AST transformation + * @returns The generated code with trailing newline preserved if original had one + */ +export function preserveTrailingNewline( + originalContent: string, + generatedCode: string, +): string { + const hadTrailingNewline = originalContent.endsWith("\n"); + const hasTrailingNewline = generatedCode.endsWith("\n"); + + if (hadTrailingNewline && !hasTrailingNewline) { + return generatedCode + "\n"; + } + + return generatedCode; +} diff --git a/packages/cli/src/lib/wizard/utils/url.ts b/packages/cli/src/lib/wizard/utils/url.ts new file mode 100644 index 0000000000..6d3af99d64 --- /dev/null +++ b/packages/cli/src/lib/wizard/utils/url.ts @@ -0,0 +1,29 @@ +/** + * Sentry URLs the wizards print after setup. + */ + +/** + * Returns the url to the Sentry project stream. + * + * Example: https://org-slug.sentry.io/issues/?project=1234567 + */ +export function getIssueStreamUrl({ + url, + orgSlug, + projectId, +}: { + url: string; + orgSlug: string; + projectId: string; +}): string { + const urlObject = new URL(url); + if (urlObject.host === "sentry.io") { + urlObject.host = `${orgSlug}.${urlObject.host}`; + urlObject.pathname = "/issues/"; + } else { + urlObject.pathname = `/organizations/${orgSlug}/issues/`; + } + urlObject.searchParams.set("project", projectId); + + return urlObject.toString(); +} diff --git a/packages/cli/test/lib/wizard/utils/ast-utils.test.ts b/packages/cli/test/lib/wizard/utils/ast-utils.test.ts new file mode 100644 index 0000000000..f42f1de88a --- /dev/null +++ b/packages/cli/test/lib/wizard/utils/ast-utils.test.ts @@ -0,0 +1,297 @@ +import { + getObjectProperty, + getOrSetObjectProperty, + hasSentryContent, + parseJsonC, + preserveTrailingNewline, + printJsonC, + setOrUpdateObjectProperty, +} from "../../../../src/lib/wizard/utils/ast-utils.js"; + +import recast from "recast"; +const b = recast.types.builders; + +import { describe, it, expect } from "vitest"; + +describe("hasSentryContent", () => { + it.each([ + ` + const { sentryVitePlugin } = require("@sentry/bundler-plugins/vite"); + const somethingelse = require('gs'); + `, + ` + import { sentryVitePlugin } from "@sentry/bundler-plugins/vite"; + import * as somethingelse from 'gs'; + + export default { + plugins: [sentryVitePlugin()] + } + `, + ])( + "returns true if a require('@sentry/') call was found in the parsed module", + (code) => { + // recast.parse returns a Program node (or fails) but it's badly typed as any + const program = recast.parse(code) + .program as recast.types.namedTypes.Program; + expect(hasSentryContent(program)).toBe(true); + }, + ); + + it.each([ + `const whatever = require('something')`, + `// const {sentryWebpackPlugin} = require('@sentry/bundler-plugins/webpack')`, + `const {sAntryWebpackPlugin} = require('webpack-plugin-@sentry')`, + ` + import * as somethingelse from 'gs'; + export default { + plugins: [] + } + `, + `import * as somethingelse from 'gs'; + // import { sentryVitePlugin } from "@sentry/bundler-plugins/vite" + export default { + plugins: [] + } + `, + `import * as thirdPartyVitePlugin from "vite-plugin-@sentry" + export default { + plugins: [thirdPartyVitePlugin()] + } + `, + ])( + "returns false if the file doesn't contain any require('@sentry/') calls", + (code) => { + // recast.parse returns a Program node (or fails) but it's badly typed as any + const program = recast.parse(code) + .program as recast.types.namedTypes.Program; + expect(hasSentryContent(program)).toBe(false); + }, + ); +}); + +describe("getObjectProperty", () => { + it.each([ + [ + "literal", + b.objectExpression([ + b.objectProperty(b.identifier("foo"), b.stringLiteral("bar")), + b.objectProperty( + b.stringLiteral("needle"), + b.stringLiteral("haystack"), + ), + ]), + ], + [ + "stringLiteral", + b.objectExpression([ + b.objectProperty(b.identifier("foo"), b.stringLiteral("bar")), + b.objectProperty(b.literal("needle"), b.stringLiteral("haystack")), + ]), + ], + [ + "identifier", + b.objectExpression([ + b.objectProperty(b.identifier("foo"), b.stringLiteral("bar")), + b.objectProperty(b.identifier("needle"), b.stringLiteral("haystack")), + ]), + ], + ])("returns the poperty (%s) if it exists", (_, object) => { + const property = getObjectProperty(object, "needle"); + expect(property).toBeDefined(); + // @ts-expect-error we know it's defined due to the expect above + expect(recast.print(property).code).toEqual( + expect.stringContaining("needle"), + ); + }); + + it("returns undefined if the property does not exist", () => { + const object = b.objectExpression([ + b.objectProperty(b.identifier("foo"), b.stringLiteral("bar")), + ]); + const property = getObjectProperty(object, "needle"); + expect(property).toBeUndefined(); + }); + + it("handles objects without simple properties", () => { + const object = b.objectExpression([b.spreadElement(b.identifier("foo"))]); + const property = getObjectProperty(object, "needle"); + expect(property).toBeUndefined(); + }); +}); + +describe("getOrSetObjectProperty", () => { + it("returns the property if it exists", () => { + const object = b.objectExpression([ + b.objectProperty(b.identifier("needle"), b.stringLiteral("haystack")), + ]); + + const property = getOrSetObjectProperty( + object, + "needle", + b.stringLiteral("nope"), + ); + + expect(property).toBeDefined(); + expect(property.type).toBe("ObjectProperty"); + // @ts-expect-error we know its type + expect(property.key.name).toBe("needle"); + // @ts-expect-error we know its type + expect(property.value.value).toBe("haystack"); + }); + + it("adds the property if it does not exist", () => { + const object = b.objectExpression([ + b.objectProperty(b.identifier("foo"), b.stringLiteral("bar")), + ]); + + const property = getOrSetObjectProperty( + object, + "needle", + b.stringLiteral("haystack"), + ); + + expect(property).toBeDefined(); + expect(property.type).toBe("Property"); + // @ts-expect-error we know its type + expect(property.key.value).toBe("needle"); + // @ts-expect-error we know its type + expect(property.value.value).toBe("haystack"); + }); +}); + +describe("setOrUpdateObjectProperty", () => { + it("sets a new property if it does not exist yet", () => { + const object = b.objectExpression([ + b.objectProperty(b.identifier("foo"), b.stringLiteral("bar")), + ]); + + setOrUpdateObjectProperty(object, "needle", b.stringLiteral("haystack")); + + expect(getObjectProperty(object, "needle")).toBeDefined(); + }); + + it("updates an existing property if it exists", () => { + const object = b.objectExpression([ + b.objectProperty(b.identifier("foo"), b.stringLiteral("bar")), + b.objectProperty(b.identifier("needle"), b.stringLiteral("haystack")), + ]); + + setOrUpdateObjectProperty(object, "needle", b.stringLiteral("haystack2")); + + const property = getObjectProperty(object, "needle"); + // @ts-expect-error it must be defiend, otherwise we fail anyway + expect(property?.value.value).toBe("haystack2"); + }); + + it("adds a comment to the existing property if provided", () => { + const object = b.objectExpression([ + b.objectProperty(b.identifier("foo"), b.stringLiteral("bar")), + ]); + + setOrUpdateObjectProperty( + object, + "needle", + b.stringLiteral("haystack"), + "This is a comment", + ); + + const property = getObjectProperty(object, "needle"); + expect(property?.comments).toHaveLength(1); + // @ts-expect-error it must be defiend, otherwise we fail anyway + expect(property?.comments[0].value).toBe(" This is a comment"); + }); + + it("adds a comment to the new property if provided", () => { + const object = b.objectExpression([ + b.objectProperty(b.identifier("foo"), b.stringLiteral("bar")), + ]); + + setOrUpdateObjectProperty( + object, + "needle", + b.stringLiteral("haystack"), + "This is a comment", + ); + + const property = getObjectProperty(object, "needle"); + expect(property?.comments).toHaveLength(1); + // @ts-expect-error it must be defiend, otherwise we fail anyway + expect(property?.comments[0].value).toBe(" This is a comment"); + }); +}); + +describe("preserveTrailingNewline", () => { + it("adds trailing newline if original had one but generated does not", () => { + const original = "const foo = 1;\n"; + const generated = "const foo = 1;"; + expect(preserveTrailingNewline(original, generated)).toBe( + "const foo = 1;\n", + ); + }); + + it("does not add trailing newline if original did not have one", () => { + const original = "const foo = 1;"; + const generated = "const foo = 1;"; + expect(preserveTrailingNewline(original, generated)).toBe("const foo = 1;"); + }); + + it("does not double trailing newline if both already have one", () => { + const original = "const foo = 1;\n"; + const generated = "const foo = 1;\n"; + expect(preserveTrailingNewline(original, generated)).toBe( + "const foo = 1;\n", + ); + }); + + it("does not remove trailing newline if original did not have one but generated does", () => { + const original = "const foo = 1;"; + const generated = "const foo = 1;\n"; + expect(preserveTrailingNewline(original, generated)).toBe( + "const foo = 1;\n", + ); + }); +}); + +describe("parse and print JSON-C", () => { + it.each([ + ["simple JSON", "{'foo': 'bar'}"], + [ + "JSON-C with inline comment", + ` + { + "foo": "bar" // with an inline comment + } + `, + ], + [ + "JSON-C with multiple comments", + ` + /* + * let's throw in a block comment for good measure + */ + { + // one line comment + "foo": "bar", // another inline comment + /* one more here */ + "dogs": /* and here */ "awesome", + } + /* and here */ + `, + ], + ])(`parses and prints JSON-C (%s)`, (_, json) => { + const { ast, jsonObject } = parseJsonC(json); + expect(ast?.type).toBe("Program"); + expect(jsonObject).toBeDefined(); + expect(jsonObject?.type).toBe("ObjectExpression"); + // @ts-expect-error we know it's defined due to the expect above + expect(printJsonC(ast)).toEqual(json); + }); + + it("returns undefined if the input is not valid JSON-C", () => { + const { ast, jsonObject } = parseJsonC(`{ + "invalid": // "json" + }`); + expect(ast).toBeUndefined(); + expect(jsonObject).toBeUndefined(); + }); +}); diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 363032cd0d..aa38f64862 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -759,6 +759,9 @@ importers: '@vitest/coverage-v8': specifier: 'catalog:' version: 5.0.5(vitest@5.0.5) + ast-types: + specifier: ^0.16.3 + version: 0.16.3 binpatch: specifier: ^0.4.2 version: 0.4.2 @@ -822,6 +825,9 @@ importers: qrcode-terminal: specifier: ^0.12.0 version: 0.12.0 + recast: + specifier: ^0.23.21 + version: 0.23.21 semver: specifier: ^7.8.5 version: 7.8.5 From 0113841962a00723228ae9299ee17ac663191c81 Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Thu, 26 Nov 2026 12:11:49 +0000 Subject: [PATCH 03/17] 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 c327e567fe1a25a7aad700b0e8abad368a2ecd38 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:17:06 +0000 Subject: [PATCH 04/17] feat(cli): add SvelteKit, Remix and React Router to sentry wizard Port the SvelteKit, Remix and React Router flows of getsentry/sentry-wizard 9.1.0 into `src/lib/wizard/` with their tests, and register them as the `sveltekit`, `remix` and `reactRouter` runners of `sentry wizard`. The flows take the same options `@sentry/wizard` passed them, and like upstream they stop with a notice under `--spotlight` (`utils/abort-if-sportlight-not-supported.ts` comes over for that). Changes from upstream: - Remix with a Vite config used the source maps wizard's Vite setup, which isn't in the CLI yet. It now writes `.env.sentry-build-plugin` and points to the manual source map steps instead. - The AST code is typed with ast-types instead of `@babel/types`, which the CLI doesn't depend on; node printing that magicast's `generateCode` did on bare nodes goes through `recast.print`, which is what `generateCode` calls for them. - Failures that went to `Sentry.captureException` go through `reportCliError`. - The SvelteKit fallback for `instrumentation.server` named the file `.ts` even in JavaScript projects; it now uses the project's ending. The upstream test fixtures are kept byte for byte, so formatting, lint and type checks skip `test/lib/wizard/**/fixtures/`. Co-Authored-By: BYK <126780+BYK@users.noreply.github.com> --- .oxfmtrc.json | 1 + .oxlintrc.json | 3 +- .../react-router/codemods/client.entry.ts | 214 +++ .../codemods/react-router-config.ts | 227 ++++ .../react-router/codemods/routes-config.ts | 107 ++ .../react-router/codemods/server-entry.ts | 437 ++++++ .../lib/wizard/react-router/codemods/utils.ts | 17 + .../lib/wizard/react-router/codemods/vite.ts | 270 ++++ .../react-router/react-router-wizard.ts | 504 +++++++ .../lib/wizard/react-router/sdk-example.ts | 337 +++++ .../src/lib/wizard/react-router/sdk-setup.ts | 442 ++++++ .../lib/wizard/react-router/sdk-version.ts | 37 + .../src/lib/wizard/react-router/templates.ts | 380 ++++++ .../wizard/remix/codemods/express-server.ts | 46 + .../lib/wizard/remix/codemods/handle-error.ts | 104 ++ .../cli/src/lib/wizard/remix/codemods/root.ts | 244 ++++ .../cli/src/lib/wizard/remix/remix-wizard.ts | 318 +++++ .../cli/src/lib/wizard/remix/sdk-example.ts | 266 ++++ .../cli/src/lib/wizard/remix/sdk-setup.ts | 569 ++++++++ .../cli/src/lib/wizard/remix/templates.ts | 15 + packages/cli/src/lib/wizard/remix/utils.ts | 102 ++ packages/cli/src/lib/wizard/run.ts | 14 + .../src/lib/wizard/sveltekit/sdk-example.ts | 63 + .../lib/wizard/sveltekit/sdk-setup/setup.ts | 695 ++++++++++ .../sveltekit/sdk-setup/svelte-config.ts | 397 ++++++ .../lib/wizard/sveltekit/sdk-setup/types.ts | 15 + .../lib/wizard/sveltekit/sdk-setup/utils.ts | 29 + .../lib/wizard/sveltekit/sdk-setup/vite.ts | 156 +++ .../lib/wizard/sveltekit/sveltekit-wizard.ts | 299 ++++ .../cli/src/lib/wizard/sveltekit/templates.ts | 369 +++++ .../cli/src/lib/wizard/sveltekit/utils.ts | 117 ++ .../abort-if-sportlight-not-supported.ts | 20 + packages/cli/test/commands/wizard.test.ts | 33 +- .../codemods/client-entry.test.ts | 368 +++++ .../codemods/fixtures/client-entry/basic.tsx | 12 + .../fixtures/client-entry/complex.tsx | 30 + .../fixtures/client-entry/no-imports.tsx | 6 + .../fixtures/client-entry/with-imports.tsx | 13 + .../fixtures/client-entry/with-sentry.tsx | 18 + .../server-entry/already-instrumented.tsx | 28 + .../codemods/fixtures/server-entry/basic.tsx | 23 + .../server-entry/entry-server-basic.ts | 5 + .../fixtures/server-entry/variable-export.tsx | 31 + .../codemods/react-router-config.test.ts | 221 +++ .../codemods/server-entry.test.ts | 683 ++++++++++ .../wizard/react-router/codemods/vite.test.ts | 314 +++++ .../wizard/react-router/routes-config.test.ts | 195 +++ .../lib/wizard/react-router/sdk-setup.test.ts | 741 ++++++++++ .../wizard/react-router/sdk-version.test.ts | 34 + .../lib/wizard/react-router/templates.test.ts | 473 +++++++ .../lib/wizard/remix/build-script.test.ts | 142 ++ .../lib/wizard/remix/client-entry.test.ts | 184 +++ .../remix/fixtures/root-already-wrapped.tsx | 8 + .../remix/fixtures/root-no-error-boundary.tsx | 5 + .../fixtures/root-variable-error-boundary.tsx | 11 + .../fixtures/root-with-error-boundary.tsx | 9 + .../root-with-sentry-error-boundary.tsx | 11 + .../cli/test/lib/wizard/remix/root.test.ts | 311 +++++ .../remix/server-instrumentation.test.ts | 79 ++ .../sveltekit/sdk-setup/svelte-config.test.ts | 664 +++++++++ .../wizard/sveltekit/sdk-setup/vite.test.ts | 111 ++ .../lib/wizard/sveltekit/templates.test.ts | 1201 +++++++++++++++++ .../test/lib/wizard/sveltekit/utils.test.ts | 143 ++ packages/cli/test/tsconfig.json | 3 +- 64 files changed, 12920 insertions(+), 4 deletions(-) create mode 100644 packages/cli/src/lib/wizard/react-router/codemods/client.entry.ts create mode 100644 packages/cli/src/lib/wizard/react-router/codemods/react-router-config.ts create mode 100644 packages/cli/src/lib/wizard/react-router/codemods/routes-config.ts create mode 100644 packages/cli/src/lib/wizard/react-router/codemods/server-entry.ts create mode 100644 packages/cli/src/lib/wizard/react-router/codemods/utils.ts create mode 100644 packages/cli/src/lib/wizard/react-router/codemods/vite.ts create mode 100644 packages/cli/src/lib/wizard/react-router/react-router-wizard.ts create mode 100644 packages/cli/src/lib/wizard/react-router/sdk-example.ts create mode 100644 packages/cli/src/lib/wizard/react-router/sdk-setup.ts create mode 100644 packages/cli/src/lib/wizard/react-router/sdk-version.ts create mode 100644 packages/cli/src/lib/wizard/react-router/templates.ts create mode 100644 packages/cli/src/lib/wizard/remix/codemods/express-server.ts create mode 100644 packages/cli/src/lib/wizard/remix/codemods/handle-error.ts create mode 100644 packages/cli/src/lib/wizard/remix/codemods/root.ts create mode 100644 packages/cli/src/lib/wizard/remix/remix-wizard.ts create mode 100644 packages/cli/src/lib/wizard/remix/sdk-example.ts create mode 100644 packages/cli/src/lib/wizard/remix/sdk-setup.ts create mode 100644 packages/cli/src/lib/wizard/remix/templates.ts create mode 100644 packages/cli/src/lib/wizard/remix/utils.ts create mode 100644 packages/cli/src/lib/wizard/sveltekit/sdk-example.ts create mode 100644 packages/cli/src/lib/wizard/sveltekit/sdk-setup/setup.ts create mode 100644 packages/cli/src/lib/wizard/sveltekit/sdk-setup/svelte-config.ts create mode 100644 packages/cli/src/lib/wizard/sveltekit/sdk-setup/types.ts create mode 100644 packages/cli/src/lib/wizard/sveltekit/sdk-setup/utils.ts create mode 100644 packages/cli/src/lib/wizard/sveltekit/sdk-setup/vite.ts create mode 100644 packages/cli/src/lib/wizard/sveltekit/sveltekit-wizard.ts create mode 100644 packages/cli/src/lib/wizard/sveltekit/templates.ts create mode 100644 packages/cli/src/lib/wizard/sveltekit/utils.ts create mode 100644 packages/cli/src/lib/wizard/utils/abort-if-sportlight-not-supported.ts create mode 100644 packages/cli/test/lib/wizard/react-router/codemods/client-entry.test.ts create mode 100644 packages/cli/test/lib/wizard/react-router/codemods/fixtures/client-entry/basic.tsx create mode 100644 packages/cli/test/lib/wizard/react-router/codemods/fixtures/client-entry/complex.tsx create mode 100644 packages/cli/test/lib/wizard/react-router/codemods/fixtures/client-entry/no-imports.tsx create mode 100644 packages/cli/test/lib/wizard/react-router/codemods/fixtures/client-entry/with-imports.tsx create mode 100644 packages/cli/test/lib/wizard/react-router/codemods/fixtures/client-entry/with-sentry.tsx create mode 100644 packages/cli/test/lib/wizard/react-router/codemods/fixtures/server-entry/already-instrumented.tsx create mode 100644 packages/cli/test/lib/wizard/react-router/codemods/fixtures/server-entry/basic.tsx create mode 100644 packages/cli/test/lib/wizard/react-router/codemods/fixtures/server-entry/entry-server-basic.ts create mode 100644 packages/cli/test/lib/wizard/react-router/codemods/fixtures/server-entry/variable-export.tsx create mode 100644 packages/cli/test/lib/wizard/react-router/codemods/react-router-config.test.ts create mode 100644 packages/cli/test/lib/wizard/react-router/codemods/server-entry.test.ts create mode 100644 packages/cli/test/lib/wizard/react-router/codemods/vite.test.ts create mode 100644 packages/cli/test/lib/wizard/react-router/routes-config.test.ts create mode 100644 packages/cli/test/lib/wizard/react-router/sdk-setup.test.ts create mode 100644 packages/cli/test/lib/wizard/react-router/sdk-version.test.ts create mode 100644 packages/cli/test/lib/wizard/react-router/templates.test.ts create mode 100644 packages/cli/test/lib/wizard/remix/build-script.test.ts create mode 100644 packages/cli/test/lib/wizard/remix/client-entry.test.ts create mode 100644 packages/cli/test/lib/wizard/remix/fixtures/root-already-wrapped.tsx create mode 100644 packages/cli/test/lib/wizard/remix/fixtures/root-no-error-boundary.tsx create mode 100644 packages/cli/test/lib/wizard/remix/fixtures/root-variable-error-boundary.tsx create mode 100644 packages/cli/test/lib/wizard/remix/fixtures/root-with-error-boundary.tsx create mode 100644 packages/cli/test/lib/wizard/remix/fixtures/root-with-sentry-error-boundary.tsx create mode 100644 packages/cli/test/lib/wizard/remix/root.test.ts create mode 100644 packages/cli/test/lib/wizard/remix/server-instrumentation.test.ts create mode 100644 packages/cli/test/lib/wizard/sveltekit/sdk-setup/svelte-config.test.ts create mode 100644 packages/cli/test/lib/wizard/sveltekit/sdk-setup/vite.test.ts create mode 100644 packages/cli/test/lib/wizard/sveltekit/templates.test.ts create mode 100644 packages/cli/test/lib/wizard/sveltekit/utils.test.ts diff --git a/.oxfmtrc.json b/.oxfmtrc.json index b27ad9c221..accc5db075 100644 --- a/.oxfmtrc.json +++ b/.oxfmtrc.json @@ -14,6 +14,7 @@ "packages/mcp-server-mocks/src/fixtures/**", "packages/mcp-core/src/ui/chart-app.generated.ts", "packages/codemod-cli3to4/tests/**", + "packages/cli/test/lib/wizard/**/fixtures/**", "**/worker-configuration.d.ts", "**/tsconfig*.json" ] diff --git a/.oxlintrc.json b/.oxlintrc.json index ff2085d067..7f682733fd 100644 --- a/.oxlintrc.json +++ b/.oxlintrc.json @@ -14,7 +14,8 @@ "**/tsconfig*.json", "packages/mcp-server-mocks/src/fixtures/**", "packages/mcp-core/src/ui/chart-app.generated.ts", - "packages/codemod-cli3to4/tests/**" + "packages/codemod-cli3to4/tests/**", + "packages/cli/test/lib/wizard/**/fixtures/**" ], "rules": { "no-unused-vars": [ diff --git a/packages/cli/src/lib/wizard/react-router/codemods/client.entry.ts b/packages/cli/src/lib/wizard/react-router/codemods/client.entry.ts new file mode 100644 index 0000000000..30d57487ab --- /dev/null +++ b/packages/cli/src/lib/wizard/react-router/codemods/client.entry.ts @@ -0,0 +1,214 @@ +/** + * Adds `Sentry.init` and the HydratedRouter error handler to a React Router + * app's `entry.client` file. + */ + +import recast from "recast"; +import type { namedTypes as t } from "ast-types"; +import type { ExpressionKind } from "ast-types/lib/gen/kinds"; + +import { clack } from "../../utils/clack/prompts.js"; +import chalk from "chalk"; + +import { loadFile, writeFile } from "magicast"; +import { hasSentryContent } from "../../utils/ast-utils.js"; +import { getDataCollectionBlock } from "../templates.js"; +import { getAfterImportsInsertionIndex } from "./utils.js"; + +// oxlint-disable-next-line max-params -- positional like the sentry-wizard original and its tests +export async function instrumentClientEntry( + clientEntryPath: string, + dsn: string, + enableTracing: boolean, + enableReplay: boolean, + reduceDataCollection: boolean, + useInstrumentationAPI = false, + useOnError = false, +): Promise { + const clientEntryAst = await loadFile(clientEntryPath); + + const alreadyHasSentry = hasSentryContent(clientEntryAst.$ast as t.Program); + + if (!alreadyHasSentry) { + clientEntryAst.imports.$add({ + from: "@sentry/react-router", + imported: "*", + local: "Sentry", + }); + + let initContent: string; + + if (useInstrumentationAPI && enableTracing) { + const integrations = ["tracing"]; + if (enableReplay) { + integrations.push("Sentry.replayIntegration()"); + } + + initContent = ` +const tracing = Sentry.reactRouterTracingIntegration(); + +Sentry.init({ + dsn: "${dsn}", +${getDataCollectionBlock(reduceDataCollection)} + integrations: [${integrations.join(", ")}], + tracesSampleRate: 1.0, + tracePropagationTargets: [/^\\//, /^https:\\/\\/yourserver\\.io\\/api/],${ + enableReplay + ? "\n replaysSessionSampleRate: 0.1,\n replaysOnErrorSampleRate: 1.0," + : "" + } +});`; + } else { + const integrations = []; + if (enableTracing) { + integrations.push("Sentry.reactRouterTracingIntegration()"); + } + if (enableReplay) { + integrations.push("Sentry.replayIntegration()"); + } + + initContent = ` +Sentry.init({ + dsn: "${dsn}", +${getDataCollectionBlock(reduceDataCollection)} + integrations: [${integrations.join(", ")}], + tracesSampleRate: ${enableTracing ? "1.0" : "0"},${ + enableTracing + ? "\n tracePropagationTargets: [/^\\//, /^https:\\/\\/yourserver\\.io\\/api/]," + : "" + }${ + enableReplay + ? "\n replaysSessionSampleRate: 0.1,\n replaysOnErrorSampleRate: 1.0," + : "" + } +});`; + } + + (clientEntryAst.$ast as t.Program).body.splice( + getAfterImportsInsertionIndex(clientEntryAst.$ast as t.Program), + 0, + ...recast.parse(initContent).program.body, + ); + } + + const useInstrAPI = useInstrumentationAPI && enableTracing; + const addInstrProp = useInstrAPI && !alreadyHasSentry; + + if (addInstrProp) { + addInstrumentationPropsToHydratedRouter(clientEntryAst.$ast as t.Program); + } + + if (useOnError) { + addOnErrorToHydratedRouter(clientEntryAst.$ast as t.Program); + } + + // Emit a single warning if HydratedRouter wasn't found for any prop we tried to add + if ( + (addInstrProp || useOnError) && + !hasHydratedRouter(clientEntryAst.$ast as t.Program) + ) { + const props: string[] = []; + if (useOnError) { + props.push("onError={Sentry.sentryOnError}"); + } + if (addInstrProp) { + props.push("instrumentations={[tracing.clientInstrumentation]}"); + } + clack.log.warn( + `Could not find ${chalk.cyan( + "HydratedRouter", + )} component in your client entry file.\n` + + `Manually add the following props:\n` + + ` ${chalk.green(``)}`, + ); + } + + await writeFile(clientEntryAst.$ast, clientEntryPath); +} + +function hasHydratedRouter(ast: t.Program): boolean { + let found = false; + recast.visit(ast, { + visitJSXElement(path) { + const name = path.node.openingElement.name; + if (name.type === "JSXIdentifier" && name.name === "HydratedRouter") { + found = true; + return false; + } + this.traverse(path); + return undefined; + }, + }); + return found; +} + +function addPropToHydratedRouter( + ast: t.Program, + propName: string, + propValue: ExpressionKind, +): boolean { + let found = false; + + recast.visit(ast, { + visitJSXElement(path) { + const openingElement = path.node.openingElement; + + if ( + openingElement.name.type === "JSXIdentifier" && + openingElement.name.name === "HydratedRouter" + ) { + found = true; + + const hasProp = openingElement.attributes?.some( + (attr) => + attr.type === "JSXAttribute" && + attr.name.type === "JSXIdentifier" && + attr.name.name === propName, + ); + + if (!hasProp) { + const prop = recast.types.builders.jsxAttribute( + recast.types.builders.jsxIdentifier(propName), + recast.types.builders.jsxExpressionContainer(propValue), + ); + + if (!openingElement.attributes) { + openingElement.attributes = []; + } + openingElement.attributes.push(prop); + } + + return false; + } + + this.traverse(path); + return undefined; + }, + }); + + return found; +} + +function addOnErrorToHydratedRouter(ast: t.Program): boolean { + return addPropToHydratedRouter( + ast, + "onError", + recast.types.builders.memberExpression( + recast.types.builders.identifier("Sentry"), + recast.types.builders.identifier("sentryOnError"), + ), + ); +} + +function addInstrumentationPropsToHydratedRouter(ast: t.Program): boolean { + return addPropToHydratedRouter( + ast, + "instrumentations", + recast.types.builders.arrayExpression([ + recast.types.builders.memberExpression( + recast.types.builders.identifier("tracing"), + recast.types.builders.identifier("clientInstrumentation"), + ), + ]), + ); +} diff --git a/packages/cli/src/lib/wizard/react-router/codemods/react-router-config.ts b/packages/cli/src/lib/wizard/react-router/codemods/react-router-config.ts new file mode 100644 index 0000000000..93726591f1 --- /dev/null +++ b/packages/cli/src/lib/wizard/react-router/codemods/react-router-config.ts @@ -0,0 +1,227 @@ +/** + * Edits `react-router.config.(js|ts)`: turns on SSR and adds the + * `sentryOnBuildEnd` hook that uploads source maps after a build. + */ + +import type { namedTypes as t } from "ast-types"; +import recast from "recast"; +import path from "node:path"; +import { existsSync, promises } from "node:fs"; + +import { parseModule, generateCode } from "magicast"; + +import { clack } from "../../utils/clack/prompts.js"; +import chalk from "chalk"; + +import { + findProperty, + preserveTrailingNewline, +} from "../../utils/ast-utils.js"; +import { getSentryReactRouterVitePluginImportPath } from "../sdk-version.js"; + +/** + * Extracts the ObjectExpression from various export patterns. + * Supports: direct object, `satisfies Config`, and `as Config` patterns. + */ +function extractConfigObject( + declaration: t.Declaration | t.Expression, +): t.ObjectExpression | undefined { + if (declaration.type === "ObjectExpression") { + return declaration as t.ObjectExpression; + } + + if ( + declaration.type === "TSSatisfiesExpression" || + declaration.type === "TSAsExpression" + ) { + const expr = (declaration as t.TSSatisfiesExpression | t.TSAsExpression) + .expression; + return expr.type === "ObjectExpression" ? expr : undefined; + } + + return undefined; +} + +/** + * Creates an identifier property for object literals. + */ +function createIdentifierProperty(name: string): t.Property { + const b = recast.types.builders; + return b.property("init", b.identifier(name), b.identifier(name)); +} + +export function addSentryBuildEndToReactRouterConfig(program: t.Program): { + success: boolean; + ssrWasChanged: boolean; +} { + const b = recast.types.builders; + let ssrWasChanged = false; + + const defaultExport = program.body.find( + (node): node is t.ExportDefaultDeclaration => + node.type === "ExportDefaultDeclaration", + ); + + if (!defaultExport) { + return { success: false, ssrWasChanged: false }; + } + + const configObj = extractConfigObject(defaultExport.declaration); + + if (!configObj) { + return { success: false, ssrWasChanged: false }; + } + + const buildEndProp = findProperty(configObj, "buildEnd"); + + if (buildEndProp) { + throw new Error( + "A buildEnd hook already exists in your React Router config.", + ); + } + + const ssrProp = findProperty(configObj, "ssr"); + + if (!ssrProp) { + const ssrProperty = b.objectProperty( + b.identifier("ssr"), + b.booleanLiteral(true), + ); + ssrProperty.comments = [ + b.commentLine( + " SSR is required for Sentry sourcemap uploads to work correctly", + true, + false, + ), + ]; + configObj.properties.unshift(ssrProperty); + ssrWasChanged = true; + } else if ( + ssrProp.value.type === "BooleanLiteral" || + ssrProp.value.type === "Literal" + ) { + const wasExplicitlyFalse = ssrProp.value.value === false; + + if (wasExplicitlyFalse) { + ssrWasChanged = true; + } + + ssrProp.value = b.booleanLiteral(true); + + if (wasExplicitlyFalse) { + ssrProp.comments = [ + b.commentLine( + " Changed to true - SSR is required for Sentry sourcemap uploads", + true, + false, + ), + ]; + } + } + + const paramNames = ["viteConfig", "reactRouterConfig", "buildManifest"]; + + const buildEndFunction = b.arrowFunctionExpression( + [b.objectPattern(paramNames.map(createIdentifierProperty))], + b.blockStatement([ + b.expressionStatement( + b.awaitExpression( + b.callExpression(b.identifier("sentryOnBuildEnd"), [ + b.objectExpression(paramNames.map(createIdentifierProperty)), + ]), + ), + ), + ]), + ); + buildEndFunction.async = true; + + configObj.properties.push( + b.objectProperty(b.identifier("buildEnd"), buildEndFunction), + ); + + return { success: true, ssrWasChanged }; +} + +export function hasReactRouterSentryContent(program: t.Program): boolean { + let hasSentry = false; + + recast.visit(program, { + visitIdentifier(path) { + if (path.node.name === "sentryOnBuildEnd") { + hasSentry = true; + return false; // stop traversal + } + this.traverse(path); + return undefined; + }, + }); + + return hasSentry; +} + +export async function instrumentReactRouterConfig( + isTS: boolean, + vitePluginImportPath: string = getSentryReactRouterVitePluginImportPath( + undefined, + ), +): Promise<{ ssrWasChanged: boolean }> { + const configFilename = `react-router.config.${isTS ? "ts" : "js"}`; + const configPath = path.join(process.cwd(), configFilename); + + if (!existsSync(configPath)) { + const defaultConfig = isTS + ? `import type { Config } from "@react-router/dev/config"; +import { sentryOnBuildEnd } from "${vitePluginImportPath}"; + +export default { + ssr: true, + buildEnd: async ({ viteConfig, reactRouterConfig, buildManifest }) => { + await sentryOnBuildEnd({ viteConfig, reactRouterConfig, buildManifest }); + }, +} satisfies Config; +` + : `import { sentryOnBuildEnd } from "${vitePluginImportPath}"; + +export default { + ssr: true, + buildEnd: async ({ viteConfig, reactRouterConfig, buildManifest }) => { + await sentryOnBuildEnd({ viteConfig, reactRouterConfig, buildManifest }); + }, +}; +`; + await promises.writeFile(configPath, defaultConfig); + return { ssrWasChanged: false }; + } + + const configContent = await promises.readFile(configPath, "utf-8"); + const filename = chalk.cyan(configFilename); + + const mod = parseModule(configContent); + + if (hasReactRouterSentryContent(mod.$ast as t.Program)) { + clack.log.info(`${filename} already contains sentryOnBuildEnd.`); + return { ssrWasChanged: false }; + } + + mod.imports.$add({ + from: vitePluginImportPath, + imported: "sentryOnBuildEnd", + local: "sentryOnBuildEnd", + }); + + const { success, ssrWasChanged } = addSentryBuildEndToReactRouterConfig( + mod.$ast as t.Program, + ); + + if (!success) { + throw new Error("Failed to modify React Router config structure"); + } + + const code = preserveTrailingNewline( + configContent, + generateCode(mod.$ast).code, + ); + await promises.writeFile(configPath, code); + + return { ssrWasChanged }; +} diff --git a/packages/cli/src/lib/wizard/react-router/codemods/routes-config.ts b/packages/cli/src/lib/wizard/react-router/codemods/routes-config.ts new file mode 100644 index 0000000000..316ed0e95c --- /dev/null +++ b/packages/cli/src/lib/wizard/react-router/codemods/routes-config.ts @@ -0,0 +1,107 @@ +/** + * Adds the example page and API routes to a React Router `routes.ts`. + */ + +import recast from "recast"; +import { existsSync } from "node:fs"; +import type { namedTypes as t } from "ast-types"; + +import { loadFile, writeFile } from "magicast"; + +export async function addRoutesToConfig( + routesConfigPath: string, + isTS: boolean, +): Promise { + // Check if file exists first + if (!existsSync(routesConfigPath)) { + return; + } + + const routesAst = await loadFile(routesConfigPath); + + // Check if routes are already added + const routesCode = routesAst.$code; + if ( + routesCode.includes("sentry-example-page") && + routesCode.includes("sentry-example-api") + ) { + return; + } + + // Add route import if not already present + const hasRouteImport = routesAst.imports.$items.some( + (item) => + item.imported === "route" && item.from === "@react-router/dev/routes", + ); + + if (!hasRouteImport) { + routesAst.imports.$add({ + from: "@react-router/dev/routes", + imported: "route", + local: "route", + }); + } + + // Set up the new routes + const routeExtension = isTS ? "tsx" : "jsx"; + const apiExtension = isTS ? "ts" : "js"; + + const pageRouteCode = `route("/sentry-example-page", "routes/sentry-example-page.${routeExtension}")`; + const apiRouteCode = `route("/api/sentry-example-api", "routes/api.sentry-example-api.${apiExtension}")`; + + let foundDefaultExport = false; + + // Get the AST program + const program = routesAst.$ast as t.Program; + + // Find the default export + for (let i = 0; i < program.body.length; i++) { + const node = program.body[i]; + if (!node) { + continue; + } + + if (node.type === "ExportDefaultDeclaration") { + foundDefaultExport = true; + + const declaration = node.declaration; + + let arrayExpression = null; + + if (declaration.type === "ArrayExpression") { + arrayExpression = declaration; + } else if (declaration.type === "TSSatisfiesExpression") { + // Handle TypeScript satisfies expression like: [...] satisfies RouteConfig + if (declaration.expression.type === "ArrayExpression") { + arrayExpression = declaration.expression; + } + } + + if (arrayExpression) { + // Parse and add the new route calls directly to the elements array + const pageRouteCall = + recast.parse(pageRouteCode).program.body[0].expression; + const apiRouteCall = + recast.parse(apiRouteCode).program.body[0].expression; + + arrayExpression.elements.push(pageRouteCall); + arrayExpression.elements.push(apiRouteCall); + } + break; + } + } + + // If no default export found, add one + if (!foundDefaultExport) { + // Create a simple array export without satisfies for now + const newExportCode = `export default [ + ${pageRouteCode}, + ${apiRouteCode}, +];`; + + const newExport = recast.parse(newExportCode).program.body[0]; + program.body.push(newExport); + } + + await writeFile(routesAst.$ast, routesConfigPath); +} diff --git a/packages/cli/src/lib/wizard/react-router/codemods/server-entry.ts b/packages/cli/src/lib/wizard/react-router/codemods/server-entry.ts new file mode 100644 index 0000000000..453cf9aa9a --- /dev/null +++ b/packages/cli/src/lib/wizard/react-router/codemods/server-entry.ts @@ -0,0 +1,437 @@ +/** + * Instruments a React Router `entry.server` file: wraps `handleRequest`, + * captures errors in `handleError`, and exports the instrumentation API hooks. + */ + +import type { ProxifiedModule } from "magicast"; + +import recast from "recast"; +import type { namedTypes as t } from "ast-types"; + +import { clack } from "../../utils/clack/prompts.js"; +import chalk from "chalk"; + +import { generateCode, loadFile, writeFile } from "magicast"; +import { debug } from "../../utils/debug.js"; +import { + hasSentryContent, + safeCalleeIdentifierMatch, + safeGetIdentifierName, +} from "../../utils/ast-utils.js"; +import { getAfterImportsInsertionIndex } from "./utils.js"; + +export async function instrumentServerEntry( + serverEntryPath: string, + useInstrumentationAPI = false, +): Promise { + const serverEntryAst = await loadFile(serverEntryPath); + + if (!hasSentryContent(serverEntryAst.$ast as t.Program)) { + serverEntryAst.imports.$add({ + from: "@sentry/react-router", + imported: "*", + local: "Sentry", + }); + } + + instrumentHandleError(serverEntryAst); + instrumentHandleRequest(serverEntryAst); + + if (useInstrumentationAPI) { + instrumentInstrumentations(serverEntryAst); + } + + await writeFile(serverEntryAst.$ast, serverEntryPath); +} + +function instrumentInstrumentations( + originalEntryServerMod: ProxifiedModule, +): void { + const originalEntryServerModAST = originalEntryServerMod.$ast as t.Program; + + const hasInstrumentations = originalEntryServerModAST.body.some((node) => { + if ( + node.type !== "ExportNamedDeclaration" || + node.declaration?.type !== "VariableDeclaration" + ) { + return false; + } + + const declarations = node.declaration.declarations; + if (declarations.length === 0) { + return false; + } + + const firstDeclaration = declarations[0]; + if (firstDeclaration?.type !== "VariableDeclarator") { + return false; + } + + const id = firstDeclaration.id; + return ( + id.type === "Identifier" && + (id.name === "instrumentations" || + id.name === "unstable_instrumentations") + ); + }); + + if (hasInstrumentations) { + debug("instrumentations export already exists, skipping adding it again"); + return; + } + + const instrumentationsExport = recast.parse( + `export const instrumentations = [Sentry.createSentryServerInstrumentation()];`, + ).program.body[0]; + + originalEntryServerModAST.body.push(instrumentationsExport); +} + +export function instrumentHandleRequest( + originalEntryServerMod: ProxifiedModule, +): void { + const originalEntryServerModAST = originalEntryServerMod.$ast as t.Program; + + const defaultServerEntryExport = originalEntryServerModAST.body.find( + (node) => { + return node.type === "ExportDefaultDeclaration"; + }, + ); + + if (!defaultServerEntryExport) { + clack.log.warn( + `Could not find function ${chalk.cyan( + "handleRequest", + )} in your server entry file. Creating one for you.`, + ); + + let foundServerRouterImport = false as boolean; + let foundRenderToPipeableStreamImport = false as boolean; + let foundCreateReadableStreamFromReadableImport = false as boolean; + + originalEntryServerMod.imports.$items.forEach((item) => { + if (item.imported === "ServerRouter" && item.from === "react-router") { + foundServerRouterImport = true; + } + if ( + item.imported === "renderToPipeableStream" && + item.from === "react-dom/server" + ) { + foundRenderToPipeableStreamImport = true; + } + if ( + item.imported === "createReadableStreamFromReadable" && + item.from === "@react-router/node" + ) { + foundCreateReadableStreamFromReadableImport = true; + } + }); + + if (!foundServerRouterImport) { + originalEntryServerMod.imports.$add({ + from: "react-router", + imported: "ServerRouter", + local: "ServerRouter", + }); + } + + if (!foundRenderToPipeableStreamImport) { + originalEntryServerMod.imports.$add({ + from: "react-dom/server", + imported: "renderToPipeableStream", + local: "renderToPipeableStream", + }); + } + + if (!foundCreateReadableStreamFromReadableImport) { + originalEntryServerMod.imports.$add({ + from: "@react-router/node", + imported: "createReadableStreamFromReadable", + local: "createReadableStreamFromReadable", + }); + } + + const implementation = + recast.parse(`const handleRequest = Sentry.createSentryHandleRequest({ + ServerRouter, + renderToPipeableStream, + createReadableStreamFromReadable, +})`).program.body[0]; + + try { + originalEntryServerModAST.body.splice( + getAfterImportsInsertionIndex(originalEntryServerModAST), + 0, + implementation, + ); + + originalEntryServerModAST.body.push({ + type: "ExportDefaultDeclaration", + declaration: { + type: "Identifier", + name: "handleRequest", + }, + }); + } catch (error) { + debug("Failed to insert handleRequest implementation:", error); + throw new Error( + "Could not automatically instrument handleRequest. Please add it manually.", + ); + } + } else if ( + // @ts-expect-error - StatementKind works here because the AST is proxified by magicast + generateCode(defaultServerEntryExport).code.includes( + "wrapSentryHandleRequest", + ) + ) { + debug("wrapSentryHandleRequest is already used, skipping wrapping again"); + clack.log.info( + "Sentry handleRequest wrapper already detected, skipping instrumentation.", + ); + } else { + let defaultExportNode = null as t.ExportDefaultDeclaration | null; + const defaultExportIndex = originalEntryServerModAST.body.findIndex( + (node) => { + const found = node.type === "ExportDefaultDeclaration"; + + if (found) { + defaultExportNode = node; + } + + return found; + }, + ); + + if (defaultExportIndex !== -1 && defaultExportNode !== null) { + recast.visit(defaultExportNode, { + visitCallExpression(path) { + if ( + safeCalleeIdentifierMatch(path.value.callee, "pipe") && + path.value.arguments.length && + path.value.arguments[0].type === "Identifier" && + safeGetIdentifierName(path.value.arguments[0]) === "body" + ) { + const wrapped = recast.types.builders.callExpression( + recast.types.builders.memberExpression( + recast.types.builders.identifier("Sentry"), + recast.types.builders.identifier("getMetaTagTransformer"), + ), + [path.value.arguments[0]], + ); + + path.value.arguments[0] = wrapped; + } + + this.traverse(path); + }, + }); + + // Replace the existing default export with the unwrapped function declaration + const funcDeclaration = defaultExportNode.declaration; + // Make non-async functions async so the return type matches wrapSentryHandleRequest + if ( + funcDeclaration.type === "FunctionDeclaration" && + !funcDeclaration.async + ) { + funcDeclaration.async = true; + } + originalEntryServerModAST.body.splice( + defaultExportIndex, + 1, + // @ts-expect-error - an expression works here because the AST is proxified by magicast + funcDeclaration, + ); + + // Adding our wrapped export + originalEntryServerModAST.body.push( + recast.types.builders.exportDefaultDeclaration( + recast.types.builders.callExpression( + recast.types.builders.memberExpression( + recast.types.builders.identifier("Sentry"), + recast.types.builders.identifier("wrapSentryHandleRequest"), + ), + [recast.types.builders.identifier("handleRequest")], + ), + ), + ); + } + } +} + +export function instrumentHandleError( + originalEntryServerMod: ProxifiedModule, +): void { + const originalEntryServerModAST = originalEntryServerMod.$ast as t.Program; + + const handleErrorFunctionExport = originalEntryServerModAST.body.find( + (node) => { + return ( + node.type === "ExportNamedDeclaration" && + node.declaration?.type === "FunctionDeclaration" && + node.declaration.id?.name === "handleError" + ); + }, + ); + + const handleErrorFunctionVariableDeclarationExport = + originalEntryServerModAST.body.find((node) => { + if ( + node.type !== "ExportNamedDeclaration" || + node.declaration?.type !== "VariableDeclaration" + ) { + return false; + } + + const declarations = node.declaration.declarations; + if (declarations.length === 0) { + return false; + } + + const firstDeclaration = declarations[0]; + if (firstDeclaration?.type !== "VariableDeclarator") { + return false; + } + + const id = firstDeclaration.id; + return id.type === "Identifier" && id.name === "handleError"; + }); + + if ( + !handleErrorFunctionExport && + !handleErrorFunctionVariableDeclarationExport + ) { + clack.log.warn( + `Could not find function ${chalk.cyan( + "handleError", + )} in your server entry file. Creating one for you.`, + ); + + const implementation = + recast.parse(`const handleError = Sentry.createSentryHandleError({ + logErrors: false +})`).program.body[0]; + + originalEntryServerModAST.body.splice( + getAfterImportsInsertionIndex(originalEntryServerModAST), + 0, + recast.types.builders.exportNamedDeclaration(implementation), + ); + } else if ( + (handleErrorFunctionExport && + // @ts-expect-error - StatementKind works here because the AST is proxified by magicast + generateCode(handleErrorFunctionExport).code.includes( + "captureException", + )) || + (handleErrorFunctionVariableDeclarationExport && + // @ts-expect-error - StatementKind works here because the AST is proxified by magicast + generateCode(handleErrorFunctionVariableDeclarationExport).code.includes( + "captureException", + )) + ) { + debug( + "Found captureException inside handleError, skipping adding it again", + ); + } else if ( + (handleErrorFunctionExport && + // @ts-expect-error - StatementKind works here because the AST is proxified by magicast + generateCode(handleErrorFunctionExport).code.includes( + "createSentryHandleError", + )) || + (handleErrorFunctionVariableDeclarationExport && + // @ts-expect-error - StatementKind works here because the AST is proxified by magicast + generateCode(handleErrorFunctionVariableDeclarationExport).code.includes( + "createSentryHandleError", + )) + ) { + debug("createSentryHandleError is already used, skipping adding it again"); + } else if (handleErrorFunctionExport) { + // Create the Sentry captureException call as an IfStatement + const sentryCall = recast.parse(`if (!request.signal.aborted) { + Sentry.captureException(error); +}`).program.body[0]; + + // Safely insert the Sentry call at the beginning of the handleError function body + // @ts-expect-error - declaration works here because the AST is proxified by magicast + const declaration = handleErrorFunctionExport.declaration; + if (declaration?.body?.body && Array.isArray(declaration.body.body)) { + declaration.body.body.unshift(sentryCall); + } else { + debug( + "Cannot safely access handleError function body, skipping instrumentation", + ); + } + } else if (handleErrorFunctionVariableDeclarationExport) { + // Create the Sentry captureException call as an IfStatement + const sentryCall = recast.parse(`if (!request.signal.aborted) { + Sentry.captureException(error); +}`).program.body[0]; + + // Safe access to existing handle error implementation with proper null checks + // We know this is ExportNamedDeclaration with VariableDeclaration from the earlier find + const exportDeclaration = handleErrorFunctionVariableDeclarationExport; + if ( + exportDeclaration.type !== "ExportNamedDeclaration" || + exportDeclaration.declaration?.type !== "VariableDeclaration" || + exportDeclaration.declaration.declarations.length === 0 + ) { + debug( + "Cannot safely access handleError variable declaration, skipping instrumentation", + ); + return; + } + + const firstDeclaration = exportDeclaration.declaration.declarations[0]; + const existingHandleErrorImplementation = + firstDeclaration?.type === "VariableDeclarator" + ? firstDeclaration.init + : undefined; + if ( + (existingHandleErrorImplementation?.type !== "ArrowFunctionExpression" && + existingHandleErrorImplementation?.type !== "FunctionExpression") || + existingHandleErrorImplementation.body.type !== "BlockStatement" + ) { + debug( + "Cannot safely access handleError variable declarator init, skipping instrumentation", + ); + return; + } + + const existingParams = existingHandleErrorImplementation.params; + const existingBody = existingHandleErrorImplementation.body; + + const requestParam = { + ...recast.types.builders.property( + "init", + recast.types.builders.identifier("request"), // key + recast.types.builders.identifier("request"), // value + ), + shorthand: true, + }; + // Add error and {request} parameters to handleError function if not present + // When none of the parameters exist + if (existingParams.length === 0) { + existingParams.push( + recast.types.builders.identifier("error"), + recast.types.builders.objectPattern([requestParam]), + ); + // When only error parameter exists + } else if (existingParams.length === 1) { + existingParams.push(recast.types.builders.objectPattern([requestParam])); + // When both parameters exist, but request is not destructured + } else { + const secondParam = existingParams[1]; + if ( + secondParam?.type === "ObjectPattern" && + !secondParam.properties.some( + (prop) => + "key" in prop && safeGetIdentifierName(prop.key) === "request", + ) + ) { + secondParam.properties.push(requestParam); + } + } + + // Add the Sentry call to the function body + existingBody.body.push(sentryCall); + } +} diff --git a/packages/cli/src/lib/wizard/react-router/codemods/utils.ts b/packages/cli/src/lib/wizard/react-router/codemods/utils.ts new file mode 100644 index 0000000000..24a6468302 --- /dev/null +++ b/packages/cli/src/lib/wizard/react-router/codemods/utils.ts @@ -0,0 +1,17 @@ +/** + * AST helpers shared by the React Router codemods. + */ + +import type { namedTypes as t } from "ast-types"; + +export function getAfterImportsInsertionIndex( + originalEntryServerModAST: t.Program, +): number { + for (let x = originalEntryServerModAST.body.length - 1; x >= 0; x--) { + if (originalEntryServerModAST.body[x]?.type === "ImportDeclaration") { + return x + 1; + } + } + + return 0; +} diff --git a/packages/cli/src/lib/wizard/react-router/codemods/vite.ts b/packages/cli/src/lib/wizard/react-router/codemods/vite.ts new file mode 100644 index 0000000000..e2e39a1002 --- /dev/null +++ b/packages/cli/src/lib/wizard/react-router/codemods/vite.ts @@ -0,0 +1,270 @@ +/** + * Adds the Sentry React Router Vite plugin to `vite.config.(js|ts)`. + */ + +import type { namedTypes as t } from "ast-types"; +import recast from "recast"; +import path from "node:path"; +import { existsSync, promises } from "node:fs"; + +import { parseModule, generateCode } from "magicast"; + +import { clack } from "../../utils/clack/prompts.js"; +import chalk from "chalk"; + +import { + hasSentryContent, + findProperty, + preserveTrailingNewline, +} from "../../utils/ast-utils.js"; +import { debug } from "../../utils/debug.js"; +import { getSentryReactRouterVitePluginImportPath } from "../sdk-version.js"; + +/** + * Extracts ObjectExpression from function body. + * Handles both arrow functions with object returns and block statements with explicit returns. + * + * - Arrow with object-return: (config) => ({ ... }) + * - Arrow with block: (config) => { return { ... }; } + * - Function with block: function(config) { return { ... }; } + * + * @param body - The function body to extract from + * @returns The ObjectExpression if found, undefined otherwise + */ +function extractFromFunctionBody( + body: t.Expression | t.BlockStatement, +): t.ObjectExpression | undefined { + if (body.type === "ObjectExpression") { + return body as t.ObjectExpression; + } + + if (body.type === "BlockStatement") { + const blockBody = body as t.BlockStatement; + const returnStatement = blockBody.body.find( + (stmt: t.Statement): stmt is t.ReturnStatement => + stmt.type === "ReturnStatement", + ); + + return returnStatement?.argument?.type === "ObjectExpression" + ? returnStatement.argument + : undefined; + } + + return undefined; +} + +/** + * Creates the sentryReactRouter Vite plugin call expression. + * + * Generates AST for: + * sentryReactRouter({ + * org: "...", + * project: "...", + * authToken: process.env.SENTRY_AUTH_TOKEN + * }, config) + * + * @param orgSlug - Sentry organization slug + * @param projectSlug - Sentry project slug + * @returns CallExpression node for the Sentry Vite plugin + */ +function createSentryPluginCall( + orgSlug: string, + projectSlug: string, +): t.CallExpression { + const b = recast.types.builders; + return b.callExpression(b.identifier("sentryReactRouter"), [ + b.objectExpression([ + b.objectProperty(b.identifier("org"), b.stringLiteral(orgSlug)), + b.objectProperty(b.identifier("project"), b.stringLiteral(projectSlug)), + b.objectProperty( + b.identifier("authToken"), + b.memberExpression( + b.memberExpression(b.identifier("process"), b.identifier("env")), + b.identifier("SENTRY_AUTH_TOKEN"), + ), + ), + ]), + b.identifier("config"), + ]); +} + +/** Adds @sentry/react-router to optimizeDeps.exclude to prevent 504 errors during dev. */ +function addOptimizeDepsExclude(configObj: t.ObjectExpression): void { + const b = recast.types.builders; + + const optimizeDeps = findProperty(configObj, "optimizeDeps"); + const optimizeDepsObj = + optimizeDeps?.type === "ObjectProperty" && + optimizeDeps.value.type === "ObjectExpression" + ? optimizeDeps.value + : null; + + let targetDepsObj: t.ObjectExpression; + if (!optimizeDepsObj) { + if (optimizeDeps) { + debug("optimizeDeps is not a static object, skipping exclude"); + return; + } + targetDepsObj = b.objectExpression([]); + configObj.properties.push( + b.objectProperty(b.identifier("optimizeDeps"), targetDepsObj), + ); + } else { + targetDepsObj = optimizeDepsObj; + } + + const excludeProp = findProperty(targetDepsObj, "exclude"); + const excludeArr = + excludeProp?.type === "ObjectProperty" && + excludeProp.value.type === "ArrayExpression" + ? excludeProp.value + : null; + + let targetArr: t.ArrayExpression; + if (!excludeArr) { + if (excludeProp) { + debug("optimizeDeps.exclude is not a static array, skipping"); + return; + } + targetArr = b.arrayExpression([]); + targetDepsObj.properties.push( + b.objectProperty(b.identifier("exclude"), targetArr), + ); + } else { + targetArr = excludeArr; + } + + const isAlreadyExcluded = targetArr.elements.some( + (el) => el?.type === "StringLiteral" && el.value === "@sentry/react-router", + ); + if (!isAlreadyExcluded) { + targetArr.elements.push(b.stringLiteral("@sentry/react-router")); + } +} + +export function addReactRouterPluginToViteConfig( + program: t.Program, + orgSlug: string, + projectSlug: string, +): { success: boolean; wasConverted: boolean } { + const b = recast.types.builders; + let wasConverted = false; + + const defaultExport = program.body.find( + (node): node is t.ExportDefaultDeclaration => + node.type === "ExportDefaultDeclaration", + ); + + if (!defaultExport) { + return { success: false, wasConverted: false }; + } + + let configObj: t.ObjectExpression | undefined; + let defineConfigCall: t.CallExpression | undefined; + + if ( + defaultExport.declaration.type === "CallExpression" && + defaultExport.declaration.callee.type === "Identifier" && + defaultExport.declaration.callee.name === "defineConfig" + ) { + defineConfigCall = defaultExport.declaration; + + const arg = defineConfigCall.arguments[0]; + + // Early exit if not single argument + if (defineConfigCall.arguments.length !== 1 || !arg) { + return { success: false, wasConverted: false }; + } + + if (arg.type === "ObjectExpression") { + configObj = arg; + // Convert to function form + const arrowFunction = b.arrowFunctionExpression( + [b.identifier("config")], + configObj, + ); + defineConfigCall.arguments[0] = arrowFunction; + wasConverted = true; + } else if ( + arg.type === "ArrowFunctionExpression" || + arg.type === "FunctionExpression" + ) { + configObj = extractFromFunctionBody(arg.body); + } + } + + if (!configObj) { + return { success: false, wasConverted }; + } + + const pluginsProp = findProperty(configObj, "plugins"); + const sentryPluginCall = createSentryPluginCall(orgSlug, projectSlug); + + if (!pluginsProp) { + configObj.properties.push( + b.objectProperty( + b.identifier("plugins"), + b.arrayExpression([sentryPluginCall]), + ), + ); + } else if (pluginsProp.value.type === "ArrayExpression") { + pluginsProp.value.elements.push(sentryPluginCall); + } else { + return { success: false, wasConverted }; + } + + // Prevent 504 "Outdated Optimize Dep" errors in dev (https://github.com/vitejs/vite/issues/13506) + addOptimizeDepsExclude(configObj); + + return { success: true, wasConverted }; +} + +export async function instrumentViteConfig( + orgSlug: string, + projectSlug: string, + vitePluginImportPath: string = getSentryReactRouterVitePluginImportPath( + undefined, + ), +): Promise<{ wasConverted: boolean }> { + const configPath = existsSync(path.join(process.cwd(), "vite.config.ts")) + ? path.join(process.cwd(), "vite.config.ts") + : path.join(process.cwd(), "vite.config.js"); + + if (!existsSync(configPath)) { + throw new Error("Could not find vite.config.ts or vite.config.js"); + } + + const configContent = await promises.readFile(configPath, "utf-8"); + const filename = chalk.cyan(path.basename(configPath)); + + const mod = parseModule(configContent); + + if (hasSentryContent(mod.$ast as t.Program)) { + clack.log.info(`${filename} already contains sentryReactRouter plugin.`); + return { wasConverted: false }; + } + + mod.imports.$add({ + from: vitePluginImportPath, + imported: "sentryReactRouter", + local: "sentryReactRouter", + }); + + const { success, wasConverted } = addReactRouterPluginToViteConfig( + mod.$ast as t.Program, + orgSlug, + projectSlug, + ); + + if (!success) { + throw new Error("Failed to modify Vite config structure"); + } + + const code = preserveTrailingNewline( + configContent, + generateCode(mod.$ast).code, + ); + await promises.writeFile(configPath, code); + + return { wasConverted }; +} diff --git a/packages/cli/src/lib/wizard/react-router/react-router-wizard.ts b/packages/cli/src/lib/wizard/react-router/react-router-wizard.ts new file mode 100644 index 0000000000..20854aecef --- /dev/null +++ b/packages/cli/src/lib/wizard/react-router/react-router-wizard.ts @@ -0,0 +1,504 @@ +/** + * The React Router (framework mode) setup wizard: installs + * `@sentry/react-router`, instruments the client and server entries, the + * Vite and React Router configs, and optionally adds an example page. + */ + +import { clack } from "../utils/clack/prompts.js"; +import chalk from "chalk"; +import { Sentry } from "../telemetry.js"; + +import type { WizardOptions } from "../utils/types.js"; +import { withTelemetry, traceStep } from "../telemetry.js"; +import { + askShouldCreateExamplePage, + confirmContinueIfNoOrDirtyGitRepo, + featureSelectionPrompt, + getOrAskForProjectData, + getPackageDotJson, + isUsingTypeScript, + printWelcome, + installPackage, + printSdkV11MigrationGuideIfOutdated, + addDotEnvSentryBuildPluginFile, + showCopyPasteInstructions, + makeCodeSnippet, + runPrettierIfInstalled, +} from "../utils/clack/index.js"; +import { offerProjectScopedMcpConfig } from "../utils/clack/mcp-config.js"; +import { + getPackageVersion, + hasPackageInstalled, +} from "../utils/package-json.js"; +import { + MIN_REACT_ROUTER_VERSION_FOR_SDK_V11, + SENTRY_REACT_ROUTER_SDK_RANGE, + getSentryReactRouterVitePluginImportPath, +} from "./sdk-version.js"; +import { debug } from "../utils/debug.js"; +import { createExamplePage } from "./sdk-example.js"; +import { + isReactRouterV7, + getReactRouterVersion, + supportsInstrumentationAPI, + supportsOnError, + runReactRouterReveal, + initializeSentryOnEntryClient, + createServerInstrumentationFile, + updatePackageJsonScripts, + instrumentSentryOnEntryServer, + configureReactRouterConfig, + configureReactRouterVitePlugin, +} from "./sdk-setup.js"; +import { + getManualClientEntryContent, + getManualServerEntryContent, + getManualServerInstrumentContent, + getManualReactRouterConfigContent, + getManualViteConfigContent, +} from "./templates.js"; +import { abortIfSpotlightNotSupported } from "../utils/abort-if-sportlight-not-supported.js"; +import { + askShouldReduceDataCollection, + sdkSupportsDataCollection, +} from "../utils/data-collection.js"; +import { warnIfNodeVersionUnsupportedBySdkV11 } from "../utils/node-version.js"; + +export async function runReactRouterWizard( + options: WizardOptions, +): Promise { + return await withTelemetry( + { + enabled: options.telemetryEnabled, + integration: "reactRouter", + wizardOptions: options, + }, + () => runReactRouterWizardWithTelemetry(options), + ); +} + +async function runReactRouterWizardWithTelemetry( + options: WizardOptions, +): Promise { + printWelcome({ + wizardName: "Sentry React Router Wizard", + promoCode: options.promoCode, + }); + + const packageJson = await getPackageDotJson(); + + const typeScriptDetected = isUsingTypeScript(); + + if (!isReactRouterV7(packageJson)) { + clack.log.error( + "This wizard requires React Router v7. Please upgrade your React Router version to v7.0.0 or higher.\n\nFor upgrade instructions, visit: https://react-router.dev/upgrade/v7", + ); + return; + } + + warnIfNodeVersionUnsupportedBySdkV11(); + + await confirmContinueIfNoOrDirtyGitRepo({ + ignoreGitChanges: options.ignoreGitChanges, + cwd: undefined, + }); + + const sentryAlreadyInstalled = hasPackageInstalled( + "@sentry/react-router", + packageJson, + ); + + const projectData = await getOrAskForProjectData( + options, + "javascript-react-router", + ); + + if (projectData.spotlight) { + return await abortIfSpotlightNotSupported("React Router"); + } + + const { selectedProject, authToken, selfHosted, sentryUrl } = projectData; + + printSdkV11MigrationGuideIfOutdated("@sentry/react-router", packageJson); + + await installPackage({ + packageName: `@sentry/react-router@${SENTRY_REACT_ROUTER_SDK_RANGE}`, + packageNameDisplayLabel: "@sentry/react-router", + alreadyInstalled: sentryAlreadyInstalled, + }); + + // The install may have been skipped (user declined the update prompt), so + // re-read package.json to learn which SDK major is actually installed. + const installedSdkVersion = getPackageVersion( + "@sentry/react-router", + await getPackageDotJson(), + ); + const vitePluginImportPath = + getSentryReactRouterVitePluginImportPath(installedSdkVersion); + + // 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, + SENTRY_REACT_ROUTER_SDK_RANGE, + ) && (await askShouldReduceDataCollection()); + + if (!supportsInstrumentationAPI(packageJson)) { + clack.log.warn( + `${chalk.yellow( + `Version 11 of the Sentry React Router SDK requires React Router ${MIN_REACT_ROUTER_VERSION_FOR_SDK_V11} or newer, but this project uses ${chalk.bold( + `react-router@${getReactRouterVersion(packageJson) ?? "unknown"}`, + )}.`, + )} +The wizard will continue, but you may need to upgrade React Router before moving to SDK v11.`, + ); + } + + const featureSelection = 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", + }, + { + id: "profiling", + prompt: `Do you want to enable ${chalk.bold( + "Profiling", + )} to track application performance in detail?`, + enabledHint: "recommended for production debugging", + }, + ] as const); + + // Only ask about Instrumentation API when Tracing is enabled, since it depends on it + let instrumentationAPISelected = false; + if (featureSelection.performance) { + const instrumentationAPISelection = await featureSelectionPrompt([ + { + id: "instrumentationAPI", + prompt: `Do you want to use the ${chalk.bold( + "Instrumentation API", + )} for automatic tracing of loaders, actions, and middleware?`, + enabledHint: "recommended", + }, + ] as const); + instrumentationAPISelected = instrumentationAPISelection.instrumentationAPI; + } + + if (featureSelection.profiling) { + const profilingAlreadyInstalled = hasPackageInstalled( + "@sentry/profiling-node", + packageJson, + ); + + await installPackage({ + packageName: `@sentry/profiling-node@${SENTRY_REACT_ROUTER_SDK_RANGE}`, + packageNameDisplayLabel: "@sentry/profiling-node", + alreadyInstalled: profilingAlreadyInstalled, + }); + } + + const createExamplePageSelection = await askShouldCreateExamplePage(); + + traceStep("Reveal missing entry files", () => { + try { + runReactRouterReveal(); + clack.log.success("Entry files are ready for instrumentation"); + } catch (e) { + clack.log.warn(`Could not run 'npx react-router reveal'. +Please create your entry files manually using React Router v7 commands.`); + debug(e); + } + }); + + Sentry.setTag("instrumentation-api-selected", instrumentationAPISelected); + + let useInstrumentationAPI = instrumentationAPISelected; + + if (useInstrumentationAPI && !supportsInstrumentationAPI(packageJson)) { + Sentry.setTag("instrumentation-api-version-guard", true); + const detectedVersion = getReactRouterVersion(packageJson) ?? "unknown"; + clack.log.warn( + `The Instrumentation API requires React Router ${chalk.cyan( + ">=7.15.0", + )} (detected ${chalk.cyan( + detectedVersion, + )}). Your version does not meet this requirement.\n` + + `Continuing without the Instrumentation API. Please upgrade React Router to use this feature:\n` + + chalk.dim( + "https://docs.sentry.io/platforms/javascript/guides/react-router/", + ), + ); + useInstrumentationAPI = false; + } + + Sentry.setTag("use-instrumentation-api", useInstrumentationAPI); + + let useOnError = true; + + if (!supportsOnError(packageJson)) { + Sentry.setTag("on-error-version-guard", true); + const detectedVersion = getReactRouterVersion(packageJson) ?? "unknown"; + clack.log.warn( + `The ${chalk.cyan( + "onError", + )} prop on HydratedRouter requires React Router ${chalk.cyan( + ">=7.11.0", + )} (detected ${chalk.cyan(detectedVersion)}).\n` + + `Skipping automatic error handler setup. Please upgrade React Router and follow the manual setup guide:\n` + + chalk.dim( + "https://docs.sentry.io/platforms/javascript/guides/react-router/", + ), + ); + useOnError = false; + } + + Sentry.setTag("use-on-error", useOnError); + + await traceStep("Initialize Sentry on client entry", async () => { + try { + await initializeSentryOnEntryClient( + selectedProject.keys[0].dsn.public, + featureSelection.performance, + featureSelection.replay, + typeScriptDetected, + reduceDataCollection, + useInstrumentationAPI, + useOnError, + ); + } catch (e) { + clack.log.warn( + `Could not initialize Sentry on client entry automatically.`, + ); + + const clientEntryFilename = `entry.client.${ + typeScriptDetected ? "tsx" : "jsx" + }`; + + const manualClientContent = getManualClientEntryContent( + selectedProject.keys[0].dsn.public, + featureSelection.performance, + featureSelection.replay, + reduceDataCollection, + useInstrumentationAPI, + useOnError, + ); + + await showCopyPasteInstructions({ + filename: clientEntryFilename, + codeSnippet: manualClientContent, + hint: "This enables error tracking and performance monitoring for your React Router app", + }); + + debug(e); + } + }); + + await traceStep("Instrument server entry", async () => { + try { + await instrumentSentryOnEntryServer( + typeScriptDetected, + useInstrumentationAPI, + ); + } catch (e) { + clack.log.warn( + `Could not initialize Sentry on server entry automatically.`, + ); + + const serverEntryFilename = `entry.server.${ + typeScriptDetected ? "tsx" : "jsx" + }`; + const manualServerContent = getManualServerEntryContent( + useInstrumentationAPI, + ); + + await showCopyPasteInstructions({ + filename: serverEntryFilename, + codeSnippet: manualServerContent, + hint: "This configures server-side request handling and error tracking", + }); + + debug(e); + } + }); + + await traceStep("Create server instrumentation file", async () => { + try { + createServerInstrumentationFile( + selectedProject.keys[0].dsn.public, + { + performance: featureSelection.performance, + replay: featureSelection.replay, + profiling: featureSelection.profiling, + }, + reduceDataCollection, + ); + } catch (e) { + clack.log.warn( + "Could not create a server instrumentation file automatically.", + ); + + const manualServerInstrumentContent = getManualServerInstrumentContent( + selectedProject.keys[0].dsn.public, + featureSelection.performance, + featureSelection.profiling, + reduceDataCollection, + ); + + await showCopyPasteInstructions({ + filename: "instrument.server.mjs", + codeSnippet: manualServerInstrumentContent, + hint: "Create the file if it does not exist - this initializes Sentry before your application starts", + }); + + debug(e); + } + }); + + await traceStep("Update package.json scripts", async () => { + try { + await updatePackageJsonScripts(); + } catch (e) { + clack.log.warn("Could not update start script automatically."); + + await showCopyPasteInstructions({ + filename: "package.json", + codeSnippet: makeCodeSnippet(true, (unchanged, plus, minus) => { + return unchanged(`{ + scripts: { + ${minus('"start": "react-router dev"')} + ${plus( + '"start": "NODE_ENV=production NODE_OPTIONS=\'--import ./instrument.server.mjs\' react-router-serve ./build/server/index.js"', + )} + ${minus('"dev": "react-router dev"')} + ${plus( + '"dev": "NODE_OPTIONS=\'--import ./instrument.server.mjs\' react-router dev"', + )} + }, + // ... rest of your package.json + }`); + }), + }); + + debug(e); + } + }); + + await traceStep("Create build plugin env file", async () => { + try { + await addDotEnvSentryBuildPluginFile(authToken); + } catch (e) { + clack.log.warn( + "Could not create .env.sentry-build-plugin file. Please create it manually.", + ); + debug(e); + } + }); + + // Validate auth token before configuring sourcemap uploads + if (!authToken) { + clack.log.warn( + `${chalk.yellow( + "Warning:", + )} No auth token found. Sourcemap uploads will not work without ${chalk.cyan( + "SENTRY_AUTH_TOKEN", + )}.\n` + + `Please set ${chalk.cyan("SENTRY_AUTH_TOKEN")} in your ${chalk.cyan( + ".env.sentry-build-plugin", + )} file or environment variables.`, + ); + } + + // Configure Vite plugin for sourcemap uploads + await traceStep("Configure Vite plugin for sourcemap uploads", async () => { + try { + await configureReactRouterVitePlugin( + selectedProject.organization.slug, + selectedProject.slug, + vitePluginImportPath, + ); + } catch (e) { + clack.log.warn( + `Could not configure Vite plugin for sourcemap uploads automatically.`, + ); + + await showCopyPasteInstructions({ + filename: `vite.config.${typeScriptDetected ? "ts" : "js"}`, + codeSnippet: getManualViteConfigContent( + selectedProject.organization.slug, + selectedProject.slug, + vitePluginImportPath, + ), + hint: "This enables automatic sourcemap uploads during build for better error tracking", + }); + + debug(e); + } + }); + + // Configure React Router config for build hook + await traceStep("Configure React Router build hook", async () => { + try { + await configureReactRouterConfig( + typeScriptDetected, + vitePluginImportPath, + ); + } catch (e) { + clack.log.warn( + `Could not configure React Router build hook automatically.`, + ); + + await showCopyPasteInstructions({ + filename: `react-router.config.${typeScriptDetected ? "ts" : "js"}`, + codeSnippet: getManualReactRouterConfigContent( + typeScriptDetected, + vitePluginImportPath, + ), + hint: "This enables automatic sourcemap uploads at the end of the build process", + }); + + debug(e); + } + }); + + // Create example page if requested + if (createExamplePageSelection) { + await traceStep("Create example page", async () => { + await createExamplePage({ + selfHosted, + orgSlug: selectedProject.organization.slug, + projectId: selectedProject.id, + url: sentryUrl, + isTS: typeScriptDetected, + projectDir: process.cwd(), + }); + }); + } + + await runPrettierIfInstalled({ cwd: undefined }); + + // Offer optional project-scoped MCP config for Sentry with org and project scope + await offerProjectScopedMcpConfig( + selectedProject.organization.slug, + selectedProject.slug, + ); + + clack.outro( + `${chalk.green("Successfully installed the Sentry React Router SDK!")}${ + createExamplePageSelection + ? `\n\nYou can validate your setup by visiting ${chalk.cyan( + '"/sentry-example-page"', + )} in your application.` + : "" + }`, + ); +} diff --git a/packages/cli/src/lib/wizard/react-router/sdk-example.ts b/packages/cli/src/lib/wizard/react-router/sdk-example.ts new file mode 100644 index 0000000000..b06c3b3a4b --- /dev/null +++ b/packages/cli/src/lib/wizard/react-router/sdk-example.ts @@ -0,0 +1,337 @@ +/** + * Writes the example page and API route that throw a test error in a React + * Router app. + */ + +import { existsSync, mkdirSync, promises } from "node:fs"; +import path from "node:path"; + +import { clack } from "../utils/clack/prompts.js"; +import chalk from "chalk"; +import { addRoutesToConfig } from "./codemods/routes-config.js"; +import { getRouteFilePath } from "./sdk-setup.js"; + +export async function createExamplePage(options: { + selfHosted: boolean; + orgSlug: string; + projectId: string; + url: string; + isTS: boolean; + projectDir: string; +}) { + const routesPath = path.join(options.projectDir, "app", "routes"); + + if (!existsSync(routesPath)) { + mkdirSync(routesPath, { recursive: true }); + } + + const exampleRoutePath = getRouteFilePath( + "sentry-example-page", + options.isTS, + ); + + const exampleRouteRelative = path.join( + "app", + "routes", + `sentry-example-page.${options.isTS ? "tsx" : "jsx"}`, + ); + + if (existsSync(exampleRoutePath)) { + clack.log.warn( + `It seems like a sentry example page already exists (${path.basename( + exampleRoutePath, + )}). Skipping creation of example route.`, + ); + return; + } + + await promises.writeFile( + exampleRoutePath, + getSentryExamplePageContents(options), + ); + + // Create the API route for backend error testing + const apiRoutePath = path.join( + routesPath, + `api.sentry-example-api.${options.isTS ? "ts" : "js"}`, + ); + + const apiRouteRelative = path.join( + "app", + "routes", + `api.sentry-example-api.${options.isTS ? "ts" : "js"}`, + ); + + if (!existsSync(apiRoutePath)) { + await promises.writeFile( + apiRoutePath, + getSentryExampleApiContents(options), + ); + clack.log.info(`Created ${chalk.cyan(apiRouteRelative)}.`); + } + + // Check if there's a routes.ts configuration file and add the route using codemod + const routesConfigPath = path.join(options.projectDir, "app", "routes.ts"); + if (existsSync(routesConfigPath)) { + try { + await addRoutesToConfig(routesConfigPath, options.isTS); + } catch (e) { + clack.log.warn( + `Could not update routes.ts configuration: ${ + e instanceof Error ? e.message : String(e) + }`, + ); + clack.log.info( + 'Please manually add these routes to your routes.ts file: route("/sentry-example-page", "routes/sentry-example-page.tsx") and route("/api/sentry-example-api", "routes/api.sentry-example-api.ts")', + ); + } + } + + clack.log.info(`Created ${chalk.cyan(exampleRouteRelative)}.`); +} + +export function getSentryExamplePageContents(options: { + selfHosted: boolean; + orgSlug: string; + projectId: string; + url: string; + isTS?: boolean; +}) { + const issuesPageLink = options.selfHosted + ? `${options.url}organizations/${options.orgSlug}/issues/?project=${options.projectId}` + : `https://${options.orgSlug}.sentry.io/issues/?project=${options.projectId}`; + + return `import * as Sentry from '@sentry/react-router'; +import { useState, useEffect } from 'react'; + +class SentryExampleFrontendError extends Error { + constructor(message${options.isTS ? ": string | undefined" : ""}) { + super(message); + this.name = "SentryExampleFrontendError"; + } +} + +export const meta = () => { + return [ + { title: "sentry-example-page" }, + ]; +} + +export default function SentryExamplePage() { + const [hasSentError, setHasSentError] = useState(false); + const [isConnected, setIsConnected] = useState(true); + + useEffect(() => { + async function checkConnectivity() { + const result = await Sentry.diagnoseSdkConnectivity(); + setIsConnected(result !== 'sentry-unreachable'); + } + checkConnectivity(); + }, [setIsConnected]); + + return ( +
+
+
+ + + +

+ 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 ? ( +

+ Sample error was 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.

+
+ ) : ( +
+ )} + +
+
+ + {/* Not for production use! We're just saving you from having to delete an extra CSS file ;) */} + +
+ ); +} + +const styles = \` + main { + display: flex; + min-height: 100vh; + flex-direction: column; + justify-content: center; + align-items: center; + gap: 16px; + padding: 16px; + font-family: system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", sans-serif; + } + + h1 { + padding: 0px 4px; + border-radius: 4px; + background-color: rgba(24, 20, 35, 0.03); + font-family: monospace; + font-size: 20px; + line-height: 1.2; + } + + p { + margin: 0; + font-size: 20px; + } + + a { + color: #6341F0; + text-decoration: underline; + cursor: pointer; + + @media (prefers-color-scheme: dark) { + color: #B3A1FF; + } + } + + button { + border-radius: 8px; + color: white; + cursor: pointer; + background-color: #553DB8; + border: none; + padding: 0; + margin-top: 4px; + + & > span { + display: inline-block; + padding: 12px 16px; + border-radius: inherit; + font-size: 20px; + font-weight: bold; + line-height: 1; + background-color: #7553FF; + border: 1px solid #553DB8; + transform: translateY(-4px); + } + + &:hover > span { + transform: translateY(-8px); + } + + &:active > span { + transform: translateY(0); + } + + &:disabled { + cursor: not-allowed; + opacity: 0.6; + + & > span { + transform: translateY(0); + border: none; + } + } + } + + .description { + text-align: center; + color: #6E6C75; + max-width: 500px; + line-height: 1.5; + font-size: 20px; + + @media (prefers-color-scheme: dark) { + color: #A49FB5; + } + } + + .flex-spacer { + flex: 1; + } + + .success { + padding: 12px 16px; + border-radius: 8px; + font-size: 20px; + line-height: 1; + background-color: #00F261; + border: 1px solid #00BF4D; + color: #181423; + } + + .success_placeholder { + height: 46px; + } + + .connectivity-error { + padding: 12px 16px; + background-color: #E50045; + border-radius: 8px; + width: 500px; + color: #FFFFFF; + border: 1px solid #A80033; + text-align: center; + margin: 0; + } + + .connectivity-error a { + color: #FFFFFF; + text-decoration: underline; + } +\`; +`; +} + +export function getSentryExampleApiContents(options: { isTS?: boolean }) { + return `import * as Sentry from '@sentry/react-router'; + +class SentryExampleBackendError extends Error { + constructor(message${options.isTS ? ": string | undefined" : ""}) { + super(message); + this.name = "SentryExampleBackendError"; + } +} + +export async function loader() { + await Sentry.startSpan({ + name: 'Example Backend Span', + op: 'test' + }, async () => { + // Simulate some backend work + await new Promise(resolve => setTimeout(resolve, 100)); + }); + + throw new SentryExampleBackendError("This error is raised on the backend API route."); +} +`; +} diff --git a/packages/cli/src/lib/wizard/react-router/sdk-setup.ts b/packages/cli/src/lib/wizard/react-router/sdk-setup.ts new file mode 100644 index 0000000000..75bb3c7380 --- /dev/null +++ b/packages/cli/src/lib/wizard/react-router/sdk-setup.ts @@ -0,0 +1,442 @@ +/** + * Setup steps of the React Router wizard: revealing the entry files, + * writing the server instrumentation file, updating `package.json` scripts, + * and the config edits, each with copy-paste instructions as a fallback. + */ + +import { existsSync, promises, writeFileSync } from "node:fs"; +import path from "node:path"; +import { execSync } from "node:child_process"; + +import { clack } from "../utils/clack/prompts.js"; +import chalk from "chalk"; +import { gte, minVersion, coerce } from "semver"; + +import type { PackageDotJson } from "../utils/package-json.js"; +import { getPackageVersion } from "../utils/package-json.js"; +import { debug } from "../utils/debug.js"; +import { getSentryInstrumentationServerContent } from "./templates.js"; +import { instrumentServerEntry } from "./codemods/server-entry.js"; +import { getPackageDotJson } from "../utils/clack/index.js"; +import { instrumentClientEntry } from "./codemods/client.entry.js"; +import { instrumentViteConfig } from "./codemods/vite.js"; +import { instrumentReactRouterConfig } from "./codemods/react-router-config.js"; + +const REACT_ROUTER_REVEAL_COMMAND = "npx react-router reveal"; +const INSTRUMENTATION_FILE = "instrument.server.mjs"; +const APP_DIRECTORY = "app"; +const ROUTES_DIRECTORY = "routes"; + +function _formatConfigErrorMessage( + filename: string, + errorMessage: string, + fallbackHint: string, +): string { + return ( + `Could not automatically configure ${filename}. ${errorMessage}\n` + + `This may happen if your config has an unusual format. ` + + fallbackHint + ); +} + +function getAppFilePath( + filename: string, + isTS: boolean, + isPage = true, +): string { + const ext = isPage ? (isTS ? "tsx" : "jsx") : isTS ? "ts" : "js"; + return path.join(process.cwd(), APP_DIRECTORY, `${filename}.${ext}`); +} + +export function getRouteFilePath(filename: string, isTS: boolean): string { + const ext = isTS ? "tsx" : "jsx"; + return path.join( + process.cwd(), + APP_DIRECTORY, + ROUTES_DIRECTORY, + `${filename}.${ext}`, + ); +} + +export async function tryRevealAndGetManualInstructions( + missingFilename: string, + filePath: string, +): Promise { + const shouldTryReveal = await clack.confirm({ + message: `Would you like to try running ${chalk.cyan( + REACT_ROUTER_REVEAL_COMMAND, + )} to generate entry files?`, + initialValue: true, + }); + + if (shouldTryReveal) { + try { + clack.log.info(`Running ${chalk.cyan(REACT_ROUTER_REVEAL_COMMAND)}...`); + const output = execSync(REACT_ROUTER_REVEAL_COMMAND, { + encoding: "utf8", + stdio: "pipe", + }); + clack.log.info(output); + + if (existsSync(filePath)) { + clack.log.success( + `Found ${chalk.cyan(missingFilename)} after running reveal.`, + ); + return true; + } + clack.log.warn( + `${chalk.cyan(missingFilename)} still not found after running reveal.`, + ); + } catch (e) { + debug("Failed to run React Router reveal command:", e); + clack.log.warn( + `Failed to run ${chalk.cyan( + REACT_ROUTER_REVEAL_COMMAND, + )}. This command generates entry files for React Router v7.`, + ); + } + } + + return false; // File still doesn't exist, manual intervention needed +} + +async function ensureEntryFileExists( + filename: string, + filePath: string, +): Promise { + if (existsSync(filePath)) { + return; // File exists, nothing to do + } + + clack.log.warn(`Could not find ${chalk.cyan(filename)}.`); + + const fileExists = await tryRevealAndGetManualInstructions( + filename, + filePath, + ); + + if (!fileExists) { + throw new Error( + `Failed to create or find ${filename}. Please create this file manually or ensure your React Router v7 project structure is correct.`, + ); + } +} + +export function runReactRouterReveal(): void { + if ( + !existsSync(path.join(process.cwd(), "app", "entry.client.tsx")) && + !existsSync(path.join(process.cwd(), "app", "entry.client.jsx")) + ) { + try { + execSync(REACT_ROUTER_REVEAL_COMMAND, { + encoding: "utf8", + stdio: "pipe", + }); + } catch (e) { + debug("Failed to run React Router reveal command:", e); + throw e; + } + } +} + +export function isReactRouterV7(packageJson: PackageDotJson): boolean { + const reactRouterVersion = getPackageVersion( + "@react-router/dev", + packageJson, + ); + if (!reactRouterVersion) { + return false; + } + + const minVer = minVersion(reactRouterVersion); + + if (!minVer) { + return false; + } + + return gte(minVer, "7.0.0"); +} + +export function getReactRouterVersion( + packageJson: PackageDotJson, +): string | undefined { + const rangeVersion = getPackageVersion("@react-router/dev", packageJson); + if (!rangeVersion) { + return undefined; + } + + const coerced = coerce(rangeVersion); + return coerced ? coerced.version : rangeVersion; +} + +export function supportsOnError(packageJson: PackageDotJson): boolean { + const reactRouterVersion = getPackageVersion( + "@react-router/dev", + packageJson, + ); + if (!reactRouterVersion) { + return false; + } + + const minVer = minVersion(reactRouterVersion); + + if (!minVer) { + return false; + } + + return gte(minVer, "7.11.0"); +} + +export function supportsInstrumentationAPI( + packageJson: PackageDotJson, +): boolean { + const reactRouterVersion = getPackageVersion( + "@react-router/dev", + packageJson, + ); + if (!reactRouterVersion) { + return false; + } + + const minVer = minVersion(reactRouterVersion); + + if (!minVer) { + return false; + } + + return gte(minVer, "7.15.0"); +} + +// oxlint-disable-next-line max-params -- positional like the sentry-wizard original and its tests +export async function initializeSentryOnEntryClient( + dsn: string, + enableTracing: boolean, + enableReplay: boolean, + isTS: boolean, + reduceDataCollection: boolean, + useInstrumentationAPI = false, + useOnError = false, +): Promise { + const clientEntryPath = getAppFilePath("entry.client", isTS); + const clientEntryFilename = path.basename(clientEntryPath); + + await ensureEntryFileExists(clientEntryFilename, clientEntryPath); + + await instrumentClientEntry( + clientEntryPath, + dsn, + enableTracing, + enableReplay, + reduceDataCollection, + useInstrumentationAPI, + useOnError, + ); + + clack.log.success( + `Updated ${chalk.cyan(clientEntryFilename)} with Sentry initialization.`, + ); +} + +export function createServerInstrumentationFile( + dsn: string, + selectedFeatures: { + performance: boolean; + replay: boolean; + profiling: boolean; + }, + reduceDataCollection: boolean, +): string { + const instrumentationPath = path.join(process.cwd(), INSTRUMENTATION_FILE); + + const content = getSentryInstrumentationServerContent( + dsn, + selectedFeatures.performance, + selectedFeatures.profiling, + reduceDataCollection, + ); + + writeFileSync(instrumentationPath, content); + clack.log.success(`Created ${chalk.cyan(INSTRUMENTATION_FILE)}.`); + return instrumentationPath; +} + +export async function updatePackageJsonScripts(): Promise { + const packageJson = await getPackageDotJson(); + + if (!packageJson.scripts) { + throw new Error( + "Could not find a `scripts` section in your package.json file. Please add scripts manually or ensure your package.json is valid.", + ); + } + + if (!packageJson.scripts["start"]) { + throw new Error( + 'Could not find a `start` script in your package.json. Please add: "start": "react-router-serve ./build/server/index.js" and re-run the wizard.', + ); + } + + function mergeNodeOptions( + scriptCommand: string, + instrumentPath = "./instrument.server.mjs", + ): string { + if (scriptCommand.includes(instrumentPath)) { + return scriptCommand; + } + + const quotedMatch = scriptCommand.match(/NODE_OPTIONS=(['"])([^'"]*)\1/); + if (quotedMatch) { + const existingOptions = quotedMatch[2]; + const mergedOptions = + `${existingOptions} --import ${instrumentPath}`.trim(); + return scriptCommand.replace( + /NODE_OPTIONS=(['"])([^'"]*)\1/, + `NODE_OPTIONS='${mergedOptions}'`, + ); + } + + const unquotedMatch = scriptCommand.match( + /NODE_OPTIONS=([^\s]+(?:\s+[^\s]+)*?)(\s+(?:react-router-serve|react-router|node|npx|tsx))/, + ); + if (unquotedMatch) { + const existingOptions = unquotedMatch[1]; + const commandPart = unquotedMatch[2]; + const mergedOptions = + `${existingOptions} --import ${instrumentPath}`.trim(); + return scriptCommand.replace( + /NODE_OPTIONS=([^\s]+(?:\s+[^\s]+)*?)(\s+(?:react-router-serve|react-router|node|npx|tsx))/, + `NODE_OPTIONS='${mergedOptions}'${commandPart}`, + ); + } + + return `NODE_OPTIONS='--import ${instrumentPath}' ${scriptCommand}`; + } + + if (packageJson.scripts["dev"]) { + packageJson.scripts["dev"] = mergeNodeOptions(packageJson.scripts["dev"]); + } + + const startScript = packageJson.scripts["start"]; + if ( + !startScript.includes(INSTRUMENTATION_FILE) && + !startScript.includes("NODE_OPTIONS") + ) { + packageJson.scripts["start"] = + `NODE_OPTIONS='--import ./${INSTRUMENTATION_FILE}' react-router-serve ./build/server/index.js`; + } else { + packageJson.scripts["start"] = mergeNodeOptions(startScript); + } + + // Prevent React CJS dev/prod bundle mismatch when --import loads react + // before react-router-serve sets NODE_ENV + if ( + packageJson.scripts["start"].includes("--import") && + !packageJson.scripts["start"].includes("NODE_ENV=") + ) { + packageJson.scripts["start"] = + `NODE_ENV=production ${packageJson.scripts["start"]}`; + } + + await promises.writeFile( + "package.json", + JSON.stringify(packageJson, null, 2), + ); +} + +export async function instrumentSentryOnEntryServer( + isTS: boolean, + useInstrumentationAPI = false, +): Promise { + const serverEntryPath = getAppFilePath("entry.server", isTS); + const serverEntryFilename = path.basename(serverEntryPath); + + await ensureEntryFileExists(serverEntryFilename, serverEntryPath); + + await instrumentServerEntry(serverEntryPath, useInstrumentationAPI); + + clack.log.success( + `Updated ${chalk.cyan(serverEntryFilename)} with Sentry error handling.`, + ); +} + +export async function configureReactRouterVitePlugin( + orgSlug: string, + projectSlug: string, + vitePluginImportPath: string, +): Promise { + const configPath = existsSync(path.join(process.cwd(), "vite.config.ts")) + ? path.join(process.cwd(), "vite.config.ts") + : path.join(process.cwd(), "vite.config.js"); + const filename = chalk.cyan(path.basename(configPath)); + + try { + const { wasConverted } = await instrumentViteConfig( + orgSlug, + projectSlug, + vitePluginImportPath, + ); + + clack.log.success(`Updated ${filename} with sentryReactRouter plugin.`); + + if (wasConverted) { + clack.log.info( + `Converted your Vite config to function form ${chalk.dim( + "(defineConfig(config => ({ ... })))", + )} to support the Sentry React Router plugin.`, + ); + } + } catch (e) { + debug("Failed to modify vite config:", e); + const errorMessage = e instanceof Error ? e.message : String(e); + throw new Error( + _formatConfigErrorMessage( + filename, + errorMessage, + "You may need to add the plugin manually.", + ), + ); + } +} + +export async function configureReactRouterConfig( + isTS: boolean, + vitePluginImportPath: string, +): Promise { + const configFilename = `react-router.config.${isTS ? "ts" : "js"}`; + const configPath = path.join(process.cwd(), configFilename); + const filename = chalk.cyan(configFilename); + + try { + const fileExistedBefore = existsSync(configPath); + + const { ssrWasChanged } = await instrumentReactRouterConfig( + isTS, + vitePluginImportPath, + ); + + if (fileExistedBefore) { + clack.log.success(`Updated ${filename} with Sentry buildEnd hook.`); + } else { + clack.log.success(`Created ${filename} with Sentry buildEnd hook.`); + } + + if (ssrWasChanged) { + clack.log.warn( + `${chalk.yellow( + "Note:", + )} SSR has been enabled in your React Router config (${chalk.cyan( + "ssr: true", + )}). This is required for Sentry sourcemap uploads to work correctly.`, + ); + } + } catch (e) { + debug("Failed to modify react-router.config:", e); + const errorMessage = e instanceof Error ? e.message : String(e); + throw new Error( + _formatConfigErrorMessage( + filename, + errorMessage, + "You may need to add the buildEnd hook manually.", + ), + ); + } +} diff --git a/packages/cli/src/lib/wizard/react-router/sdk-version.ts b/packages/cli/src/lib/wizard/react-router/sdk-version.ts new file mode 100644 index 0000000000..a08793f961 --- /dev/null +++ b/packages/cli/src/lib/wizard/react-router/sdk-version.ts @@ -0,0 +1,37 @@ +import { getMajorVersion } from "../utils/semver.js"; + +/** + * Version range of `@sentry/react-router` (and `@sentry/profiling-node`) the + * wizard installs. Also decides the default import path of the Vite plugin + * helpers when the installed version is unknown. + */ +export const SENTRY_REACT_ROUTER_SDK_RANGE = "^11"; + +/** Root export. Exposes `sentryReactRouter` and `sentryOnBuildEnd` up to SDK v10 only. */ +export const SENTRY_REACT_ROUTER_ROOT_IMPORT_PATH = "@sentry/react-router"; + +/** Subpath that exposes the Vite plugin helpers from SDK v11 on. v10 does not ship it. */ +export const SENTRY_REACT_ROUTER_VITE_IMPORT_PATH = "@sentry/react-router/vite"; + +/** Minimum React Router version supported by SDK v11 in framework mode. */ +export const MIN_REACT_ROUTER_VERSION_FOR_SDK_V11 = "7.15.0"; + +/** + * Returns the module `sentryReactRouter` and `sentryOnBuildEnd` must be + * imported from for the installed SDK. v11 moved them to the `/vite` subpath + * and removed them from the root export, while v10 only has them on the root + * export. Unknown or unparseable versions fall back to whatever the wizard + * would install. + */ +export function getSentryReactRouterVitePluginImportPath( + installedSdkVersion: string | undefined, +): string { + const sdkMajor = + getMajorVersion(installedSdkVersion) ?? + getMajorVersion(SENTRY_REACT_ROUTER_SDK_RANGE) ?? + 0; + + return sdkMajor >= 11 + ? SENTRY_REACT_ROUTER_VITE_IMPORT_PATH + : SENTRY_REACT_ROUTER_ROOT_IMPORT_PATH; +} diff --git a/packages/cli/src/lib/wizard/react-router/templates.ts b/packages/cli/src/lib/wizard/react-router/templates.ts new file mode 100644 index 0000000000..2f7b87481b --- /dev/null +++ b/packages/cli/src/lib/wizard/react-router/templates.ts @@ -0,0 +1,380 @@ +/** + * Code templates the React Router wizard writes or shows as copy-paste + * instructions. + */ + +import { makeCodeSnippet } from "../utils/clack/index.js"; +import { getDataCollectionSnippet } from "../utils/data-collection.js"; +import { getSentryReactRouterVitePluginImportPath } from "./sdk-version.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/react-router/configuration/options/#dataCollection + // userInfo: false, + // httpBodies: [], + },`; + +/** + * The active PII-reducing preset when the user opted in, the commented-out + * hint otherwise. + */ +export function getDataCollectionBlock(reduceDataCollection: boolean): string { + return reduceDataCollection + ? getDataCollectionSnippet(" ") + : DATA_COLLECTION_HINT; +} + +export const EXAMPLE_PAGE_TEMPLATE_TSX = `import type { Route } from "./+types/sentry-example-page"; + +export async function loader() { + throw new Error("some error thrown in a loader"); +} + +export default function SentryExamplePage() { + return
Loading this page will throw an error
; +}`; + +export const EXAMPLE_PAGE_TEMPLATE_JSX = `export async function loader() { + throw new Error("some error thrown in a loader"); +} + +export default function SentryExamplePage() { + return
Loading this page will throw an error
; +}`; + +function generateServerInstrumentationCode( + dsn: string, + enableTracing: boolean, + enableProfiling: boolean, + reduceDataCollection: boolean, +): string { + return `import * as Sentry from '@sentry/react-router';${ + enableProfiling + ? `\nimport { nodeProfilingIntegration } from '@sentry/profiling-node';` + : "" + } + +Sentry.init({ + dsn: "${dsn}", + +${getDataCollectionBlock(reduceDataCollection)}${ + enableProfiling ? "\n\n integrations: [nodeProfilingIntegration()]," : "" + } + tracesSampleRate: ${enableTracing ? "1.0" : "0"}, ${ + enableTracing ? "// Capture 100% of the traces" : "" + }${ + enableProfiling + ? `\n profileSessionSampleRate: 1.0, // profile every session\n profileLifecycle: "trace", // profile while a trace is active` + : "" + }${ + enableTracing + ? ` + + // Set up performance monitoring + beforeSend(event) { + // Filter out 404s from error reporting + if (event.exception) { + const error = event.exception.values?.[0]; + if (error?.type === "NotFoundException" || error?.value?.includes("404")) { + return null; + } + } + return event; + },` + : "" + } +});`; +} + +export const getSentryInstrumentationServerContent = ( + dsn: string, + enableTracing: boolean, + enableProfiling: boolean, + reduceDataCollection: boolean, +) => { + return generateServerInstrumentationCode( + dsn, + enableTracing, + enableProfiling, + reduceDataCollection, + ); +}; + +// oxlint-disable-next-line max-params -- positional like the sentry-wizard original and its tests +export const getManualClientEntryContent = ( + dsn: string, + enableTracing: boolean, + enableReplay: boolean, + reduceDataCollection: boolean, + useInstrumentationAPI = false, + useOnError = false, +) => { + if (useInstrumentationAPI && enableTracing) { + const integrations = ["tracing"]; + if (enableReplay) { + integrations.push("Sentry.replayIntegration()"); + } + + const integrationsStr = integrations.join(",\n "); + + return makeCodeSnippet(true, (unchanged, plus) => + unchanged(`${plus("import * as Sentry from '@sentry/react-router';")} +import { startTransition, StrictMode } from 'react'; +import { hydrateRoot } from 'react-dom/client'; +import { HydratedRouter } from 'react-router/dom'; + +${plus(`const tracing = Sentry.reactRouterTracingIntegration();`)} + +${plus(`Sentry.init({ + dsn: "${dsn}", + +${getDataCollectionBlock(reduceDataCollection)} + + integrations: [ + ${integrationsStr} + ], + + tracesSampleRate: 1.0, // Capture 100% of the traces + + // Set \`tracePropagationTargets\` to declare which URL(s) should have trace propagation enabled + // In production, replace "yourserver.io" with your actual backend domain + tracePropagationTargets: [/^\\//, /^https:\\/\\/yourserver\\.io\\/api/],${ + enableReplay + ? "\n\n // Capture Replay for 10% of all sessions,\n // plus 100% of sessions with an error\n replaysSessionSampleRate: 0.1,\n replaysOnErrorSampleRate: 1.0," + : "" + } +});`)} + +startTransition(() => { + hydrateRoot( + document, + + ${plus( + ``, + )} + + ); +});`), + ); + } + + const integrations = []; + + if (enableTracing) { + integrations.push("Sentry.reactRouterTracingIntegration()"); + } + + if (enableReplay) { + integrations.push("Sentry.replayIntegration()"); + } + + const integrationsStr = + integrations.length > 0 ? integrations.join(",\n ") : ""; + + return makeCodeSnippet(true, (unchanged, plus) => + unchanged(`${plus("import * as Sentry from '@sentry/react-router';")} +import { startTransition, StrictMode } from 'react'; +import { hydrateRoot } from 'react-dom/client'; +import { HydratedRouter } from 'react-router/dom'; + +${plus(`Sentry.init({ + dsn: "${dsn}", + +${getDataCollectionBlock(reduceDataCollection)} + + integrations: [ + ${integrationsStr} + ], + + tracesSampleRate: ${enableTracing ? "1.0" : "0"},${ + enableTracing ? " // Capture 100% of the traces" : "" + }${ + enableTracing + ? '\n\n // Set `tracePropagationTargets` to declare which URL(s) should have trace propagation enabled\n // In production, replace "yourserver.io" with your actual backend domain\n tracePropagationTargets: [/^\\//, /^https:\\/\\/yourserver\\.io\\/api/],' + : "" + }${ + enableReplay + ? "\n\n // Capture Replay for 10% of all sessions,\n // plus 100% of sessions with an error\n replaysSessionSampleRate: 0.1,\n replaysOnErrorSampleRate: 1.0," + : "" + } +});`)} + +startTransition(() => { + hydrateRoot( + document, + + ${plus( + ``, + )} + + ); +});`), + ); +}; + +export const getManualServerEntryContent = (useInstrumentationAPI = false) => { + if (useInstrumentationAPI) { + return makeCodeSnippet(true, (unchanged, plus) => + unchanged(`${plus("import * as Sentry from '@sentry/react-router';")} +import { createReadableStreamFromReadable } from '@react-router/node'; +import { renderToPipeableStream } from 'react-dom/server'; +import { ServerRouter } from 'react-router'; + +${plus(`const handleRequest = Sentry.createSentryHandleRequest({ + ServerRouter, + renderToPipeableStream, + createReadableStreamFromReadable, +});`)} + +export default handleRequest; + +${plus(`export const handleError = Sentry.createSentryHandleError({ + logErrors: false +});`)} + +${plus(`// Enable automatic server-side instrumentation for loaders, actions, middleware +export const instrumentations = [Sentry.createSentryServerInstrumentation()];`)} + +// ... rest of your server entry`), + ); + } + + return makeCodeSnippet(true, (unchanged, plus) => + unchanged(`${plus("import * as Sentry from '@sentry/react-router';")} +import { createReadableStreamFromReadable } from '@react-router/node'; +import { renderToPipeableStream } from 'react-dom/server'; +import { ServerRouter } from 'react-router'; + +${plus(`const handleRequest = Sentry.createSentryHandleRequest({ + ServerRouter, + renderToPipeableStream, + createReadableStreamFromReadable, +});`)} + +export default handleRequest; + +${plus(`export const handleError = Sentry.createSentryHandleError({ + logErrors: false +});`)} + +// ... rest of your server entry`), + ); +}; + +export const getManualHandleRequestContent = () => { + return makeCodeSnippet(true, (unchanged, plus) => + unchanged(`${plus("import * as Sentry from '@sentry/react-router';")} +import { createReadableStreamFromReadable } from '@react-router/node'; +import { renderToPipeableStream } from 'react-dom/server'; +import { ServerRouter } from 'react-router'; + +${plus(`// Replace your existing handleRequest function with this Sentry-wrapped version: +const handleRequest = Sentry.createSentryHandleRequest({ + ServerRouter, + renderToPipeableStream, + createReadableStreamFromReadable, +});`)} + +${plus(`// If you have a custom handleRequest implementation, wrap it like this: +// export default Sentry.wrapSentryHandleRequest(yourCustomHandleRequest);`)} + +export default handleRequest;`), + ); +}; + +export const getManualServerInstrumentContent = ( + dsn: string, + enableTracing: boolean, + enableProfiling: boolean, + reduceDataCollection: boolean, +) => { + return makeCodeSnippet(true, (_unchanged, plus) => + plus( + generateServerInstrumentationCode( + dsn, + enableTracing, + enableProfiling, + reduceDataCollection, + ), + ), + ); +}; + +export const getManualReactRouterConfigContent = ( + isTS = true, + vitePluginImportPath: string = getSentryReactRouterVitePluginImportPath( + undefined, + ), +) => { + return makeCodeSnippet(true, (unchanged, plus) => + isTS + ? unchanged(`${plus( + 'import type { Config } from "@react-router/dev/config";', + )} +${plus(`import { sentryOnBuildEnd } from '${vitePluginImportPath}';`)} + +export default { + ${plus("ssr: true,")} + ${plus(`buildEnd: async ({ viteConfig, reactRouterConfig, buildManifest }) => { + await sentryOnBuildEnd({ viteConfig, reactRouterConfig, buildManifest }); + },`)} +} satisfies Config; + +// If you already have a buildEnd hook, modify it to call sentryOnBuildEnd: +// buildEnd: async (args) => { +// await yourExistingLogic(args); +// await sentryOnBuildEnd(args); +// }`) + : unchanged(`${plus( + `import { sentryOnBuildEnd } from '${vitePluginImportPath}';`, + )} + +export default { + ${plus("ssr: true,")} + ${plus(`buildEnd: async ({ viteConfig, reactRouterConfig, buildManifest }) => { + await sentryOnBuildEnd({ viteConfig, reactRouterConfig, buildManifest }); + },`)} +}; + +// If you already have a buildEnd hook, modify it to call sentryOnBuildEnd: +// buildEnd: async (args) => { +// await yourExistingLogic(args); +// await sentryOnBuildEnd(args); +// }`), + ); +}; + +export const getManualViteConfigContent = ( + orgSlug: string, + projectSlug: string, + vitePluginImportPath: string = getSentryReactRouterVitePluginImportPath( + undefined, + ), +) => { + return makeCodeSnippet(true, (unchanged, plus) => + unchanged(`${plus( + `import { sentryReactRouter } from '${vitePluginImportPath}';`, + )} +import { defineConfig } from 'vite'; + +export default defineConfig(config => { + return { + plugins: [ + // ... your existing plugins + ${plus(`sentryReactRouter({ + org: "${orgSlug}", + project: "${projectSlug}", + authToken: process.env.SENTRY_AUTH_TOKEN, + }, config),`)} + ], + ${plus(`optimizeDeps: { + exclude: ['@sentry/react-router'], + },`)} + }; +});`), + ); +}; diff --git a/packages/cli/src/lib/wizard/remix/codemods/express-server.ts b/packages/cli/src/lib/wizard/remix/codemods/express-server.ts new file mode 100644 index 0000000000..09d9dd844b --- /dev/null +++ b/packages/cli/src/lib/wizard/remix/codemods/express-server.ts @@ -0,0 +1,46 @@ +/** + * Finds a custom Express server in a Remix app, so the wizard can import + * the instrumentation file there. + */ + +import { loadFile } from "magicast"; +import { statSync } from "node:fs"; + +import { findFile } from "../../utils/ast-utils.js"; + +// Try to find the Express server implementation that contains `createRequestHandler` from `@remix-run/express` +export async function findCustomExpressServerImplementation() { + const possiblePaths = [ + "server", + "server/index", + "app/server", + "app/server/index", + ]; + + for (const filePath of possiblePaths) { + const filename = findFile(filePath); + + if (!filename) { + continue; + } + + const fileStat = statSync(filename); + + if (!fileStat.isFile()) { + continue; + } + + const fileMod = await loadFile(filename); + const createRequestHandlerImport = fileMod.imports.$items.find( + (imp) => + imp.from === "@remix-run/express" && + imp.imported === "createRequestHandler", + ); + + if (createRequestHandlerImport) { + return filename; + } + } + + return null; +} diff --git a/packages/cli/src/lib/wizard/remix/codemods/handle-error.ts b/packages/cli/src/lib/wizard/remix/codemods/handle-error.ts new file mode 100644 index 0000000000..8d741f2f52 --- /dev/null +++ b/packages/cli/src/lib/wizard/remix/codemods/handle-error.ts @@ -0,0 +1,104 @@ +/** + * Adds or wraps `handleError` in a Remix `entry.server` file so server + * errors reach Sentry. + */ + +import type { ProxifiedModule } from "magicast"; +import type { namedTypes as t } from "ast-types"; + +import recast from "recast"; + +import { HANDLE_ERROR_TEMPLATE } from "../templates.js"; +import { getAfterImportsInsertionIndex, hasSentryContent } from "../utils.js"; + +import { clack } from "../../utils/clack/prompts.js"; +import chalk from "chalk"; + +export function instrumentHandleError( + originalEntryServerMod: ProxifiedModule, + serverEntryFilename: string, +): boolean { + const originalEntryServerModAST = originalEntryServerMod.$ast as t.Program; + + const handleErrorFunctionExport = originalEntryServerModAST.body.find( + (node) => { + return ( + node.type === "ExportNamedDeclaration" && + node.declaration?.type === "FunctionDeclaration" && + node.declaration.id?.name === "handleError" + ); + }, + ); + + const handleErrorFunctionVariableDeclarationExport = + originalEntryServerModAST.body.find( + (node) => + node.type === "ExportNamedDeclaration" && + node.declaration?.type === "VariableDeclaration" && + // @ts-expect-error - id should always have a name in this case + node.declaration.declarations[0].id.name === "handleError", + ); + + if ( + !handleErrorFunctionExport && + !handleErrorFunctionVariableDeclarationExport + ) { + clack.log.warn( + `Could not find function ${chalk.cyan("handleError")} in ${chalk.cyan( + serverEntryFilename, + )}. Creating one for you.`, + ); + + const implementation = recast.parse(HANDLE_ERROR_TEMPLATE).program.body[0]; + + originalEntryServerModAST.body.splice( + getAfterImportsInsertionIndex(originalEntryServerModAST), + 0, + recast.types.builders.exportNamedDeclaration(implementation), + ); + } else if ( + (handleErrorFunctionExport && + ["wrapHandleErrorWithSentry", "sentryHandleError"].some((util) => + hasSentryContent( + recast.print(handleErrorFunctionExport).code, + originalEntryServerMod.$code, + util, + ), + )) || + (handleErrorFunctionVariableDeclarationExport && + ["wrapHandleErrorWithSentry", "sentryHandleError"].some((util) => + hasSentryContent( + recast.print(handleErrorFunctionVariableDeclarationExport).code, + originalEntryServerMod.$code, + util, + ), + )) + ) { + return false; + } else if (handleErrorFunctionExport) { + const implementation = recast.parse(HANDLE_ERROR_TEMPLATE).program.body[0]; + + // If the current handleError function has a body, we need to merge the new implementation with the existing one + implementation.declarations[0].init.arguments[0].body.body.unshift( + // @ts-expect-error - declaration works here because the AST is proxified by magicast + ...handleErrorFunctionExport.declaration.body.body, + ); + + // @ts-expect-error - declaration works here because the AST is proxified by magicast + handleErrorFunctionExport.declaration = implementation; + } else if (handleErrorFunctionVariableDeclarationExport) { + const implementation = recast.parse(HANDLE_ERROR_TEMPLATE).program.body[0]; + + // If the current handleError function has a body, we need to merge the new implementation with the existing one + implementation.declarations[0].init.arguments[0].body.body.unshift( + // @ts-expect-error - declaration works here because the AST is proxified by magicast + ...handleErrorFunctionVariableDeclarationExport.declaration + .declarations[0].init.body.body, + ); + + // @ts-expect-error - declaration works here because the AST is proxified by magicast + handleErrorFunctionVariableDeclarationExport.declaration = implementation; + } + + return true; +} diff --git a/packages/cli/src/lib/wizard/remix/codemods/root.ts b/packages/cli/src/lib/wizard/remix/codemods/root.ts new file mode 100644 index 0000000000..ca80578747 --- /dev/null +++ b/packages/cli/src/lib/wizard/remix/codemods/root.ts @@ -0,0 +1,244 @@ +/** + * Wraps a Remix root route with `withSentry` and captures errors in its + * `ErrorBoundary`. + */ + +import recast from "recast"; +import path from "node:path"; + +import type { namedTypes as t } from "ast-types"; + +import { + builders, + generateCode, + loadFile, + type ProxifiedModule, + writeFile, +} from "magicast"; + +import { ERROR_BOUNDARY_TEMPLATE } from "../templates.js"; +import { hasSentryContent } from "../utils.js"; +import chalk from "chalk"; + +import { clack } from "../../utils/clack/prompts.js"; + +export function wrapAppWithSentry( + rootRouteAst: ProxifiedModule, + rootFileName: string, +) { + rootRouteAst.imports.$add({ + from: "@sentry/remix", + imported: "withSentry", + local: "withSentry", + }); + + recast.visit(rootRouteAst.$ast, { + visitExportDefaultDeclaration(path) { + if (path.value.declaration.type === "FunctionDeclaration") { + // Move the function declaration just before the default export + path.insertBefore(path.value.declaration); + + // Get the name of the function to be wrapped + const functionName: string = path.value.declaration.id.name as string; + + // Create the wrapped function call + const functionCall = recast.types.builders.callExpression( + recast.types.builders.identifier("withSentry"), + [recast.types.builders.identifier(functionName)], + ); + + // Replace the default export with the wrapped function call + path.value.declaration = functionCall; + } else if (path.value.declaration.type === "Identifier") { + const rootRouteExport = rootRouteAst.exports["default"]; + + const expressionToWrap = generateCode(rootRouteExport.$ast).code; + + rootRouteAst.exports["default"] = builders.raw( + `withSentry(${expressionToWrap})`, + ); + } else { + clack.log.warn( + chalk.yellow( + `Couldn't instrument ${chalk.bold( + rootFileName, + )} automatically. Wrap your default export with: ${chalk.dim( + "withSentry()", + )}\n`, + ), + ); + } + + this.traverse(path); + }, + }); +} + +export function isWithSentryAlreadyUsed( + rootRouteAst: ProxifiedModule, +): boolean { + // Check if withSentry is called anywhere in the code + let isUsed = false; + recast.visit(rootRouteAst.$ast, { + visitCallExpression(path) { + if ( + path.value.callee.type === "Identifier" && + path.value.callee.name === "withSentry" + ) { + isUsed = true; + return false; // Stop traversal + } + this.traverse(path); + return undefined; + }, + }); + return isUsed; +} + +export async function instrumentRoot(rootFileName: string): Promise { + const rootRouteAst = await loadFile( + path.join(process.cwd(), "app", rootFileName), + ); + + const exportsAst = rootRouteAst.exports.$ast as t.Program; + + const namedExports = exportsAst.body.filter( + (node): node is t.ExportNamedDeclaration => + node.type === "ExportNamedDeclaration", + ); + + let foundErrorBoundary = false as boolean; + const withSentryAlreadyUsed = isWithSentryAlreadyUsed(rootRouteAst); + + namedExports.forEach((namedExport) => { + const declaration = namedExport.declaration; + + if (!declaration) { + return; + } + + if (declaration.type === "FunctionDeclaration") { + if (declaration.id?.name === "ErrorBoundary") { + foundErrorBoundary = true; + } + } else if (declaration.type === "VariableDeclaration") { + const declarations = declaration.declarations; + + declarations.forEach((declaration) => { + // @ts-expect-error - id should always have a name in this case + if (declaration.id?.name === "ErrorBoundary") { + foundErrorBoundary = true; + } + }); + } + }); + + if (!foundErrorBoundary) { + rootRouteAst.imports.$add({ + from: "@sentry/remix", + imported: "captureRemixErrorBoundaryError", + local: "captureRemixErrorBoundaryError", + }); + + rootRouteAst.imports.$add({ + from: "@remix-run/react", + imported: "useRouteError", + local: "useRouteError", + }); + + // Call wrapAppWithSentry if withSentry is not already used + if (!withSentryAlreadyUsed) { + wrapAppWithSentry(rootRouteAst, rootFileName); + } + + recast.visit(rootRouteAst.$ast, { + visitExportDefaultDeclaration(path) { + const implementation = recast.parse(ERROR_BOUNDARY_TEMPLATE).program + .body[0]; + + path.insertBefore( + recast.types.builders.exportDeclaration(false, implementation), + ); + + this.traverse(path); + }, + }); + // If there is already a ErrorBoundary export, and it doesn't have Sentry content + } else if (!hasSentryContent(rootFileName, rootRouteAst.$code)) { + rootRouteAst.imports.$add({ + from: "@sentry/remix", + imported: "captureRemixErrorBoundaryError", + local: "captureRemixErrorBoundaryError", + }); + + // Call wrapAppWithSentry if withSentry is not already used + if (!withSentryAlreadyUsed) { + wrapAppWithSentry(rootRouteAst, rootFileName); + } + + recast.visit(rootRouteAst.$ast, { + visitExportNamedDeclaration(path) { + // Find ErrorBoundary export + if (path.value.declaration?.id?.name === "ErrorBoundary") { + const errorBoundaryExport = path.value.declaration; + + let errorIdentifier = undefined as string | undefined; + + // check if useRouteError is called + recast.visit(errorBoundaryExport, { + visitVariableDeclaration(path) { + const variableDeclaration = path.value.declarations[0]; + const initializer = variableDeclaration.init; + + if ( + initializer.type === "CallExpression" && + initializer.callee.name === "useRouteError" + ) { + errorIdentifier = variableDeclaration.id.name; + } + + this.traverse(path); + }, + }); + + // We don't have an errorIdentifier, which means useRouteError is not called / imported + // We need to add it and capture the error + if (!errorIdentifier) { + rootRouteAst.imports.$add({ + from: "@remix-run/react", + imported: "useRouteError", + local: "useRouteError", + }); + + const useRouteErrorCall = recast.parse( + `const error = useRouteError();`, + ).program.body[0]; + + // Insert at the top of ErrorBoundary body + errorBoundaryExport.body.body.splice(0, 0, useRouteErrorCall); + } + + const captureErrorCall = recast.parse( + `captureRemixErrorBoundaryError(error);`, + ).program.body[0]; + + // Insert just before the the fallback page is returned + errorBoundaryExport.body.body.splice( + errorBoundaryExport.body.body.length - 1, + 0, + captureErrorCall, + ); + } + this.traverse(path); + }, + }); + } else if (!withSentryAlreadyUsed) { + // Even if we have Sentry content but withSentry is not used, we should still wrap the app + wrapAppWithSentry(rootRouteAst, rootFileName); + } + + await writeFile( + rootRouteAst.$ast, + path.join(process.cwd(), "app", rootFileName), + ); +} diff --git a/packages/cli/src/lib/wizard/remix/remix-wizard.ts b/packages/cli/src/lib/wizard/remix/remix-wizard.ts new file mode 100644 index 0000000000..9c427af1d2 --- /dev/null +++ b/packages/cli/src/lib/wizard/remix/remix-wizard.ts @@ -0,0 +1,318 @@ +/** + * The Remix (v2) setup wizard: installs `@sentry/remix`, instruments the + * client and server entries and the root route, writes the server + * instrumentation file, and sets up source map uploads. + */ + +import { clack } from "../utils/clack/prompts.js"; +import chalk from "chalk"; +import path from "node:path"; + +import { traceStep, withTelemetry } from "../telemetry.js"; +import { findFile } from "../utils/ast-utils.js"; +import { + addDotEnvSentryBuildPluginFile, + addSentryCliConfig, + askShouldCreateExamplePage, + confirmContinueIfNoOrDirtyGitRepo, + ensurePackageIsInstalled, + featureSelectionPrompt, + getOrAskForProjectData, + getPackageDotJson, + installPackage, + printSdkV11MigrationGuideIfOutdated, + isUsingTypeScript, + printWelcome, + rcCliSetupConfig, + runPrettierIfInstalled, +} from "../utils/clack/index.js"; +import { + askShouldReduceDataCollection, + sdkSupportsDataCollection, +} from "../utils/data-collection.js"; +import { debug } from "../utils/debug.js"; +import { + getPackageVersion, + hasPackageInstalled, +} from "../utils/package-json.js"; +import type { WizardOptions } from "../utils/types.js"; +import { offerProjectScopedMcpConfig } from "../utils/clack/mcp-config.js"; +import { createExamplePage } from "./sdk-example.js"; +import { + createServerInstrumentationFile, + initializeSentryOnEntryClient, + insertServerInstrumentationFile, + instrumentRootRoute, + instrumentSentryOnEntryServer, + isRemixV2, + runRemixReveal, + updateBuildScript, + updateStartScript, +} from "./sdk-setup.js"; +import { isHydrogenApp } from "./utils.js"; +import { abortIfSpotlightNotSupported } from "../utils/abort-if-sportlight-not-supported.js"; +import { warnIfNodeVersionUnsupportedBySdkV11 } from "../utils/node-version.js"; + +export async function runRemixWizard(options: WizardOptions): Promise { + return await withTelemetry( + { + enabled: options.telemetryEnabled, + integration: "remix", + wizardOptions: options, + }, + () => runRemixWizardWithTelemetry(options), + ); +} + +async function runRemixWizardWithTelemetry( + options: WizardOptions, +): Promise { + const { promoCode, telemetryEnabled, forceInstall } = options; + + printWelcome({ + wizardName: "Sentry Remix Wizard", + promoCode, + telemetryEnabled, + }); + + const packageJson = await getPackageDotJson(); + + if (!isRemixV2(packageJson)) { + clack.log.error( + `Sentry only supports Remix v2 and above. Please upgrade your Remix version to use Sentry.`, + ); + return; + } + + warnIfNodeVersionUnsupportedBySdkV11(); + + await confirmContinueIfNoOrDirtyGitRepo({ + ignoreGitChanges: options.ignoreGitChanges, + cwd: undefined, + }); + + // We expect `@remix-run/dev` to be installed for every Remix project + await ensurePackageIsInstalled(packageJson, "@remix-run/dev", "Remix"); + + const projectData = await getOrAskForProjectData(options, "javascript-remix"); + + if (projectData.spotlight) { + return await abortIfSpotlightNotSupported("Remix"); + } + + const { selectedProject, authToken, sentryUrl, selfHosted } = projectData; + + printSdkV11MigrationGuideIfOutdated("@sentry/remix", packageJson); + + await installPackage({ + packageName: "@sentry/remix@^11", + packageNameDisplayLabel: "@sentry/remix", + alreadyInstalled: hasPackageInstalled("@sentry/remix", packageJson), + forceInstall, + }); + + // The install may have been skipped (user declined the update prompt), so + // re-read package.json to learn which SDK major is actually installed. + const installedSdkVersion = getPackageVersion( + "@sentry/remix", + await getPackageDotJson(), + ); + + // From v11 on, the SDK collects rich context by default, so offer to + // reduce collection of data that can identify users. + const reduceDataCollection = + sdkSupportsDataCollection(installedSdkVersion, "^10") && + (await askShouldReduceDataCollection()); + + const dsn = selectedProject.keys[0].dsn.public; + + const isTS = isUsingTypeScript(); + const viteConfig = findFile("vite.config"); + 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); + + if (viteConfig) { + // The source maps wizard's Vite setup isn't in the CLI yet, so point at + // the manual steps and write the auth token the plugin reads. + await traceStep( + "Update vite configuration for sourcemap uploads", + async () => { + clack.log.info( + `To upload source maps, add the Sentry Vite plugin to your ${chalk.cyan( + path.basename(viteConfig), + )} using the instructions at https://docs.sentry.io/platforms/javascript/guides/remix/sourcemaps/`, + ); + await addDotEnvSentryBuildPluginFile(authToken); + }, + ); + } else { + await traceStep("Update build script for sourcemap uploads", async () => { + try { + await updateBuildScript({ + org: selectedProject.organization.slug, + project: selectedProject.slug, + url: selfHosted ? sentryUrl : undefined, + isHydrogen: isHydrogenApp(packageJson), + }); + + await addSentryCliConfig({ authToken }, rcCliSetupConfig); + } catch (e) { + clack.log + .warn(`Could not update build script to generate and upload sourcemaps. + Please update your build script manually using instructions from https://docs.sentry.io/platforms/javascript/guides/remix/sourcemaps/`); + debug(e); + } + }); + } + + await traceStep("Instrument root route", async () => { + try { + await instrumentRootRoute(isTS); + } catch (e) { + clack.log.warn(`Could not instrument root route. + Please do it manually using instructions from https://docs.sentry.io/platforms/javascript/guides/remix/manual-setup/`); + debug(e); + } + }); + + traceStep("Reveal missing entry files", () => { + try { + runRemixReveal(isTS); + } catch (e) { + clack.log.warn(`Could not run 'npx remix reveal'. + Please create your entry files manually`); + debug(e); + } + }); + + await traceStep("Initialize Sentry on client entry", async () => { + try { + await initializeSentryOnEntryClient( + dsn, + isTS, + selectedFeatures, + reduceDataCollection, + ); + } catch (e) { + clack.log.warn(`Could not initialize Sentry on client entry. + Please do it manually using instructions from https://docs.sentry.io/platforms/javascript/guides/remix/manual-setup/`); + debug(e); + } + }); + + let instrumentationFile = "" as string; + + await traceStep("Create server instrumentation file", async () => { + try { + instrumentationFile = await createServerInstrumentationFile( + dsn, + selectedFeatures, + reduceDataCollection, + ); + } catch (e) { + clack.log.warn( + "Could not create a server instrumentation file. Please do it manually using instructions from https://docs.sentry.io/platforms/javascript/guides/remix/manual-setup/", + ); + debug(e); + } + }); + + let serverFileInstrumented = false as boolean; + + await traceStep( + "Create server instrumentation file and import it", + async () => { + try { + serverFileInstrumented = await insertServerInstrumentationFile( + dsn, + selectedFeatures, + reduceDataCollection, + ); + } catch (e) { + clack.log.warn( + "Could not create a server instrumentation file. Please do it manually using instructions from https://docs.sentry.io/platforms/javascript/guides/remix/manual-setup/", + ); + debug(e); + } + }, + ); + + if (!serverFileInstrumented && instrumentationFile) { + await traceStep( + "Update `start` script to import instrumentation file.", + async () => { + try { + await updateStartScript(instrumentationFile); + } catch (e) { + clack.log + .warn(`Could not automatically add Sentry initialization to server entry. + Please do it manually using instructions from https://docs.sentry.io/platforms/javascript/guides/remix/manual-setup/`); + debug(e); + } + }, + ); + } + + await traceStep("Instrument server `handleError`", async () => { + try { + await instrumentSentryOnEntryServer(isTS); + } catch (e) { + clack.log.warn(`Could not initialize Sentry on server entry. + Please do it manually using instructions from https://docs.sentry.io/platforms/javascript/guides/remix/manual-setup/`); + debug(e); + } + }); + + const shouldCreateExamplePage = await askShouldCreateExamplePage(); + + if (shouldCreateExamplePage) { + await traceStep("Create example page", async () => { + await createExamplePage({ + isTS, + selfHosted, + orgSlug: selectedProject.organization.slug, + projectId: selectedProject.id, + url: sentryUrl, + }); + }); + } + + await runPrettierIfInstalled({ cwd: undefined }); + + // Offer optional project-scoped MCP config for Sentry with org and project scope + await offerProjectScopedMcpConfig( + selectedProject.organization.slug, + selectedProject.slug, + ); + + clack.outro(` +${chalk.green( + "Sentry has been successfully configured for your Remix project.", +)} + +${chalk.cyan("You can now deploy your project to see Sentry in action.")} + +${chalk.cyan( + `To learn more about how to use Sentry with Remix, visit our documentation: +https://docs.sentry.io/platforms/javascript/guides/remix/`, +)}`); +} + +/** + * Offers to add a project-scoped MCP server configuration for the Sentry MCP. + * Supports Cursor, VS Code, and Claude Code. + */ diff --git a/packages/cli/src/lib/wizard/remix/sdk-example.ts b/packages/cli/src/lib/wizard/remix/sdk-example.ts new file mode 100644 index 0000000000..6ebaf06b5e --- /dev/null +++ b/packages/cli/src/lib/wizard/remix/sdk-example.ts @@ -0,0 +1,266 @@ +/** + * Writes the example page that throws a test error in a Remix app. + */ + +import { existsSync, mkdirSync, promises } from "node:fs"; +import path from "node:path"; +import { clack } from "../utils/clack/prompts.js"; + +/** + * Creates an example Remix page to test Sentry + */ +export async function createExamplePage(options: { + selfHosted: boolean; + orgSlug: string; + projectId: string; + url: string; + isTS: boolean; +}) { + const routesPath = "app/routes"; + + if (!existsSync(routesPath)) { + mkdirSync(routesPath, { recursive: true }); + } + + const exampleRoutePath = `app/routes/sentry-example-page.${ + options.isTS ? "ts" : "js" + }x`; + + if (existsSync(exampleRoutePath)) { + clack.log.warn( + `It seems like a sentry example page already exists (${path.basename( + exampleRoutePath, + )}). Skipping creation of example route.`, + ); + return; + } + + await promises.writeFile( + exampleRoutePath, + getSentryExamplePageContents(options), + ); + + clack.log.info(`Created sentry example page at ${exampleRoutePath}.`); +} + +export function getSentryExamplePageContents(options: { + selfHosted: boolean; + orgSlug: string; + projectId: string; + url: string; + isTS?: boolean; +}) { + const issuesPageLink = options.selfHosted + ? `${options.url}organizations/${options.orgSlug}/issues/?project=${options.projectId}` + : `https://${options.orgSlug}.sentry.io/issues/?project=${options.projectId}`; + + return `import * as Sentry from "@sentry/remix"; +import { useState, useEffect } from "react"; + +class SentryExampleFrontendError extends Error { + constructor(message${options.isTS ? ": string | undefined" : ""}) { + super(message); + this.name = "SentryExampleFrontendError"; + } +} + +export const meta = () => { + return [ + { title: "sentry-example-page" }, + ]; +} + +export default function SentryExamplePage() { + const [hasSentError, setHasSentError] = useState(false); + const [isConnected, setIsConnected] = useState(true); + + useEffect(() => { + async function checkConnectivity() { + const result = await Sentry.diagnoseSdkConnectivity(); + setIsConnected(result !== 'sentry-unreachable'); + } + checkConnectivity(); + }, [setIsConnected]); + + return ( +
+
+
+ + + +

+ 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 ? ( +

+ Sample error was 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.

+
+ ) : ( +
+ )} + +
+
+ + {/* Not for production use! We're just saving you from having to delete an extra CSS file ;) */} + +
+ ); +} + +const styles = \` + main { + display: flex; + min-height: 100vh; + flex-direction: column; + justify-content: center; + align-items: center; + gap: 16px; + padding: 16px; + font-family: system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", sans-serif; + } + + h1 { + padding: 0px 4px; + border-radius: 4px; + background-color: rgba(24, 20, 35, 0.03); + font-family: monospace; + font-size: 20px; + line-height: 1.2; + } + + p { + margin: 0; + font-size: 20px; + } + + a { + color: #6341F0; + text-decoration: underline; + cursor: pointer; + + @media (prefers-color-scheme: dark) { + color: #B3A1FF; + } + } + + button { + border-radius: 8px; + color: white; + cursor: pointer; + background-color: #553DB8; + border: none; + padding: 0; + margin-top: 4px; + + & > span { + display: inline-block; + padding: 12px 16px; + border-radius: inherit; + font-size: 20px; + font-weight: bold; + line-height: 1; + background-color: #7553FF; + border: 1px solid #553DB8; + transform: translateY(-4px); + } + + &:hover > span { + transform: translateY(-8px); + } + + &:active > span { + transform: translateY(0); + } + + &:disabled { + cursor: not-allowed; + opacity: 0.6; + + & > span { + transform: translateY(0); + border: none; + } + } + } + + .description { + text-align: center; + color: #6E6C75; + max-width: 500px; + line-height: 1.5; + font-size: 20px; + + @media (prefers-color-scheme: dark) { + color: #A49FB5; + } + } + + .flex-spacer { + flex: 1; + } + + .success { + padding: 12px 16px; + border-radius: 8px; + font-size: 20px; + line-height: 1; + background-color: #00F261; + border: 1px solid #00BF4D; + color: #181423; + } + + .success_placeholder { + height: 46px; + } + + .connectivity-error { + padding: 12px 16px; + background-color: #E50045; + border-radius: 8px; + width: 500px; + color: #FFFFFF; + border: 1px solid #A80033; + text-align: center; + margin: 0; + } + + .connectivity-error a { + color: #FFFFFF; + text-decoration: underline; + } +\`; +`; +} diff --git a/packages/cli/src/lib/wizard/remix/sdk-setup.ts b/packages/cli/src/lib/wizard/remix/sdk-setup.ts new file mode 100644 index 0000000000..ef128c2625 --- /dev/null +++ b/packages/cli/src/lib/wizard/remix/sdk-setup.ts @@ -0,0 +1,569 @@ +/** + * Setup steps of the Remix wizard: revealing the entry files, writing and + * importing the server instrumentation file, and updating the `build` and + * `start` scripts. + */ + +import { formatError } from "../../errors.js"; +import type { namedTypes as t } from "ast-types"; + +import type { Proxified, ProxifiedModule } from "magicast"; + +import { existsSync, promises, writeFileSync } from "node:fs"; +import path from "node:path"; +import { pathToFileURL } from "node:url"; +import { execSync } from "node:child_process"; + +import { clack } from "../utils/clack/prompts.js"; +import chalk from "chalk"; +import { gte, minVersion } from "semver"; + +import { + builders, + generateCode, + loadFile, + parseModule, + writeFile, +} from "magicast"; +import type { PackageDotJson } from "../utils/package-json.js"; +import { getPackageVersion } from "../utils/package-json.js"; +import { getDataCollectionSnippet } from "../utils/data-collection.js"; +import { + getAfterImportsInsertionIndex, + hasSentryContent, + serverHasInstrumentationImport, +} from "./utils.js"; +import { instrumentRoot } from "./codemods/root.js"; +import { instrumentHandleError } from "./codemods/handle-error.js"; +import { getPackageDotJson } from "../utils/clack/index.js"; +import { findCustomExpressServerImplementation } from "./codemods/express-server.js"; + +export type PartialRemixConfig = { + unstable_dev?: boolean; +}; + +const REMIX_CONFIG_FILE = "remix.config.js"; +const REMIX_REVEAL_COMMAND = "npx remix reveal"; + +export function runRemixReveal(isTS: boolean): void { + // Check if entry files already exist + const clientEntryFilename = `entry.client.${isTS ? "tsx" : "jsx"}`; + const serverEntryFilename = `entry.server.${isTS ? "tsx" : "jsx"}`; + + const clientEntryPath = path.join(process.cwd(), "app", clientEntryFilename); + const serverEntryPath = path.join(process.cwd(), "app", serverEntryFilename); + + if (existsSync(clientEntryPath) && existsSync(serverEntryPath)) { + clack.log.info( + `Found entry files ${chalk.cyan(clientEntryFilename)} and ${chalk.cyan( + serverEntryFilename, + )}.`, + ); + } else { + clack.log.info( + `Couldn't find entry files in your project. Trying to run ${chalk.cyan( + REMIX_REVEAL_COMMAND, + )}...`, + ); + + clack.log.info(execSync(REMIX_REVEAL_COMMAND).toString()); + } +} + +interface SdkAstOptions { + dsn: string; + tracesSampleRate?: number; + replaysSessionSampleRate?: number; + replaysOnErrorSampleRate?: number; + integrations?: Array; +} + +function getInitCallArgs( + dsn: string, + type: "client" | "server", + selectedFeatures: { + performance: boolean; + replay: boolean; + }, +) { + const initCallArgs: SdkAstOptions = { + dsn, + }; + + // Adding tracing sample rate for both client and server + if (selectedFeatures.performance) { + initCallArgs.tracesSampleRate = 1.0; + } + + // Adding integrations and replay options only for client + if ( + type === "client" && + (selectedFeatures.performance || selectedFeatures.replay) + ) { + initCallArgs.integrations = [] as Array; + + if (selectedFeatures.performance) { + initCallArgs.integrations.push( + builders.functionCall( + "browserTracingIntegration", + builders.raw("{ useEffect, useLocation, useMatches }"), + ), + ); + } + + if (selectedFeatures.replay) { + initCallArgs.integrations.push( + builders.functionCall("replayIntegration", { + maskAllText: true, + blockAllMedia: true, + }), + ); + + initCallArgs.replaysSessionSampleRate = 0.1; + initCallArgs.replaysOnErrorSampleRate = 1.0; + } + } + + return initCallArgs; +} + +/** + * Splices the PII-reducing `dataCollection` preset (with its comment block) + * into generated init code. Magicast cannot express comments inside an + * options object, so the block is inserted textually before the closing `})`. + */ +function withDataCollectionPreset( + generatedInitCode: string, + reduceDataCollection: boolean, +): string { + if (!reduceDataCollection) { + return generatedInitCode; + } + + return generatedInitCode.replace( + /\n\}\)$/, + `,\n${getDataCollectionSnippet(" ")}\n})`, + ); +} + +function insertClientInitCall( + dsn: string, + originalHooksMod: ProxifiedModule, + selectedFeatures: { + performance: boolean; + replay: boolean; + }, + reduceDataCollection: boolean, +): void { + const initCallArgs = getInitCallArgs(dsn, "client", selectedFeatures); + const initCall = builders.functionCall("init", initCallArgs); + + const generatedInitCode = withDataCollectionPreset( + generateCode(initCall).code, + reduceDataCollection, + ); + + const originalHooksModAST = originalHooksMod.$ast as t.Program; + const initCallInsertionIndex = + getAfterImportsInsertionIndex(originalHooksModAST); + + originalHooksModAST.body.splice( + initCallInsertionIndex, + 0, + // @ts-expect-error - string works here because the AST is proxified by magicast + generatedInitCode, + ); +} + +export function generateServerInstrumentationFile( + dsn: string, + selectedFeatures: { + performance: boolean; + replay: boolean; + }, + reduceDataCollection: boolean, +) { + // create an empty file named `instrument.server.mjs` + const instrumentationFile = "instrumentation.server.mjs"; + const instrumentationFileMod = parseModule(""); + + instrumentationFileMod.imports.$add({ + from: "@sentry/remix", + imported: "*", + local: "Sentry", + }); + + const initCallArgs = getInitCallArgs(dsn, "server", selectedFeatures); + const initCall = builders.functionCall("Sentry.init", initCallArgs); + + const generatedInitCode = withDataCollectionPreset( + generateCode(initCall).code, + reduceDataCollection, + ); + + const instrumentationFileModAST = instrumentationFileMod.$ast as t.Program; + + const initCallInsertionIndex = getAfterImportsInsertionIndex( + instrumentationFileModAST, + ); + + instrumentationFileModAST.body.splice( + initCallInsertionIndex, + 0, + // @ts-expect-error - string works here because the AST is proxified by magicast + generatedInitCode, + ); + + return { instrumentationFile, instrumentationFileMod }; +} + +export async function createServerInstrumentationFile( + dsn: string, + selectedFeatures: { + performance: boolean; + replay: boolean; + }, + reduceDataCollection: boolean, +) { + const { instrumentationFile, instrumentationFileMod } = + generateServerInstrumentationFile( + dsn, + selectedFeatures, + reduceDataCollection, + ); + + await writeFile(instrumentationFileMod.$ast, instrumentationFile); + + return instrumentationFile; +} + +export async function insertServerInstrumentationFile( + dsn: string, + selectedFeatures: { + performance: boolean; + replay: boolean; + }, + reduceDataCollection: boolean, +) { + const instrumentationFile = await createServerInstrumentationFile( + dsn, + selectedFeatures, + reduceDataCollection, + ); + + const expressServerPath = await findCustomExpressServerImplementation(); + + if (!expressServerPath) { + return false; + } + + const originalExpressServerMod = await loadFile(expressServerPath); + + if ( + serverHasInstrumentationImport( + expressServerPath, + originalExpressServerMod.$code, + ) + ) { + clack.log.warn( + `File ${chalk.cyan( + path.basename(expressServerPath), + )} already contains instrumentation import. +Skipping adding instrumentation functionality to ${chalk.cyan( + path.basename(expressServerPath), + )}.`, + ); + + return true; + } + + originalExpressServerMod.$code = `import './${instrumentationFile}';\n${originalExpressServerMod.$code}`; + + writeFileSync(expressServerPath, originalExpressServerMod.$code); + + return true; +} + +export function isRemixV2(packageJson: PackageDotJson): boolean { + const remixVersion = getPackageVersion("@remix-run/react", packageJson); + if (!remixVersion) { + return false; + } + + const minVer = minVersion(remixVersion); + + if (!minVer) { + return false; + } + + return gte(minVer, "2.0.0"); +} + +export async function loadRemixConfig(): Promise { + const configFilePath = path.join(process.cwd(), REMIX_CONFIG_FILE); + + try { + if (!existsSync(configFilePath)) { + return {}; + } + + const configUrl = pathToFileURL(configFilePath).href; + const remixConfigModule = (await import(configUrl)) as { + default?: PartialRemixConfig; + }; + + return remixConfigModule.default ?? {}; + } catch (e: unknown) { + clack.log.error(`Couldn't load ${REMIX_CONFIG_FILE}.`); + clack.log.info(chalk.dim(formatError(e))); + + return {}; + } +} + +export async function instrumentRootRoute(isTS?: boolean): Promise { + const rootFilename = `root.${isTS ? "tsx" : "jsx"}`; + + await instrumentRoot(rootFilename); + + clack.log.success( + `Successfully instrumented root route ${chalk.cyan(rootFilename)}.`, + ); +} + +export async function updateBuildScript(args: { + org: string; + project: string; + url?: string | undefined; + isHydrogen: boolean; +}): Promise { + const packageJson = await getPackageDotJson(); + + if (!packageJson.scripts) { + packageJson.scripts = {}; + } + + const buildCommand = args.isHydrogen + ? "shopify hydrogen build" + : "remix build"; + + const instrumentedBuildCommand = + `${buildCommand} --sourcemap && npx @sentry/remix --upload-sourcemaps --org ${args.org} --project ${args.project}` + + (args.url ? ` --url ${args.url}` : "") + + (args.isHydrogen ? " --buildPath ./dist" : ""); + + if (!packageJson.scripts["build"]) { + packageJson.scripts["build"] = instrumentedBuildCommand; + } else if (packageJson.scripts["build"].includes(buildCommand)) { + packageJson.scripts["build"] = packageJson.scripts["build"].replace( + buildCommand, + instrumentedBuildCommand, + ); + } else { + throw new Error( + "`build` script doesn't contain a known build command. Please update it manually.", + ); + } + + await promises.writeFile( + path.join(process.cwd(), "package.json"), + JSON.stringify(packageJson, null, 2), + ); + + clack.log.success( + `Successfully updated ${chalk.cyan("build")} script in ${chalk.cyan( + "package.json", + )} to generate and upload sourcemaps.`, + ); +} + +export function updateEntryClientMod( + originalEntryClientMod: ProxifiedModule, + dsn: string, + selectedFeatures: { + performance: boolean; + replay: boolean; + }, + reduceDataCollection: boolean, +): ProxifiedModule { + const imports = ["init"]; + if (selectedFeatures.replay) { + imports.push("replayIntegration"); + } + if (selectedFeatures.performance) { + imports.push("browserTracingIntegration"); + } + originalEntryClientMod.imports.$add({ + from: "@sentry/remix", + imported: imports.join(", "), + }); + + if (selectedFeatures.performance) { + originalEntryClientMod.imports.$add({ + from: "@remix-run/react", + imported: "useLocation", + local: "useLocation", + }); + + originalEntryClientMod.imports.$add({ + from: "@remix-run/react", + imported: "useMatches", + local: "useMatches", + }); + + originalEntryClientMod.imports.$add({ + from: "react", + imported: "useEffect", + local: "useEffect", + }); + } + + insertClientInitCall( + dsn, + originalEntryClientMod, + selectedFeatures, + reduceDataCollection, + ); + + return originalEntryClientMod; +} + +export async function initializeSentryOnEntryClient( + dsn: string, + isTS: boolean, + selectedFeatures: { + performance: boolean; + replay: boolean; + }, + reduceDataCollection: boolean, +): Promise { + const clientEntryFilename = `entry.client.${isTS ? "tsx" : "jsx"}`; + + const originalEntryClient = path.join( + process.cwd(), + "app", + clientEntryFilename, + ); + + const originalEntryClientMod = await loadFile(originalEntryClient); + + if (hasSentryContent(originalEntryClient, originalEntryClientMod.$code)) { + return; + } + + const updatedEntryClientMod = updateEntryClientMod( + originalEntryClientMod, + dsn, + selectedFeatures, + reduceDataCollection, + ); + + await writeFile( + updatedEntryClientMod.$ast, + path.join(process.cwd(), "app", clientEntryFilename), + ); + + clack.log.success( + `Successfully initialized Sentry on client entry point ${chalk.cyan( + clientEntryFilename, + )}`, + ); +} + +export async function updateStartScript(instrumentationFile: string) { + const packageJson = await getPackageDotJson(); + + if (!packageJson.scripts?.["start"]) { + throw new Error( + "Couldn't find a `start` script in your package.json. Please add one manually.", + ); + } + + if (packageJson.scripts["start"].includes("NODE_OPTIONS")) { + clack.log.warn( + `Found existing NODE_OPTIONS in ${chalk.cyan( + "start", + )} script. Skipping adding Sentry initialization.`, + ); + + return; + } + + if ( + !packageJson.scripts["start"].includes("remix-serve") && + // Adding a following empty space not to match a path that includes `node` + !packageJson.scripts["start"].includes("node ") + ) { + clack.log.warn( + `Found a ${chalk.cyan("start")} script that doesn't use ${chalk.cyan( + "remix-serve", + )} or ${chalk.cyan("node")}. Skipping adding Sentry initialization.`, + ); + + return; + } + + const startCommand = packageJson.scripts["start"]; + + packageJson.scripts["start"] = + `NODE_OPTIONS='--import ./${instrumentationFile}' ${startCommand}`; + + await promises.writeFile( + path.join(process.cwd(), "package.json"), + JSON.stringify(packageJson, null, 2), + ); + + clack.log.success( + `Successfully updated ${chalk.cyan("start")} script in ${chalk.cyan( + "package.json", + )} to include Sentry initialization on start.`, + ); +} + +export async function instrumentSentryOnEntryServer( + isTS: boolean, +): Promise { + const serverEntryFilename = `entry.server.${isTS ? "tsx" : "jsx"}`; + + const originalEntryServer = path.join( + process.cwd(), + "app", + serverEntryFilename, + ); + + const originalEntryServerMod = await loadFile(originalEntryServer); + + if (hasSentryContent(originalEntryServer, originalEntryServerMod.$code)) { + return; + } + + originalEntryServerMod.imports.$add({ + from: "@sentry/remix", + imported: "*", + local: "Sentry", + }); + + const handleErrorInstrumented = instrumentHandleError( + originalEntryServerMod, + serverEntryFilename, + ); + + if (handleErrorInstrumented) { + clack.log.success( + `Instrumented ${chalk.cyan("handleError")} in ${chalk.cyan( + serverEntryFilename, + )}`, + ); + } + + await writeFile( + originalEntryServerMod.$ast, + path.join(process.cwd(), "app", serverEntryFilename), + ); + + clack.log.success( + `Successfully initialized Sentry on server entry point ${chalk.cyan( + serverEntryFilename, + )}.`, + ); +} diff --git a/packages/cli/src/lib/wizard/remix/templates.ts b/packages/cli/src/lib/wizard/remix/templates.ts new file mode 100644 index 0000000000..5606bff3b4 --- /dev/null +++ b/packages/cli/src/lib/wizard/remix/templates.ts @@ -0,0 +1,15 @@ +/** + * Code templates the Remix codemods insert. + */ + +export const ERROR_BOUNDARY_TEMPLATE = `const ErrorBoundary = () => { + const error = useRouteError(); + captureRemixErrorBoundaryError(error); + return
Something went wrong
; +}; +`; + +export const HANDLE_ERROR_TEMPLATE = `const handleError = Sentry.wrapHandleErrorWithSentry((error, { request }) => { + // Custom handleError implementation +}); +`; diff --git a/packages/cli/src/lib/wizard/remix/utils.ts b/packages/cli/src/lib/wizard/remix/utils.ts new file mode 100644 index 0000000000..b602a374bc --- /dev/null +++ b/packages/cli/src/lib/wizard/remix/utils.ts @@ -0,0 +1,102 @@ +/** + * Helpers shared by the Remix wizard steps: detecting Sentry code, + * Hydrogen apps, and where to insert new statements. + */ + +import type { namedTypes as t } from "ast-types"; + +import path from "node:path"; + +import { clack } from "../utils/clack/prompts.js"; +import chalk from "chalk"; +import { + type PackageDotJson, + hasPackageInstalled, +} from "../utils/package-json.js"; + +export const POSSIBLE_SERVER_INSTRUMENTATION_PATHS = [ + "./instrumentation", + "./instrumentation.server", +]; + +export function hasSentryContent( + fileName: string, + fileContent: string, + expectedContent = "@sentry/remix", +): boolean { + const includesContent = fileContent.includes(expectedContent); + + if (includesContent) { + clack.log.warn( + `File ${chalk.cyan( + path.basename(fileName), + )} already contains ${expectedContent}. +Skipping adding Sentry functionality to ${chalk.cyan( + path.basename(fileName), + )}.`, + ); + } + + return includesContent; +} + +export function serverHasInstrumentationImport( + serverFileName: string, + serverFileContent: string, +): boolean { + const includesServerInstrumentationImport = + POSSIBLE_SERVER_INSTRUMENTATION_PATHS.some((path) => + serverFileContent.includes(path), + ); + + if (includesServerInstrumentationImport) { + clack.log.warn( + `File ${chalk.cyan( + path.basename(serverFileName), + )} already contains instrumentation import. +Skipping adding instrumentation functionality to ${chalk.cyan( + path.basename(serverFileName), + )}.`, + ); + } + + return includesServerInstrumentationImport; +} + +/** + * We want to insert the init call on top of the file, before any other imports. + */ +export function getBeforeImportsInsertionIndex( + originalHooksModAST: t.Program, +): number { + for (let x = 0; x < originalHooksModAST.body.length - 1; x++) { + const node = originalHooksModAST.body[x]; + if ( + node?.type === "ImportDeclaration" && + node.source.value === "@sentry/remix" + ) { + return x + 1; + } + } + + return 0; +} + +/** + * We want to insert the handleError function just after all imports + */ +export function getAfterImportsInsertionIndex( + originalEntryServerModAST: t.Program, +): number { + for (let x = originalEntryServerModAST.body.length - 1; x >= 0; x--) { + if (originalEntryServerModAST.body[x]?.type === "ImportDeclaration") { + return x + 1; + } + } + + return 0; +} + +export function isHydrogenApp(packageJson: PackageDotJson): boolean { + return hasPackageInstalled("@shopify/hydrogen", packageJson); +} diff --git a/packages/cli/src/lib/wizard/run.ts b/packages/cli/src/lib/wizard/run.ts index 8bd377980b..74b1a8881f 100644 --- a/packages/cli/src/lib/wizard/run.ts +++ b/packages/cli/src/lib/wizard/run.ts @@ -55,6 +55,20 @@ const WIZARD_RUNNERS: Partial> = { const { runNextjsWizard } = await import("./nextjs/nextjs-wizard.js"); await runNextjsWizard(options); }, + remix: async (options) => { + const { runRemixWizard } = await import("./remix/remix-wizard.js"); + await runRemixWizard(options); + }, + reactRouter: async (options) => { + const { runReactRouterWizard } = + await import("./react-router/react-router-wizard.js"); + await runReactRouterWizard(options); + }, + sveltekit: async (options) => { + const { runSvelteKitWizard } = + await import("./sveltekit/sveltekit-wizard.js"); + await runSvelteKitWizard(options); + }, }; /** What `sentry wizard` passes to {@link runWizard}. */ diff --git a/packages/cli/src/lib/wizard/sveltekit/sdk-example.ts b/packages/cli/src/lib/wizard/sveltekit/sdk-example.ts new file mode 100644 index 0000000000..7fcae593a3 --- /dev/null +++ b/packages/cli/src/lib/wizard/sveltekit/sdk-example.ts @@ -0,0 +1,63 @@ +/** + * Writes the example page and API route that throw a test error in a + * SvelteKit app. + */ + +import { existsSync, mkdirSync, promises } from "node:fs"; +import path from "node:path"; +import { clack } from "../utils/clack/prompts.js"; + +import type { PartialBackwardsForwardsCompatibleSvelteConfig } from "./sdk-setup/svelte-config.js"; +import { + getSentryExampleApiRoute, + getSentryExampleSveltePage, +} from "./templates.js"; + +/** + * Creates example page and API route to test Sentry + */ +export async function createExamplePage( + svelteConfig: PartialBackwardsForwardsCompatibleSvelteConfig, + projectProps: { + selfHosted: boolean; + url: string; + orgSlug: string; + projectId: string; + isUsingSvelte5: boolean; + }, +): Promise { + const routesDirectory = svelteConfig.kit?.files?.routes || "src/routes"; + const exampleRoutePath = path.resolve( + path.join(routesDirectory, "sentry-example-page"), + ); + + if (!existsSync(routesDirectory)) { + clack.log.warn( + `Couldn't find your routes directory. Creating it now: ${routesDirectory}`, + ); + mkdirSync(routesDirectory, { recursive: true }); + } + + if (!existsSync(exampleRoutePath)) { + mkdirSync(exampleRoutePath); + } else { + clack.log.warn( + `It seems like a sentry example page already exists (${path.basename( + exampleRoutePath, + )}). Skipping creation of example route.`, + ); + return; + } + + await promises.writeFile( + path.join(exampleRoutePath, "+page.svelte"), + getSentryExampleSveltePage({ + ...projectProps, + }), + ); + + await promises.writeFile( + path.join(exampleRoutePath, "+server.js"), + getSentryExampleApiRoute(), + ); +} diff --git a/packages/cli/src/lib/wizard/sveltekit/sdk-setup/setup.ts b/packages/cli/src/lib/wizard/sveltekit/sdk-setup/setup.ts new file mode 100644 index 0000000000..42269d7385 --- /dev/null +++ b/packages/cli/src/lib/wizard/sveltekit/sdk-setup/setup.ts @@ -0,0 +1,695 @@ +/** + * Creates or merges the SvelteKit hooks and `instrumentation.server` files + * that initialize the Sentry SDK. + */ + +import { promises } from "node:fs"; +import path from "node:path"; +import chalk from "chalk"; + +import { Sentry } from "../../telemetry.js"; + +import { clack } from "../../utils/clack/prompts.js"; +import type { ProxifiedModule } from "magicast"; +import { builders, generateCode, loadFile } from "magicast"; +import { + getClientHooksTemplate, + getInstrumentationServerTemplate, + getServerHooksTemplate, +} from "../templates.js"; +import { + featureSelectionPrompt, + isUsingTypeScript, + showCopyPasteInstructions, +} from "../../utils/clack/index.js"; +import { findFile, hasSentryContent } from "../../utils/ast-utils.js"; +import { getDataCollectionSnippet } from "../../utils/data-collection.js"; + +import recast from "recast"; +import type { namedTypes as t } from "ast-types"; +import { + enableTracingAndInstrumentation, + type PartialBackwardsForwardsCompatibleSvelteConfig, +} from "./svelte-config.js"; +import type { ProjectInfo } from "./types.js"; +import { modifyViteConfig } from "./vite.js"; +import { modifyAndRecordFail } from "./utils.js"; +import { debug } from "../../utils/debug.js"; + +export async function createOrMergeSvelteKitFiles( + projectInfo: ProjectInfo, + svelteConfig: PartialBackwardsForwardsCompatibleSvelteConfig, + setupForSvelteKitTracing: boolean, +): Promise { + const selectedFeatures = await featureSelectionPrompt([ + { + id: "performance", + prompt: `Do you want to enable ${chalk.bold( + "Tracing", + )} to track the performance of your application?`, + enabledHint: "recommended", + }, + { + id: "replay", + prompt: `Do you want to enable ${chalk.bold( + "Session Replay", + )} to get a video-like reproduction of errors during a user session?`, + enabledHint: "recommended, but increases bundle size", + }, + ] as const); + + const { clientHooksPath, serverHooksPath } = getHooksConfigDirs(svelteConfig); + + // full file paths with correct file ending (or undefined if not found) + const originalClientHooksFile = findFile(clientHooksPath); + const originalServerHooksFile = findFile(serverHooksPath); + const originalInstrumentationServerFile = findFile( + path.resolve(process.cwd(), "src", "instrumentation.server"), + ); + + const viteConfig = findFile(path.resolve(process.cwd(), "vite.config")); + + const fileEnding = isUsingTypeScript() ? "ts" : "js"; + + const { dsn, reduceDataCollection } = projectInfo; + + if (setupForSvelteKitTracing) { + await enableTracingAndInstrumentation( + svelteConfig, + selectedFeatures.performance, + ); + + try { + if (!originalInstrumentationServerFile) { + await createNewInstrumentationServerFile( + dsn, + selectedFeatures, + reduceDataCollection, + ); + } else { + await mergeInstrumentationServerFile( + originalInstrumentationServerFile, + dsn, + selectedFeatures, + reduceDataCollection, + ); + } + } catch (e) { + clack.log.warn( + `Failed to automatically set up ${chalk.cyan( + `instrumentation.server.${fileEnding}`, + )}.`, + ); + debug(e); + + await showCopyPasteInstructions({ + codeSnippet: getInstrumentationServerTemplate( + dsn, + selectedFeatures, + reduceDataCollection, + ), + filename: `instrumentation.server.${fileEnding}`, + }); + + Sentry.setTag("created-instrumentation-server", "fail"); + } + } + + Sentry.setTag( + "server-hooks-file-strategy", + originalServerHooksFile ? "merge" : "create", + ); + + if (!originalServerHooksFile) { + await createNewHooksFile( + `${serverHooksPath}.${fileEnding}`, + "server", + dsn, + selectedFeatures, + !setupForSvelteKitTracing, + reduceDataCollection, + ); + } else { + await mergeHooksFile( + originalServerHooksFile, + "server", + dsn, + selectedFeatures, + !setupForSvelteKitTracing, + reduceDataCollection, + ); + } + + Sentry.setTag( + "client-hooks-file-strategy", + originalClientHooksFile ? "merge" : "create", + ); + if (!originalClientHooksFile) { + await createNewHooksFile( + `${clientHooksPath}.${fileEnding}`, + "client", + dsn, + selectedFeatures, + true, + reduceDataCollection, + ); + } else { + await mergeHooksFile( + originalClientHooksFile, + "client", + dsn, + selectedFeatures, + true, + reduceDataCollection, + ); + } + + if (viteConfig) { + await modifyViteConfig(viteConfig, projectInfo); + } +} + +/** + * Attempts to read the svelte.config.js file to find the location of the hooks files. + * If users specified a custom location, we'll use that. Otherwise, we'll use the default. + */ +function getHooksConfigDirs( + svelteConfig: PartialBackwardsForwardsCompatibleSvelteConfig, +): { + clientHooksPath: string; + serverHooksPath: string; +} { + const relativeUserClientHooksPath = svelteConfig.kit?.files?.hooks?.client; + const relativeUserServerHooksPath = svelteConfig.kit?.files?.hooks?.server; + const userClientHooksPath = + relativeUserClientHooksPath && + path.resolve(process.cwd(), relativeUserClientHooksPath); + const userServerHooksPath = + relativeUserServerHooksPath && + path.resolve(process.cwd(), relativeUserServerHooksPath); + + const defaulHooksDir = path.resolve(process.cwd(), "src"); + const defaultClientHooksPath = path.resolve(defaulHooksDir, "hooks.client"); // file ending missing on purpose + const defaultServerHooksPath = path.resolve(defaulHooksDir, "hooks.server"); // same here + + return { + clientHooksPath: userClientHooksPath || defaultClientHooksPath, + serverHooksPath: userServerHooksPath || defaultServerHooksPath, + }; +} + +/** + * Reads the template, replaces the dsn placeholder with the actual dsn and writes the file to @param hooksFileDest + */ +// oxlint-disable-next-line max-params -- positional like the sentry-wizard original and its tests +async function createNewHooksFile( + hooksFileDest: string, + hooktype: "client" | "server", + dsn: string, + selectedFeatures: { + performance: boolean; + replay: boolean; + }, + setupForSvelteKitTracing: boolean, + reduceDataCollection: boolean, +): Promise { + const filledTemplate = + hooktype === "client" + ? getClientHooksTemplate(dsn, selectedFeatures, reduceDataCollection) + : getServerHooksTemplate( + dsn, + selectedFeatures, + setupForSvelteKitTracing, + reduceDataCollection, + ); + + await promises.mkdir(path.dirname(hooksFileDest), { recursive: true }); + await promises.writeFile(hooksFileDest, filledTemplate); + + clack.log.success(`Created ${hooksFileDest}`); + Sentry.setTag(`created-${hooktype}-hooks`, "success"); +} + +async function createNewInstrumentationServerFile( + dsn: string, + selectedFeatures: { + performance: boolean; + }, + reduceDataCollection: boolean, +): Promise { + const filledTemplate = getInstrumentationServerTemplate( + dsn, + selectedFeatures, + reduceDataCollection, + ); + + const fileEnding = isUsingTypeScript() ? "ts" : "js"; + + const instrumentationServerFile = path.resolve( + process.cwd(), + "src", + `instrumentation.server.${fileEnding}`, + ); + + await promises.mkdir(path.dirname(instrumentationServerFile), { + recursive: true, + }); + + await promises.writeFile(instrumentationServerFile, filledTemplate); + + clack.log.success( + `Created ${chalk.cyan(path.basename(instrumentationServerFile))}`, + ); + Sentry.setTag("created-instrumentation-server", "success"); +} + +/** + * Merges the users' hooks file with Sentry-related code. + * + * Both hooks: + * - add import * as Sentry + * - add Sentry.init + * - add handleError hook wrapper + * + * Additionally in Server hook: + * - add handle hook handler + */ +// oxlint-disable-next-line max-params -- positional like the sentry-wizard original and its tests +async function mergeHooksFile( + hooksFile: string, + hookType: "client" | "server", + dsn: string, + selectedFeatures: { + performance: boolean; + replay: boolean; + }, + includeSentryInit: boolean, + reduceDataCollection: boolean, +): Promise { + const originalHooksMod = await loadFile(hooksFile); + + const file: "server-hooks" | "client-hooks" = `${hookType}-hooks`; + + if (hasSentryContent(originalHooksMod.$ast as t.Program)) { + // We don't want to mess with files that already have Sentry content. + // Let's just bail out at this point. + clack.log.warn( + `File ${chalk.cyan( + path.basename(hooksFile), + )} already contains Sentry code. +Skipping adding Sentry functionality to.`, + ); + Sentry.setTag(`modified-${file}`, "fail"); + Sentry.setTag(`${file}-fail-reason`, "has-sentry-content"); + return; + } + + await modifyAndRecordFail( + () => + originalHooksMod.imports.$add({ + from: "@sentry/sveltekit", + imported: "*", + local: "Sentry", + }), + "import-injection", + file, + ); + + if (hookType === "client" || includeSentryInit) { + await modifyAndRecordFail( + () => { + if (hookType === "client") { + insertClientInitCall( + dsn, + originalHooksMod, + selectedFeatures, + reduceDataCollection, + ); + } else { + insertServerInitCall( + dsn, + originalHooksMod, + selectedFeatures, + reduceDataCollection, + ); + } + }, + "init-call-injection", + file, + ); + } + + await modifyAndRecordFail( + () => wrapHandleError(originalHooksMod), + "wrap-handle-error", + file, + ); + + if (hookType === "server") { + await modifyAndRecordFail( + () => wrapHandle(originalHooksMod), + "wrap-handle", + "server-hooks", + ); + } + + await modifyAndRecordFail( + async () => { + const modifiedCode = originalHooksMod.generate().code; + await promises.writeFile(hooksFile, modifiedCode); + }, + "write-file", + file, + ); + + clack.log.success(`Added Sentry code to ${hooksFile}`); + Sentry.setTag(`modified-${hookType}-hooks`, "success"); +} + +/** + * Merges the users' instrumentation.server file with Sentry-related code. + * + * Both hooks: + * - add import * as Sentry + * - add Sentry.init + * - add handleError hook wrapper + * + * Additionally in Server hook: + * - add handle hook handler + */ +async function mergeInstrumentationServerFile( + instrumentationServerFilePath: string, + dsn: string, + selectedFeatures: { + performance: boolean; + replay: boolean; + }, + reduceDataCollection: boolean, +): Promise { + const originalInstrumentationServerMod = await loadFile( + instrumentationServerFilePath, + ); + const filename = path.basename(instrumentationServerFilePath); + + if (hasSentryContent(originalInstrumentationServerMod.$ast as t.Program)) { + // We don't want to mess with files that already have Sentry content. + // Let's just bail out at this point. + clack.log.warn( + `File ${chalk.cyan(filename)} already contains Sentry code. +Skipping adding Sentry functionality to it.`, + ); + Sentry.setTag(`modified-instrumentation-server`, "fail"); + Sentry.setTag(`instrumentation-server-fail-reason`, "has-sentry-content"); + return; + } + + await modifyAndRecordFail( + () => + originalInstrumentationServerMod.imports.$add({ + from: "@sentry/sveltekit", + imported: "*", + local: "Sentry", + }), + "import-injection", + "instrumentation-server", + ); + + await modifyAndRecordFail( + () => { + insertServerInitCall( + dsn, + originalInstrumentationServerMod, + selectedFeatures, + reduceDataCollection, + ); + }, + "init-call-injection", + "instrumentation-server", + ); + + await modifyAndRecordFail( + async () => { + const modifiedCode = originalInstrumentationServerMod.generate().code; + await promises.writeFile(instrumentationServerFilePath, modifiedCode); + }, + "write-file", + "instrumentation-server", + ); + + clack.log.success(`Added Sentry.init code to ${chalk.cyan(filename)}`); + Sentry.setTag(`modified-instrumentation-server`, "success"); +} + +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/sveltekit/configuration/options/#dataCollection", + " // userInfo: false,", + " // httpBodies: [],", + " },", +].join("\n"); + +/** + * The active PII-reducing preset when the user opted in, the commented-out + * hint otherwise. Spliced into the generated `Sentry.init` code right before + * the closing `})`. + */ +function getDataCollectionInitCode(reduceDataCollection: boolean): string { + return reduceDataCollection + ? `\n${getDataCollectionSnippet(" ")}` + : DATA_COLLECTION_HINT; +} + +export function insertClientInitCall( + dsn: string, + originalHooksMod: ProxifiedModule, + selectedFeatures: { + performance: boolean; + replay: boolean; + }, + reduceDataCollection: boolean, +): void { + const initCallComment = ` + // If you don't want to use Session Replay, remove the \`Replay\` integration, + // \`replaysSessionSampleRate\` and \`replaysOnErrorSampleRate\` options.`; + + const initArgs: { + dsn: string; + tracesSampleRate?: number; + replaysSessionSampleRate?: number; + replaysOnErrorSampleRate?: number; + integrations?: string[]; + } = { + dsn, + }; + + if (selectedFeatures.performance) { + initArgs.tracesSampleRate = 1.0; + } + + if (selectedFeatures.replay) { + initArgs.replaysSessionSampleRate = 0.1; + initArgs.replaysOnErrorSampleRate = 1.0; + initArgs.integrations = [builders.functionCall("Sentry.replayIntegration")]; + } + + // This assignment of any values is fine because we're just creating a function call in magicast + const initCall = builders.functionCall("Sentry.init", initArgs); + + const generatedInitCode = generateCode(initCall).code; + const initCodeWithHint = generatedInitCode.replace( + /\n\}\)$/, + `,${getDataCollectionInitCode(reduceDataCollection)}\n})`, + ); + + const initCallWithComment = builders.raw( + `${initCallComment}\n${initCodeWithHint}`, + ); + + const originalHooksModAST = originalHooksMod.$ast as t.Program; + + const initCallInsertionIndex = getInitCallInsertionIndex(originalHooksModAST); + + originalHooksModAST.body.splice( + initCallInsertionIndex, + 0, + // @ts-expect-error - string works here because the AST is proxified by magicast + generateCode(initCallWithComment).code, + ); +} + +function insertServerInitCall( + dsn: string, + originalMod: ProxifiedModule, + selectedFeatures: { + performance: boolean; + }, + reduceDataCollection: boolean, +): void { + const initArgs: { + dsn: string; + tracesSampleRate?: number; + } = { + dsn, + }; + + if (selectedFeatures.performance) { + initArgs.tracesSampleRate = 1.0; + } + + // This assignment of any values is fine because we're just creating a function call in magicast + const initCall = builders.functionCall("Sentry.init", initArgs); + + const generatedInitCode = generateCode(initCall).code; + const initCodeWithHint = generatedInitCode.replace( + /\n\}\)$/, + `,${getDataCollectionInitCode(reduceDataCollection)}\n})`, + ); + + const originalModAST = originalMod.$ast as t.Program; + + const initCallInsertionIndex = getInitCallInsertionIndex(originalModAST); + + originalModAST.body.splice( + initCallInsertionIndex, + 0, + // @ts-expect-error - string works here because the AST is proxified by magicast + initCodeWithHint, + ); +} + +function wrapHandleError(mod: ProxifiedModule): void { + const modAst = mod.exports.$ast as t.Program; + const namedExports = modAst.body.filter( + (node): node is t.ExportNamedDeclaration => + node.type === "ExportNamedDeclaration", + ); + + let foundHandleError = false as boolean; + + namedExports.forEach((modExport) => { + const declaration = modExport.declaration; + if (!declaration) { + return; + } + if (declaration.type === "FunctionDeclaration") { + if (declaration.id?.name !== "handleError") { + return; + } + foundHandleError = true; + const userCode = recast.print(declaration).code; + mod.exports["handleError"] = builders.raw( + `Sentry.handleErrorWithSentry(${userCode.replace( + "handleError", + "_handleError", + )})`, + ); + // because magicast doesn't overwrite the original function export, we need to remove it manually + modAst.body = modAst.body.filter((node) => node !== modExport); + } else if (declaration.type === "VariableDeclaration") { + const declarations = declaration.declarations; + declarations.forEach((declaration) => { + if ( + declaration.type !== "VariableDeclarator" || + declaration.id.type !== "Identifier" || + declaration.id.name !== "handleError" + ) { + return; + } + foundHandleError = true; + const userCode = declaration.init; + const stringifiedUserCode = userCode ? recast.print(userCode).code : ""; + // @ts-expect-error - we can just place a string here, magicast will convert it to a node + declaration.init = `Sentry.handleErrorWithSentry(${stringifiedUserCode})`; + }); + } + }); + + if (!foundHandleError) { + mod.exports["handleError"] = builders.functionCall( + "Sentry.handleErrorWithSentry", + ); + } +} + +function wrapHandle(mod: ProxifiedModule): void { + const modAst = mod.exports.$ast as t.Program; + const namedExports = modAst.body.filter( + (node): node is t.ExportNamedDeclaration => + node.type === "ExportNamedDeclaration", + ); + + let foundHandle = false as boolean; + + namedExports.forEach((modExport) => { + const declaration = modExport.declaration; + if (!declaration) { + return; + } + if (declaration.type === "FunctionDeclaration") { + if (declaration.id?.name !== "handle") { + return; + } + foundHandle = true; + const userCode = recast.print(declaration).code; + mod.exports["handle"] = builders.raw( + `sequence(Sentry.sentryHandle(), ${userCode.replace( + "handle", + "_handle", + )})`, + ); + // because of an issue with magicast, we need to remove the original export + modAst.body = modAst.body.filter((node) => node !== modExport); + } else if (declaration.type === "VariableDeclaration") { + const declarations = declaration.declarations; + declarations.forEach((declaration) => { + if ( + declaration.type !== "VariableDeclarator" || + declaration.id.type !== "Identifier" || + (declaration.id.name && declaration.id.name !== "handle") + ) { + return; + } + const userCode = declaration.init; + const stringifiedUserCode = userCode ? recast.print(userCode).code : ""; + // @ts-expect-error - we can just place a string here, magicast will convert it to a node + declaration.init = `sequence(Sentry.sentryHandle(), ${stringifiedUserCode})`; + foundHandle = true; + }); + } + }); + + if (!foundHandle) { + // can't use builders.functionCall here because it doesn't yet + // support member expressions (Sentry.sentryHandle()) in args + mod.exports["handle"] = builders.raw("sequence(Sentry.sentryHandle())"); + } + + try { + mod.imports.$add({ + from: "@sveltejs/kit/hooks", + imported: "sequence", + local: "sequence", + }); + } catch (error) { + // It's possible sequence is already imported. in this case, magicast throws but that's fine. + debug(error); + } +} + +/** + * We want to insert the init call on top of the file but after all import statements + */ +function getInitCallInsertionIndex(originalModAST: t.Program): number { + // We need to deep-copy here because reverse mutates in place + const copiedBodyNodes = [...originalModAST.body]; + const lastImportDeclaration = copiedBodyNodes + .reverse() + .find((node) => node.type === "ImportDeclaration"); + + const initCallInsertionIndex = lastImportDeclaration + ? originalModAST.body.indexOf(lastImportDeclaration) + 1 + : 0; + return initCallInsertionIndex; +} diff --git a/packages/cli/src/lib/wizard/sveltekit/sdk-setup/svelte-config.ts b/packages/cli/src/lib/wizard/sveltekit/sdk-setup/svelte-config.ts new file mode 100644 index 0000000000..46437b7319 --- /dev/null +++ b/packages/cli/src/lib/wizard/sveltekit/sdk-setup/svelte-config.ts @@ -0,0 +1,397 @@ +/** + * Reads `svelte.config.js` and turns on SvelteKit's native tracing and + * instrumentation in it. + */ + +import { formatError } from "../../../errors.js"; +import { reportCliError } from "../../../error-reporting.js"; +import { existsSync, promises } from "node:fs"; +import path from "node:path"; +import { pathToFileURL } from "node:url"; +import chalk from "chalk"; +import recast from "recast"; +import type { namedTypes as t } from "ast-types"; + +import { clack } from "../../utils/clack/prompts.js"; +import { + makeCodeSnippet, + showCopyPasteInstructions, +} from "../../utils/clack/index.js"; +import { generateCode, parseModule, type ProxifiedModule } from "magicast"; +import { debug } from "../../utils/debug.js"; + +const SVELTE_CONFIG_FILE = "svelte.config.js"; + +const b = recast.types.builders; + +export type PartialBackwardsForwardsCompatibleSvelteConfig = { + kit?: { + files?: { + hooks?: { + client?: string; + server?: string; + }; + routes?: string; + }; + experimental?: { + tracing?: { + server?: boolean; + }; + instrumentation?: { + server?: boolean; + }; + }; + }; +}; + +export async function loadSvelteConfig(): Promise { + const configFilePath = path.join(process.cwd(), SVELTE_CONFIG_FILE); + + try { + if (!existsSync(configFilePath)) { + return {}; + } + + const configUrl = pathToFileURL(configFilePath).href; + const svelteConfigModule = (await import(configUrl)) as { + default?: PartialBackwardsForwardsCompatibleSvelteConfig; + }; + + return svelteConfigModule.default ?? {}; + } catch (e: unknown) { + clack.log.error(`Couldn't load ${chalk.cyan(SVELTE_CONFIG_FILE)}. +Are you running this wizard from the root of your SvelteKit project?`); + clack.log.info(chalk.dim(formatError(e))); + + return {}; + } +} + +export async function enableTracingAndInstrumentation( + originalSvelteConfig: PartialBackwardsForwardsCompatibleSvelteConfig, + enableTracing: boolean, +) { + const hasTracingEnabled = originalSvelteConfig.kit?.experimental?.tracing; + const hasInstrumentationEnabled = + originalSvelteConfig.kit?.experimental?.instrumentation; + + if (hasTracingEnabled && hasInstrumentationEnabled) { + clack.log.info("Tracing and instrumentation are already enabled."); + return; + } + + if (hasTracingEnabled || hasInstrumentationEnabled) { + clack.log.info( + "Tracing and instrumentation are partially enabled. Make sure both options are enabled.", + ); + await showFallbackConfigSnippet(); + return; + } + try { + const configPath = path.join(process.cwd(), SVELTE_CONFIG_FILE); + const svelteConfigContent = await promises.readFile(configPath, "utf-8"); + + const { error, result } = _enableTracingAndInstrumentationInConfig( + svelteConfigContent, + enableTracing, + ); + + if (error) { + clack.log.warning( + "Failed to automatically enable SvelteKit tracing and instrumentation.", + ); + debug(error); + reportCliError(error); + await showFallbackConfigSnippet(); + return; + } + + if (result) { + await promises.writeFile(configPath, result); + } + + clack.log.success( + `Enabled tracing and instrumentation in ${chalk.cyan( + SVELTE_CONFIG_FILE, + )}`, + ); + } catch (e) { + clack.log.error( + `Failed to enable tracing and instrumentation in ${chalk.cyan( + SVELTE_CONFIG_FILE, + )}.`, + ); + debug(e); + reportCliError( + new Error( + `Failed to enable tracing and instrumentation in ${SVELTE_CONFIG_FILE}`, + ), + ); + await showFallbackConfigSnippet(); + return; + } +} + +export function _enableTracingAndInstrumentationInConfig( + config: string, + enableTracing: boolean, +): { + result?: string; + error?: string; +} { + let svelteConfig: ProxifiedModule; + try { + svelteConfig = parseModule(config); + } catch (e) { + // The caller shows the error and falls back to copy-paste instructions. + debug(e); + return { + error: "Failed to parse Svelte config", + }; + } + + let configObject: t.ObjectExpression | undefined = undefined; + + // Cases to handle for finding the config object: + // 1. default export is named object + // 2. default export is in-place object + // 3. default export is an identifier, so look up the variable declaration + recast.visit(svelteConfig.$ast, { + visitExportDefaultDeclaration(path) { + const exportDeclarationNode = path.node; + if ( + exportDeclarationNode.declaration.type === "AssignmentExpression" && + exportDeclarationNode.declaration.right.type === "ObjectExpression" + ) { + configObject = exportDeclarationNode.declaration.right; + return false; + } + + if (exportDeclarationNode.declaration.type === "ObjectExpression") { + configObject = exportDeclarationNode.declaration; + return false; + } + + if (exportDeclarationNode.declaration.type === "Identifier") { + const identifierName = exportDeclarationNode.declaration.name; + recast.visit(svelteConfig.$ast, { + visitVariableDeclarator(path) { + if ( + path.node.id.type === "Identifier" && + path.node.id.name === identifierName && + path.node.init?.type === "ObjectExpression" + ) { + configObject = path.node.init; + return false; + } + + this.traverse(path); + return undefined; + }, + }); + } + + this.traverse(path); + return undefined; + }, + }); + + if (!_isValidConfigObject(configObject)) { + return { + error: "Couldn't find the config object", + }; + } + + // This type cast is safe. For some reason, TS still assumes that `configObject` + // is `undefined` so we have to tell it that it's not (see check above) + const validatedConfigObject = + configObject as recast.types.namedTypes.ObjectExpression; + + const kitProp = validatedConfigObject.properties.find( + (prop) => + prop.type === "ObjectProperty" && + prop.key.type === "Identifier" && + prop.key.name === "kit", + ); + + if (kitProp?.type !== "ObjectProperty") { + return { + error: "Couldn't find the `kit` property", + }; + } + + if (kitProp.value.type !== "ObjectExpression") { + return { + error: `\`kit\` property has unexpected type: ${kitProp.value.type}`, + }; + } + + // 1. find or add `kit.experimental` property + // type-cast because TS can't infer the type in `.find` :( + const kitExperimentalProp = kitProp.value.properties.find( + (prop) => + prop.type === "ObjectProperty" && + prop.key.type === "Identifier" && + prop.key.name === "experimental", + ) as t.ObjectProperty | undefined; + + let experimentalObject: t.ObjectExpression; + + if (kitExperimentalProp) { + if (kitExperimentalProp.value.type !== "ObjectExpression") { + return { + error: `Property \`kit.experimental\` has unexpected type: ${kitExperimentalProp.value.type}`, + }; + } + + experimentalObject = kitExperimentalProp.value; + } else { + experimentalObject = b.objectExpression([]); + kitProp.value.properties.push( + b.objectProperty(b.identifier("experimental"), experimentalObject), + ); + } + + // 2. find or add `kit.experimental.tracing` property + // find or add `kit.experimental.instrumentation` property + const kitExperimentalTraingProp = experimentalObject.properties.find( + (prop) => + prop.type === "ObjectProperty" && + prop.key.type === "Identifier" && + prop.key.name === "tracing", + ) as t.ObjectProperty | undefined; + + const kitExperimentalInstrumentationProp = experimentalObject.properties.find( + (prop) => + prop.type === "ObjectProperty" && + prop.key.type === "Identifier" && + prop.key.name === "instrumentation", + ) as t.ObjectProperty | undefined; + + let experimentalTracingObject: t.ObjectExpression; + let experimentalInstrumentationObject: t.ObjectExpression; + + if (kitExperimentalTraingProp) { + if (kitExperimentalTraingProp.value.type !== "ObjectExpression") { + return { + error: `Property \`kit.experimental.tracing\` has unexpected type: ${kitExperimentalTraingProp.value.type}`, + }; + } + + experimentalTracingObject = kitExperimentalTraingProp.value; + } else { + experimentalTracingObject = b.objectExpression([]); + experimentalObject.properties.push( + b.objectProperty(b.identifier("tracing"), experimentalTracingObject), + ); + } + + if (kitExperimentalInstrumentationProp) { + if (kitExperimentalInstrumentationProp.value.type !== "ObjectExpression") { + return { + error: `Property \`kit.experimental.instrumentation\` has unexpected type: ${kitExperimentalInstrumentationProp.value.type}`, + }; + } + + experimentalInstrumentationObject = + kitExperimentalInstrumentationProp.value; + } else { + experimentalInstrumentationObject = b.objectExpression([]); + experimentalObject.properties.push( + b.objectProperty( + b.identifier("instrumentation"), + experimentalInstrumentationObject, + ), + ); + } + + // 3. find or add `kit.experimental.tracing.server` property + // find or add `kit.experimental.instrumentation.server` property + const kitExperimentalTracingSeverProp = + experimentalTracingObject.properties.find( + (prop) => + prop.type === "ObjectProperty" && + prop.key.type === "Identifier" && + prop.key.name === "server", + ) as t.ObjectProperty | undefined; + + const kitExperimentalInstrumentationSeverProp = + experimentalInstrumentationObject.properties.find( + (prop) => + prop.type === "ObjectProperty" && + prop.key.type === "Identifier" && + prop.key.name === "server", + ) as t.ObjectProperty | undefined; + + if (kitExperimentalTracingSeverProp) { + if (kitExperimentalTracingSeverProp.value.type !== "BooleanLiteral") { + return { + error: `Property \`kit.experimental.tracing.server\` has unexpected type: ${kitExperimentalTracingSeverProp.value.type}`, + }; + } + + kitExperimentalTracingSeverProp.value = b.booleanLiteral(enableTracing); + } else { + experimentalTracingObject.properties.push( + b.objectProperty(b.identifier("server"), b.booleanLiteral(enableTracing)), + ); + } + + if (kitExperimentalInstrumentationSeverProp) { + if ( + kitExperimentalInstrumentationSeverProp.value.type !== "BooleanLiteral" + ) { + return { + error: `Property \`kit.experimental.instrumentation.server\` has unexpected type: ${kitExperimentalInstrumentationSeverProp.value.type}`, + }; + } + kitExperimentalInstrumentationSeverProp.value = b.booleanLiteral(true); + } else { + experimentalInstrumentationObject.properties.push( + b.objectProperty(b.identifier("server"), b.booleanLiteral(true)), + ); + } + + try { + return { + result: generateCode(svelteConfig).code, + }; + } catch (e) { + debug(e); + return { + error: "Failed to generate code for Svelte config", + }; + } +} + +function _isValidConfigObject( + o: t.ObjectExpression | undefined, +): o is t.ObjectExpression { + return !!o; +} + +async function showFallbackConfigSnippet(): Promise { + const codeSnippet = makeCodeSnippet(true, (unchanged, plus) => + unchanged(`const config = { +preprocess: vitePreprocess(), + +kit: { + adapter: adapter(), + ${plus(`experimental: { + instrumentation: { + server: true, + }, + tracing: { + server: true, + }, + },`)} +}, +}; +`), + ); + + await showCopyPasteInstructions({ + filename: "svelte.config.js", + codeSnippet, + }); +} diff --git a/packages/cli/src/lib/wizard/sveltekit/sdk-setup/types.ts b/packages/cli/src/lib/wizard/sveltekit/sdk-setup/types.ts new file mode 100644 index 0000000000..ddf6fcb2b9 --- /dev/null +++ b/packages/cli/src/lib/wizard/sveltekit/sdk-setup/types.ts @@ -0,0 +1,15 @@ +/** + * Types shared by the SvelteKit setup steps. + */ + +export type ProjectInfo = { + dsn: string; + org: string; + project: string; + selfHosted: boolean; + url: string; + /** Module `sentrySvelteKit` is imported from; depends on the installed SDK major. */ + vitePluginImportPath: string; + /** Whether to write the PII-reducing `dataCollection` preset into `Sentry.init` (SDK v11+). */ + reduceDataCollection: boolean; +}; diff --git a/packages/cli/src/lib/wizard/sveltekit/sdk-setup/utils.ts b/packages/cli/src/lib/wizard/sveltekit/sdk-setup/utils.ts new file mode 100644 index 0000000000..ee2f4b9737 --- /dev/null +++ b/packages/cli/src/lib/wizard/sveltekit/sdk-setup/utils.ts @@ -0,0 +1,29 @@ +/** + * Runs a SvelteKit setup step as a telemetry step and tags why it failed. + */ + +import { traceStep } from "../../telemetry.js"; +import { Sentry } from "../../telemetry.js"; + +/** + * Applies the @param modifyCallback and records Sentry tags if the call failed. + * In case of a failure, a tag is set with @param reason as a fail reason + * and the error is rethrown. + */ +export async function modifyAndRecordFail( + modifyCallback: () => T | Promise, + reason: string, + fileType: + | "server-hooks" + | "client-hooks" + | "vite-cfg" + | "instrumentation-server", +): Promise { + try { + await traceStep(`${fileType}-${reason}`, modifyCallback); + } catch (e) { + Sentry.setTag(`modified-${fileType}`, "fail"); + Sentry.setTag(`${fileType}-mod-fail-reason`, reason); + throw e; + } +} diff --git a/packages/cli/src/lib/wizard/sveltekit/sdk-setup/vite.ts b/packages/cli/src/lib/wizard/sveltekit/sdk-setup/vite.ts new file mode 100644 index 0000000000..9fd5924f11 --- /dev/null +++ b/packages/cli/src/lib/wizard/sveltekit/sdk-setup/vite.ts @@ -0,0 +1,156 @@ +/** + * Adds the Sentry SvelteKit Vite plugin to `vite.config.(js|ts)`. + */ + +import { reportCliError } from "../../../error-reporting.js"; +import { Sentry } from "../../telemetry.js"; +import { promises } from "node:fs"; +import path from "node:path"; +import chalk from "chalk"; + +import { clack } from "../../utils/clack/prompts.js"; +import { generateCode, parseModule } from "magicast"; +import { addVitePlugin } from "magicast/helpers"; + +import type { namedTypes as t } from "ast-types"; + +import { + hasSentryContent, + preserveTrailingNewline, +} from "../../utils/ast-utils.js"; +import { debug } from "../../utils/debug.js"; +import { abortIfCancelled } from "../../utils/clack/index.js"; +import type { ProjectInfo } from "./types.js"; +import { modifyAndRecordFail } from "./utils.js"; + +export async function modifyViteConfig( + viteConfigPath: string, + projectInfo: ProjectInfo, +): Promise { + const viteConfigContent = ( + await promises.readFile(viteConfigPath, "utf-8") + ).toString(); + + const { org, project, url, selfHosted, vitePluginImportPath } = projectInfo; + + const prettyViteConfigFilename = chalk.cyan(path.basename(viteConfigPath)); + + try { + const viteModule = parseModule(viteConfigContent); + + if (hasSentryContent(viteModule.$ast as t.Program)) { + clack.log.warn( + `File ${prettyViteConfigFilename} already contains Sentry code. +Skipping adding Sentry functionality to.`, + ); + Sentry.setTag(`modified-vite-cfg`, "fail"); + Sentry.setTag(`vite-cfg-fail-reason`, "has-sentry-content"); + return; + } + + await modifyAndRecordFail( + () => + addVitePlugin(viteModule, { + imported: "sentrySvelteKit", + from: vitePluginImportPath, + constructor: "sentrySvelteKit", + options: { + org, + project, + ...(selfHosted && { sentryUrl: url }), + }, + index: 0, + }), + "add-vite-plugin", + "vite-cfg", + ); + + await modifyAndRecordFail( + async () => { + const code = preserveTrailingNewline( + viteConfigContent, + generateCode(viteModule.$ast).code, + ); + await promises.writeFile(viteConfigPath, code); + }, + "write-file", + "vite-cfg", + ); + } catch (e) { + debug(e); + await showFallbackViteCopyPasteSnippet( + viteConfigPath, + getViteConfigCodeSnippet( + org, + project, + selfHosted, + url, + vitePluginImportPath, + ), + ); + reportCliError(new Error("Sveltekit Vite Config Modification Fail")); + } + + clack.log.success(`Added Sentry code to ${prettyViteConfigFilename}`); + Sentry.setTag(`modified-vite-cfg`, "success"); +} + +async function showFallbackViteCopyPasteSnippet( + viteConfigPath: string, + codeSnippet: string, +) { + const viteConfigFilename = path.basename(viteConfigPath); + + clack.log.warning( + `Couldn't automatically modify your ${chalk.cyan(viteConfigFilename)} +${chalk.dim(`This sometimes happens when we encounter more complex vite configs. +It may not seem like it but sometimes our magical powers are limited ;)`)}`, + ); + + clack.log.info("But don't worry - it's super easy to do this yourself!"); + + clack.log.step( + `Add the following code to your ${chalk.cyan(viteConfigFilename)}:`, + ); + + // Printed outside clack's gutter for easier copy/pasting + clack.rawOutput(codeSnippet); + + await abortIfCancelled( + clack.select({ + message: "Did you copy the snippet above?", + options: [ + { label: "Yes!", value: true, hint: "Great, that's already it!" }, + ], + initialValue: true, + }), + ); +} + +const getViteConfigCodeSnippet = ( + org: string, + project: string, + selfHosted: boolean, + url: string, + vitePluginImportPath: string, +) => + chalk.gray(` +import { sveltekit } from '@sveltejs/kit/vite'; +import { defineConfig } from 'vite'; +${chalk.greenBright( + `import { sentrySvelteKit } from '${vitePluginImportPath}'`, +)} + +export default defineConfig({ + plugins: [ + // Make sure \`sentrySvelteKit\` is registered before \`sveltekit\` + ${chalk.greenBright(`sentrySvelteKit({ + org: '${org}', + project: '${project}',${ + selfHosted ? `\n sentryUrl: '${url}',` : "" + } + }),`)} + sveltekit(), + ] +}); +`); diff --git a/packages/cli/src/lib/wizard/sveltekit/sveltekit-wizard.ts b/packages/cli/src/lib/wizard/sveltekit/sveltekit-wizard.ts new file mode 100644 index 0000000000..58ed06cf04 --- /dev/null +++ b/packages/cli/src/lib/wizard/sveltekit/sveltekit-wizard.ts @@ -0,0 +1,299 @@ +/** + * The SvelteKit setup wizard: installs `@sentry/sveltekit`, sets up the + * hooks and instrumentation files and the Vite plugin, and optionally adds + * an example page. + */ + +import { formatError } from "../../errors.js"; +import { reportCliError } from "../../error-reporting.js"; +import { clack } from "../utils/clack/prompts.js"; +import chalk from "chalk"; + +import { Sentry } from "../telemetry.js"; + +import { traceStep, withTelemetry } from "../telemetry.js"; +import { + abort, + abortIfCancelled, + addDotEnvSentryBuildPluginFile, + askShouldCreateExamplePage, + confirmContinueIfNoOrDirtyGitRepo, + ensurePackageIsInstalled, + getOrAskForProjectData, + getPackageDotJson, + getPackageManager, + installPackage, + printSdkV11MigrationGuideIfOutdated, + printWelcome, + runPrettierIfInstalled, +} from "../utils/clack/index.js"; +import { + askShouldReduceDataCollection, + sdkSupportsDataCollection, +} from "../utils/data-collection.js"; +import { + getPackageVersion, + hasPackageInstalled, +} from "../utils/package-json.js"; +import { NPM } from "../utils/package-manager.js"; +import type { WizardOptions } from "../utils/types.js"; +import { offerProjectScopedMcpConfig } from "../utils/clack/mcp-config.js"; +import { createExamplePage } from "./sdk-example.js"; +import { createOrMergeSvelteKitFiles } from "./sdk-setup/setup.js"; +import { loadSvelteConfig } from "./sdk-setup/svelte-config.js"; +import { + getKitVersionBucket, + getSvelteVersionBucket, + SENTRY_SVELTEKIT_SDK_RANGE, + getSentrySvelteKitVitePluginImportPath, +} from "./utils.js"; +import { abortIfSpotlightNotSupported } from "../utils/abort-if-sportlight-not-supported.js"; +import { warnIfNodeVersionUnsupportedBySdkV11 } from "../utils/node-version.js"; + +export async function runSvelteKitWizard( + options: WizardOptions, +): Promise { + return await withTelemetry( + { + enabled: options.telemetryEnabled, + integration: "sveltekit", + wizardOptions: options, + }, + () => runSvelteKitWizardWithTelemetry(options), + ); +} + +export async function runSvelteKitWizardWithTelemetry( + options: WizardOptions, +): Promise { + const { promoCode, telemetryEnabled, forceInstall } = options; + + printWelcome({ + wizardName: "Sentry SvelteKit Wizard", + promoCode, + telemetryEnabled, + }); + + warnIfNodeVersionUnsupportedBySdkV11(); + + await confirmContinueIfNoOrDirtyGitRepo({ + ignoreGitChanges: options.ignoreGitChanges, + cwd: undefined, + }); + + const packageJson = await getPackageDotJson(); + + await ensurePackageIsInstalled(packageJson, "@sveltejs/kit", "Sveltekit"); + + const kitVersion = getPackageVersion("@sveltejs/kit", packageJson); + const kitVersionBucket = getKitVersionBucket(kitVersion); + Sentry.setTag("sveltekit-version", kitVersionBucket); + + if (kitVersionBucket === "0.x") { + clack.log.warn( + "It seems you're using a SvelteKit version <1.0.0 which is not supported by Sentry.\nWe recommend upgrading to the latest 1.x version before you continue.", + ); + const shouldContinue = await abortIfCancelled( + clack.select({ + message: "Do you want to continue anyway?", + options: [ + { + label: "Yes, continue", + hint: "The SDK might not work correctly", + value: true, + }, + { label: "No, I'll upgrade first", value: false }, + ], + }), + ); + if (!shouldContinue) { + await abort("Exiting Wizard", 0); + return; + } + } + + let setupForSvelteKitTracing = kitVersionBucket === ">=2.31.0"; + + if (kitVersionBucket !== ">=2.31.0") { + clack.log.warn( + `It seems you're using a SvelteKit version ${chalk.cyan( + "<2.31.0", + )} (detected ${chalk.cyan(kitVersion ?? "unknown")}). + +We recommend upgrading SvelteKit to version ${chalk.cyan( + ">=2.31.0", + )} to use SvelteKit's builtin observability: +${chalk.cyan("https://svelte.dev/docs/kit/observability")} + +Sentry works best with SvelteKit versions ${chalk.cyan(">=2.31.0")}. + +If you prefer, you can stay on your current version and use the Sentry SDK +without SvelteKit's builtin observability.`, + ); + + const decision = await abortIfCancelled( + clack.select({ + message: "Do you want to continue anyway?", + options: [ + { + label: "No, I'll upgrade SvelteKit first", + hint: "Recommended", + value: "exit-to-upgrade", + }, + { + label: "I'm already on SvelteKit >=2.31.0", + hint: "Sorry, my bad!", + value: "install-with-kit-tracing", + }, + { + label: "Yes, continue", + hint: "No Problem!", + value: "install-without-kit-tracing", + }, + ], + }), + ); + + if (decision === "install-with-kit-tracing") { + setupForSvelteKitTracing = true; + } + + if (decision === "exit-to-upgrade") { + await abort("Exiting Wizard", 0); + return; + } + } + + const svelteVersionBucket = getSvelteVersionBucket( + getPackageVersion("svelte", packageJson), + ); + Sentry.setTag("svelte-version", svelteVersionBucket); + + const projectData = await getOrAskForProjectData( + options, + "javascript-sveltekit", + ); + + if (projectData.spotlight) { + return await abortIfSpotlightNotSupported("SvelteKit"); + } + + const { selectedProject, selfHosted, sentryUrl, authToken } = projectData; + + const sdkAlreadyInstalled = hasPackageInstalled( + "@sentry/sveltekit", + packageJson, + ); + Sentry.setTag("sdk-already-installed", sdkAlreadyInstalled); + + printSdkV11MigrationGuideIfOutdated("@sentry/sveltekit", packageJson); + + await installPackage({ + packageName: `@sentry/sveltekit@${SENTRY_SVELTEKIT_SDK_RANGE}`, + packageNameDisplayLabel: "@sentry/sveltekit", + alreadyInstalled: sdkAlreadyInstalled, + forceInstall, + }); + + // The install may have been skipped (user declined the update prompt), so + // re-read package.json to learn which SDK major is actually installed. + const installedSdkVersion = getPackageVersion( + "@sentry/sveltekit", + await getPackageDotJson(), + ); + const vitePluginImportPath = + getSentrySvelteKitVitePluginImportPath(installedSdkVersion); + + // 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, + SENTRY_SVELTEKIT_SDK_RANGE, + ) && (await askShouldReduceDataCollection()); + + await addDotEnvSentryBuildPluginFile(authToken); + + const svelteConfig = await traceStep("load-svelte-config", loadSvelteConfig); + + try { + await traceStep("configure-sdk", () => + createOrMergeSvelteKitFiles( + { + dsn: selectedProject.keys[0].dsn.public, + org: selectedProject.organization.slug, + project: selectedProject.slug, + selfHosted, + url: sentryUrl, + vitePluginImportPath, + reduceDataCollection, + }, + svelteConfig, + setupForSvelteKitTracing, + ), + ); + } catch (e: unknown) { + clack.log.error("Error while setting up the SvelteKit SDK:"); + clack.log.info(chalk.dim(formatError(e))); + reportCliError(new Error("Error while setting up the SvelteKit SDK")); + await abort("Exiting Wizard"); + return; + } + + const shouldCreateExamplePage = await askShouldCreateExamplePage( + "/sentry-example-page", + ); + + if (shouldCreateExamplePage) { + try { + await traceStep( + "create-example-page", + async () => + await createExamplePage(svelteConfig, { + selfHosted, + url: sentryUrl, + orgSlug: selectedProject.organization.slug, + projectId: selectedProject.id, + isUsingSvelte5: ["5.x", ">5.x"].includes(svelteVersionBucket), + }), + ); + } catch (e: unknown) { + clack.log.error("Error while creating an example page to test Sentry:"); + clack.log.info(chalk.dim(formatError(e))); + reportCliError( + new Error("Error while creating an example Svelte page to test Sentry"), + ); + await abort("Exiting Wizard"); + return; + } + } + + await runPrettierIfInstalled({ cwd: undefined }); + + // Offer optional project-scoped MCP config for Sentry with org and project scope + await offerProjectScopedMcpConfig( + selectedProject.organization.slug, + selectedProject.slug, + ); + + clack.outro(await buildOutroMessage(shouldCreateExamplePage)); +} + +async function buildOutroMessage( + shouldCreateExamplePage: boolean, +): Promise { + const packageManager = await getPackageManager(NPM); + + let msg = chalk.green("Successfully installed the Sentry SvelteKit SDK!"); + + if (shouldCreateExamplePage) { + msg += `\n\nYou can validate your setup by starting your dev environment (${chalk.cyan( + `\`${packageManager.runScriptCommand} dev\``, + )}) and visiting ${chalk.cyan('"/sentry-example-page"')}.`; + } + + msg += `\n\nCheck out the SDK documentation for further configuration: +https://docs.sentry.io/platforms/javascript/guides/sveltekit/`; + + return msg; +} diff --git a/packages/cli/src/lib/wizard/sveltekit/templates.ts b/packages/cli/src/lib/wizard/sveltekit/templates.ts new file mode 100644 index 0000000000..936a9b6aa1 --- /dev/null +++ b/packages/cli/src/lib/wizard/sveltekit/templates.ts @@ -0,0 +1,369 @@ +/** + * Code templates the SvelteKit wizard writes or shows as copy-paste + * instructions. + */ + +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/sveltekit/configuration/options/#dataCollection + // userInfo: false, + // httpBodies: [], + },`; + +/** + * The active PII-reducing preset when the user opted in, the commented-out + * hint otherwise. + */ +function getDataCollectionBlock(reduceDataCollection: boolean): string { + return reduceDataCollection + ? getDataCollectionSnippet(" ") + : DATA_COLLECTION_HINT; +} + +export function getClientHooksTemplate( + dsn: string, + selectedFeatures: { + performance: boolean; + replay: boolean; + }, + reduceDataCollection: boolean, +) { + return `import { handleErrorWithSentry, replayIntegration } from "@sentry/sveltekit"; +import * as Sentry from '@sentry/sveltekit'; + +Sentry.init({ + dsn: '${dsn}', +${ + selectedFeatures.performance + ? ` + tracesSampleRate: 1.0, +` + : "" +} +${ + selectedFeatures.replay + ? ` // This sets the sample rate to be 10%. You may want this to be 100% while + // in development and sample at a lower rate in production + replaysSessionSampleRate: 0.1, + + // If the entire session is not sampled, use the below sample rate to sample + // sessions when an error occurs. + replaysOnErrorSampleRate: 1.0, + + // If you don't want to use Session Replay, just remove the line below: + integrations: [replayIntegration()],` + : "" +} + +${getDataCollectionBlock(reduceDataCollection)} +}); + +// If you have a custom error handler, pass it to \`handleErrorWithSentry\` +export const handleError = handleErrorWithSentry(); +`; +} + +export function getServerHooksTemplate( + dsn: string, + selectedFeatures: { + performance: boolean; + replay: boolean; + }, + includeSentryInit: boolean, + reduceDataCollection: boolean, +) { + const sentryInit = includeSentryInit + ? `import * as Sentry from '@sentry/sveltekit'; + +Sentry.init({ + dsn: '${dsn}', +${ + selectedFeatures.performance + ? ` + tracesSampleRate: 1.0, +` + : "" +} +${getDataCollectionBlock(reduceDataCollection)} + + // uncomment the line below to enable Spotlight (https://spotlightjs.com) + // spotlight: import.meta.env.DEV, +});` + : ``; + + return `import { sequence } from "@sveltejs/kit/hooks"; +import { handleErrorWithSentry, sentryHandle } from "@sentry/sveltekit"; +${sentryInit} + +// If you have custom handlers, make sure to place them after \`sentryHandle()\` in the \`sequence\` function. +export const handle = sequence(sentryHandle()); + +// If you have a custom error handler, pass it to \`handleErrorWithSentry\` +export const handleError = handleErrorWithSentry(); +`; +} + +export function getInstrumentationServerTemplate( + dsn: string, + selectedFeatures: { + performance: boolean; + }, + reduceDataCollection: boolean, +) { + return `import * as Sentry from '@sentry/sveltekit'; + +Sentry.init({ + dsn: '${dsn}', +${ + selectedFeatures.performance + ? ` + tracesSampleRate: 1.0, +` + : "" +}${ + reduceDataCollection + ? `${getDataCollectionSnippet(" ")} +` + : "" + } // uncomment the line below to enable Spotlight (https://spotlightjs.com) + // spotlight: import.meta.env.DEV, +});`; +} + +/** + * +page.svelte with Sentry example + */ +export function getSentryExampleSveltePage(options: { + selfHosted: boolean; + url: string; + orgSlug: string; + projectId: string; + isUsingSvelte5: boolean; +}) { + const issuesPageLink = options.selfHosted + ? `${options.url}organizations/${options.orgSlug}/issues/?project=${options.projectId}` + : `https://${options.orgSlug}.sentry.io/issues/?project=${options.projectId}`; + + 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. +

+ + + + {#if hasSentError} +

+ Sample error was sent to Sentry. +

+ {:else if !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.

+
+ {:else} +
+ {/if} +
+
+
+ + +`; +} + +export function getSentryExampleApiRoute() { + return `// This is just a very simple API route that throws an example error. +// Feel free to delete this file and the entire sentry route. + +export const GET = async () => { + throw new Error("Sentry Example API Route Error"); +}; +`; +} diff --git a/packages/cli/src/lib/wizard/sveltekit/utils.ts b/packages/cli/src/lib/wizard/sveltekit/utils.ts new file mode 100644 index 0000000000..13045bacf9 --- /dev/null +++ b/packages/cli/src/lib/wizard/sveltekit/utils.ts @@ -0,0 +1,117 @@ +/** + * SvelteKit SDK version constants and the SvelteKit and Svelte version + * buckets the wizard branches on. + */ + +import { debug } from "../utils/debug.js"; +import { lt, minVersion } from "semver"; + +import { getMajorVersion } from "../utils/semver.js"; + +/** + * Version range of `@sentry/sveltekit` the wizard installs. Also decides the + * default import path of the Vite plugin when the installed version is unknown. + */ +export const SENTRY_SVELTEKIT_SDK_RANGE = "^11"; + +/** Root export. Exposes `sentrySvelteKit` up to SDK v10 only. */ +export const SENTRY_SVELTEKIT_ROOT_IMPORT_PATH = "@sentry/sveltekit"; + +/** Subpath that exposes `sentrySvelteKit` from SDK v11 on. v10 does not ship it. */ +export const SENTRY_SVELTEKIT_VITE_IMPORT_PATH = "@sentry/sveltekit/vite"; + +/** + * Returns the module `sentrySvelteKit` must be imported from for the installed + * SDK. v11 moved the Vite plugin to the `/vite` subpath and removed it from the + * root export, while v10 only has it on the root export. Unknown or unparseable + * versions fall back to whatever the wizard would install. + */ +export function getSentrySvelteKitVitePluginImportPath( + installedSdkVersion: string | undefined, +): string { + const sdkMajor = + getMajorVersion(installedSdkVersion) ?? + getMajorVersion(SENTRY_SVELTEKIT_SDK_RANGE) ?? + 0; + + return sdkMajor >= 11 + ? SENTRY_SVELTEKIT_VITE_IMPORT_PATH + : SENTRY_SVELTEKIT_ROOT_IMPORT_PATH; +} + +export type KitVersionBucket = + | "none" + | "invalid" + | "0.x" + | ">=1.0.0 <1.24.0" + | ">=1.24.0 <2.31.0" + | ">=2.31.0"; + +export function getKitVersionBucket( + version: string | undefined, +): KitVersionBucket { + if (!version) { + return "none"; + } + + try { + const minVer = minVersion(version); + if (!minVer) { + return "invalid"; + } + + if (lt(minVer, "1.0.0")) { + return "0.x"; + } + if (lt(minVer, "1.24.0")) { + return ">=1.0.0 <1.24.0"; + } + if (lt(minVer, "2.31.0")) { + // This is the version when the client-side invalidation fix was released + // https://github.com/sveltejs/kit/releases/tag/%40sveltejs%2Fkit%401.24.0 + // https://github.com/sveltejs/kit/pull/10576 + return ">=1.24.0 <2.31.0"; + } + // This is the version where sveltekit-native tracing and instrumentation was + // introduced as an experimental feature. + return ">=2.31.0"; + } catch (error) { + // `minVersion` throws for a range it can't parse; the bucket says so. + debug(error); + return "invalid"; + } +} + +export function getSvelteVersionBucket( + version: string | undefined, +): "none" | "invalid" | "<3.0.0" | "3.x" | "4.x" | "5.x" | ">5.x" { + if (!version) { + return "none"; + } + + try { + const minVer = minVersion(version); + if (!minVer) { + return "invalid"; + } + + if (lt(minVer, "3.0.0")) { + return "<3.0.0"; + } + if (lt(minVer, "4.0.0")) { + return "3.x"; + } + if (lt(minVer, "5.0.0")) { + return "4.x"; + } + if (lt(minVer, "6.0.0")) { + return "5.x"; + } + // bucket for any future versions of svelte not covered by the other buckets + return ">5.x"; + } catch (error) { + // `minVersion` throws for a range it can't parse; the bucket says so. + debug(error); + return "invalid"; + } +} diff --git a/packages/cli/src/lib/wizard/utils/abort-if-sportlight-not-supported.ts b/packages/cli/src/lib/wizard/utils/abort-if-sportlight-not-supported.ts new file mode 100644 index 0000000000..18c9a86043 --- /dev/null +++ b/packages/cli/src/lib/wizard/utils/abort-if-sportlight-not-supported.ts @@ -0,0 +1,20 @@ +/** + * Stop a wizard flow that has no Spotlight mode yet when `--spotlight` is + * passed. + */ + +import { abort } from "./clack/index.js"; +import { clack } from "./clack/prompts.js"; + +/** + * Aborts the wizard with a message that Spotlight mode is not yet supported + * for the given platform. + */ +export async function abortIfSpotlightNotSupported( + platform: string, +): Promise { + clack.log.warn(`Spotlight mode is not yet supported for ${platform}.`); + clack.log.info("Spotlight is currently only available for Next.js."); + + return await abort("Exiting wizard", 0); +} diff --git a/packages/cli/test/commands/wizard.test.ts b/packages/cli/test/commands/wizard.test.ts index f320f998b9..e6b27e7dff 100644 --- a/packages/cli/test/commands/wizard.test.ts +++ b/packages/cli/test/commands/wizard.test.ts @@ -12,6 +12,23 @@ vi.mock("../../src/lib/wizard/nextjs/nextjs-wizard.js", () => ({ runNextjsWizard, })); +const { runRemixWizard, runReactRouterWizard, runSvelteKitWizard } = vi.hoisted( + () => ({ + runRemixWizard: vi.fn<(options: unknown) => Promise>(), + runReactRouterWizard: vi.fn<(options: unknown) => Promise>(), + runSvelteKitWizard: vi.fn<(options: unknown) => Promise>(), + }), +); +vi.mock("../../src/lib/wizard/remix/remix-wizard.js", () => ({ + runRemixWizard, +})); +vi.mock("../../src/lib/wizard/react-router/react-router-wizard.js", () => ({ + runReactRouterWizard, +})); +vi.mock("../../src/lib/wizard/sveltekit/sveltekit-wizard.js", () => ({ + runSvelteKitWizard, +})); + import { wizardCommand } from "../../src/commands/wizard.js"; import type { SentryContext } from "../../src/context.js"; import { ValidationError, WizardExitError } from "../../src/lib/errors.js"; @@ -107,9 +124,21 @@ describe("sentry wizard", () => { expect(runNextjsWizard).not.toHaveBeenCalled(); }); + test.each([ + ["remix", runRemixWizard], + ["reactRouter", runReactRouterWizard], + ["sveltekit", runSvelteKitWizard], + ])("runs the %s wizard", async (integration, runner) => { + await runWizardCommand({ integration, org: "acme" }); + + expect(runner).toHaveBeenCalledWith( + expect.objectContaining({ orgSlug: "acme" }), + ); + }); + 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.", + await expect(runWizardCommand({ integration: "flutter" })).rejects.toThrow( + "The flutter wizard is not available in this version yet.", ); }); diff --git a/packages/cli/test/lib/wizard/react-router/codemods/client-entry.test.ts b/packages/cli/test/lib/wizard/react-router/codemods/client-entry.test.ts new file mode 100644 index 0000000000..2038964b4f --- /dev/null +++ b/packages/cli/test/lib/wizard/react-router/codemods/client-entry.test.ts @@ -0,0 +1,368 @@ +import { describe, expect, it, vi, beforeEach, afterEach } from "vitest"; +import { + existsSync, + mkdirSync, + readFileSync, + rmSync, + writeFileSync, +} from "node:fs"; +import path from "node:path"; +import { instrumentClientEntry } from "../../../../../src/lib/wizard/react-router/codemods/client.entry.js"; + +vi.mock("@clack/prompts", () => { + const mock = { + log: { + warn: vi.fn(), + info: vi.fn(), + success: vi.fn(), + }, + }; + return { + default: mock, + ...mock, + }; +}); + +describe("instrumentClientEntry", () => { + const fixturesDir = path.join(__dirname, "fixtures", "client-entry"); + let tmpDir: string; + let tmpFile: string; + + beforeEach(() => { + vi.clearAllMocks(); + + // Create unique tmp directory for each test + tmpDir = path.join( + fixturesDir, + "tmp", + `test-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`, + ); + tmpFile = path.join(tmpDir, "entry.client.tsx"); + + // Ensure tmp directory exists + mkdirSync(tmpDir, { recursive: true }); + }); + + afterEach(() => { + // Clean up tmp directory + if (existsSync(tmpDir)) { + rmSync(tmpDir, { recursive: true }); + } + }); + + it("should add Sentry import and initialization with all features enabled", async () => { + const basicContent = readFileSync( + path.join(fixturesDir, "basic.tsx"), + "utf8", + ); + + writeFileSync(tmpFile, basicContent); + + await instrumentClientEntry( + tmpFile, + "test-dsn", + true, + true, + false, + false, + true, + ); + + const modifiedContent = readFileSync(tmpFile, "utf8"); + + expect(modifiedContent).toContain( + 'import * as Sentry from "@sentry/react-router";', + ); + expect(modifiedContent).toContain("Sentry.init({"); + expect(modifiedContent).toContain('dsn: "test-dsn"'); + expect(modifiedContent).toContain("integrations: ["); + expect(modifiedContent).toContain("Sentry.reactRouterTracingIntegration()"); + expect(modifiedContent).toContain("Sentry.replayIntegration("); + expect(modifiedContent).toContain("onError={Sentry.sentryOnError}"); + }); + + it("should add Sentry initialization with only tracing enabled", async () => { + const basicContent = readFileSync( + path.join(fixturesDir, "basic.tsx"), + "utf8", + ); + + writeFileSync(tmpFile, basicContent); + + await instrumentClientEntry(tmpFile, "test-dsn", true, false, false); + + const modifiedContent = readFileSync(tmpFile, "utf8"); + + expect(modifiedContent).toContain( + 'import * as Sentry from "@sentry/react-router";', + ); + expect(modifiedContent).toContain("Sentry.init({"); + expect(modifiedContent).toContain('dsn: "test-dsn"'); + expect(modifiedContent).toContain("integrations: ["); + expect(modifiedContent).toContain("Sentry.reactRouterTracingIntegration()"); + expect(modifiedContent).not.toContain("Sentry.replayIntegration()"); + }); + + it("should add Sentry initialization with only replay enabled", async () => { + const basicContent = readFileSync( + path.join(fixturesDir, "basic.tsx"), + "utf8", + ); + + writeFileSync(tmpFile, basicContent); + + await instrumentClientEntry(tmpFile, "test-dsn", false, true, false); + + const modifiedContent = readFileSync(tmpFile, "utf8"); + + expect(modifiedContent).toContain( + 'import * as Sentry from "@sentry/react-router";', + ); + expect(modifiedContent).toContain("Sentry.init({"); + expect(modifiedContent).toContain('dsn: "test-dsn"'); + expect(modifiedContent).toContain("integrations: ["); + expect(modifiedContent).not.toContain( + "Sentry.reactRouterTracingIntegration()", + ); + expect(modifiedContent).toContain("Sentry.replayIntegration("); + }); + + it("should add minimal Sentry initialization when all features are disabled", async () => { + const basicContent = readFileSync( + path.join(fixturesDir, "basic.tsx"), + "utf8", + ); + + writeFileSync(tmpFile, basicContent); + + await instrumentClientEntry(tmpFile, "test-dsn", false, false, false); + + const modifiedContent = readFileSync(tmpFile, "utf8"); + + expect(modifiedContent).toContain( + 'import * as Sentry from "@sentry/react-router";', + ); + expect(modifiedContent).toContain("Sentry.init({"); + expect(modifiedContent).toContain('dsn: "test-dsn"'); + expect(modifiedContent).toContain("integrations: []"); + expect(modifiedContent).not.toContain( + "Sentry.reactRouterTracingIntegration()", + ); + expect(modifiedContent).not.toContain("Sentry.replayIntegration()"); + }); + + it("should write the dataCollection preset when reduceDataCollection is true", async () => { + const basicContent = readFileSync( + path.join(fixturesDir, "basic.tsx"), + "utf8", + ); + + writeFileSync(tmpFile, basicContent); + + await instrumentClientEntry(tmpFile, "test-dsn", true, true, true); + + const modifiedContent = readFileSync(tmpFile, "utf8"); + + expect(modifiedContent).toContain("userInfo: false,"); + expect(modifiedContent).toContain( + 'httpHeaders: { deny: ["forwarded", "-ip", "remote-", "via", "-user"] }', + ); + expect(modifiedContent).not.toContain("// userInfo: false,"); + expect(modifiedContent).not.toContain( + "uncomment the lines below. For more info visit:", + ); + }); + + it("should keep the commented dataCollection hint when reduceDataCollection is false", async () => { + const basicContent = readFileSync( + path.join(fixturesDir, "basic.tsx"), + "utf8", + ); + + writeFileSync(tmpFile, basicContent); + + await instrumentClientEntry(tmpFile, "test-dsn", true, true, false); + + const modifiedContent = readFileSync(tmpFile, "utf8"); + + expect(modifiedContent).toContain("// userInfo: false,"); + expect(modifiedContent).toContain("// httpBodies: [],"); + expect(modifiedContent).toContain( + "uncomment the lines below. For more info visit:", + ); + }); + + it("should not add Sentry.init when Sentry content already exists but still add onError", async () => { + const withSentryContent = readFileSync( + path.join(fixturesDir, "with-sentry.tsx"), + "utf8", + ); + + writeFileSync(tmpFile, withSentryContent); + + await instrumentClientEntry( + tmpFile, + "test-dsn", + true, + true, + false, + false, + true, + ); + + const modifiedContent = readFileSync(tmpFile, "utf8"); + + // Should not duplicate Sentry.init + const initCount = (modifiedContent.match(/Sentry\.init\(/g) || []).length; + expect(initCount).toBe(1); + + // Should still add onError prop to HydratedRouter + expect(modifiedContent).toContain("onError={Sentry.sentryOnError}"); + }); + + it("should insert Sentry initialization after imports", async () => { + const withImportsContent = readFileSync( + path.join(fixturesDir, "with-imports.tsx"), + "utf8", + ); + + writeFileSync(tmpFile, withImportsContent); + + await instrumentClientEntry(tmpFile, "test-dsn", true, false, false); + + const modifiedContent = readFileSync(tmpFile, "utf8"); + + expect(modifiedContent).toContain( + 'import * as Sentry from "@sentry/react-router";', + ); + expect(modifiedContent).toContain("Sentry.init({"); + + // Check that the Sentry import is before the init call + const sentryImportIndex = modifiedContent.indexOf( + 'import * as Sentry from "@sentry/react-router";', + ); + const sentryInitIndex = modifiedContent.indexOf("Sentry.init({"); + expect(sentryImportIndex).toBeLessThan(sentryInitIndex); + }); + + it("should handle files with no imports", async () => { + const noImportsContent = readFileSync( + path.join(fixturesDir, "no-imports.tsx"), + "utf8", + ); + + writeFileSync(tmpFile, noImportsContent); + + await instrumentClientEntry(tmpFile, "test-dsn", false, true, false); + + const modifiedContent = readFileSync(tmpFile, "utf8"); + + expect(modifiedContent).toContain( + 'import * as Sentry from "@sentry/react-router";', + ); + expect(modifiedContent).toContain("Sentry.init({"); + expect(modifiedContent).toContain("Sentry.replayIntegration("); + }); + + it("should preserve existing code structure", async () => { + const complexContent = readFileSync( + path.join(fixturesDir, "complex.tsx"), + "utf8", + ); + + writeFileSync(tmpFile, complexContent); + + await instrumentClientEntry(tmpFile, "test-dsn", true, true, false); + + const modifiedContent = readFileSync(tmpFile, "utf8"); + + expect(modifiedContent).toContain( + 'import * as Sentry from "@sentry/react-router";', + ); + expect(modifiedContent).toContain("Sentry.init({"); + + // Original content should still be there + expect(modifiedContent).toContain("startTransition"); + expect(modifiedContent).toContain("hydrateRoot"); + expect(modifiedContent).toContain(""); + }); + + describe("Instrumentation API", () => { + it("should add instrumentation API setup when enabled", async () => { + const basicContent = readFileSync( + path.join(fixturesDir, "basic.tsx"), + "utf8", + ); + + writeFileSync(tmpFile, basicContent); + + await instrumentClientEntry( + tmpFile, + "test-dsn", + true, + false, + false, + true, + ); + + const modifiedContent = readFileSync(tmpFile, "utf8"); + + expect(modifiedContent).toContain( + "const tracing = Sentry.reactRouterTracingIntegration();", + ); + expect(modifiedContent).toContain("integrations: [tracing]"); + expect(modifiedContent).toContain( + "instrumentations={[tracing.clientInstrumentation]}", + ); + }); + + it("should combine instrumentation API with replay", async () => { + const basicContent = readFileSync( + path.join(fixturesDir, "basic.tsx"), + "utf8", + ); + + writeFileSync(tmpFile, basicContent); + + await instrumentClientEntry(tmpFile, "test-dsn", true, true, false, true); + + const modifiedContent = readFileSync(tmpFile, "utf8"); + + expect(modifiedContent).toContain( + "const tracing = Sentry.reactRouterTracingIntegration();", + ); + expect(modifiedContent).toContain( + "integrations: [tracing, Sentry.replayIntegration()]", + ); + expect(modifiedContent).toContain( + "instrumentations={[tracing.clientInstrumentation]}", + ); + }); + + it("should not use instrumentation API when useInstrumentationAPI is false", async () => { + const basicContent = readFileSync( + path.join(fixturesDir, "basic.tsx"), + "utf8", + ); + + writeFileSync(tmpFile, basicContent); + + await instrumentClientEntry( + tmpFile, + "test-dsn", + true, + false, + false, + false, + ); + + const modifiedContent = readFileSync(tmpFile, "utf8"); + + expect(modifiedContent).not.toContain("const tracing"); + expect(modifiedContent).toContain( + "Sentry.reactRouterTracingIntegration()", + ); + expect(modifiedContent).not.toContain("instrumentations"); + }); + }); +}); diff --git a/packages/cli/test/lib/wizard/react-router/codemods/fixtures/client-entry/basic.tsx b/packages/cli/test/lib/wizard/react-router/codemods/fixtures/client-entry/basic.tsx new file mode 100644 index 0000000000..08ab4ec358 --- /dev/null +++ b/packages/cli/test/lib/wizard/react-router/codemods/fixtures/client-entry/basic.tsx @@ -0,0 +1,12 @@ +import { startTransition, StrictMode } from "react"; +import { hydrateRoot } from "react-dom/client"; +import { HydratedRouter } from "react-router/dom"; + +startTransition(() => { + hydrateRoot( + document, + + + + ); +}); diff --git a/packages/cli/test/lib/wizard/react-router/codemods/fixtures/client-entry/complex.tsx b/packages/cli/test/lib/wizard/react-router/codemods/fixtures/client-entry/complex.tsx new file mode 100644 index 0000000000..87ab5bdca3 --- /dev/null +++ b/packages/cli/test/lib/wizard/react-router/codemods/fixtures/client-entry/complex.tsx @@ -0,0 +1,30 @@ +import { startTransition, StrictMode } from "react"; +import { hydrateRoot } from "react-dom/client"; +import { HydratedRouter } from "react-router/dom"; +import { SomeProvider } from "./providers"; +import { GlobalStyles } from "./styles"; + +// Some configuration +const config = { + enableTracing: true, + debugMode: false, +}; + +// Initialize the app +function initializeApp() { + console.log('Initializing app with config:', config); +} + +startTransition(() => { + initializeApp(); + + hydrateRoot( + document, + + + + + + + ); +}); diff --git a/packages/cli/test/lib/wizard/react-router/codemods/fixtures/client-entry/no-imports.tsx b/packages/cli/test/lib/wizard/react-router/codemods/fixtures/client-entry/no-imports.tsx new file mode 100644 index 0000000000..fcb950ad77 --- /dev/null +++ b/packages/cli/test/lib/wizard/react-router/codemods/fixtures/client-entry/no-imports.tsx @@ -0,0 +1,6 @@ +// Simple client entry without imports + +const element = document.getElementById('root'); +if (element) { + console.log('Starting app'); +} diff --git a/packages/cli/test/lib/wizard/react-router/codemods/fixtures/client-entry/with-imports.tsx b/packages/cli/test/lib/wizard/react-router/codemods/fixtures/client-entry/with-imports.tsx new file mode 100644 index 0000000000..d69b73c94d --- /dev/null +++ b/packages/cli/test/lib/wizard/react-router/codemods/fixtures/client-entry/with-imports.tsx @@ -0,0 +1,13 @@ +import { startTransition, StrictMode } from "react"; +import { hydrateRoot } from "react-dom/client"; +import { HydratedRouter } from "react-router/dom"; +import { SomeOtherImport } from "./some-module"; + +startTransition(() => { + hydrateRoot( + document, + + + + ); +}); diff --git a/packages/cli/test/lib/wizard/react-router/codemods/fixtures/client-entry/with-sentry.tsx b/packages/cli/test/lib/wizard/react-router/codemods/fixtures/client-entry/with-sentry.tsx new file mode 100644 index 0000000000..980a959e71 --- /dev/null +++ b/packages/cli/test/lib/wizard/react-router/codemods/fixtures/client-entry/with-sentry.tsx @@ -0,0 +1,18 @@ +import * as Sentry from '@sentry/react-router'; +import { startTransition, StrictMode } from "react"; +import { hydrateRoot } from "react-dom/client"; +import { HydratedRouter } from "react-router/dom"; + +Sentry.init({ + dsn: "existing-dsn", + tracesSampleRate: 1.0, +}); + +startTransition(() => { + hydrateRoot( + document, + + + + ); +}); diff --git a/packages/cli/test/lib/wizard/react-router/codemods/fixtures/server-entry/already-instrumented.tsx b/packages/cli/test/lib/wizard/react-router/codemods/fixtures/server-entry/already-instrumented.tsx new file mode 100644 index 0000000000..10ab95329a --- /dev/null +++ b/packages/cli/test/lib/wizard/react-router/codemods/fixtures/server-entry/already-instrumented.tsx @@ -0,0 +1,28 @@ +import * as Sentry from '@sentry/react-router'; +import type { AppLoadContext, EntryContext } from 'react-router'; + +async function handleRequest( + request: Request, + responseStatusCode: number, + responseHeaders: Headers, + routerContext: EntryContext, + loadContext: AppLoadContext +) { + return new Response('Already instrumented', { + status: responseStatusCode, + headers: responseHeaders, + }); +} + +export async function handleError( + error: unknown, + { request }: { request: Request } +): Promise { + if (!request.signal.aborted) { + Sentry.captureException(error); + } + console.error(error); + return new Response('Internal Server Error', { status: 500 }); +} + +export default Sentry.wrapSentryHandleRequest(handleRequest); diff --git a/packages/cli/test/lib/wizard/react-router/codemods/fixtures/server-entry/basic.tsx b/packages/cli/test/lib/wizard/react-router/codemods/fixtures/server-entry/basic.tsx new file mode 100644 index 0000000000..7bc4603f8d --- /dev/null +++ b/packages/cli/test/lib/wizard/react-router/codemods/fixtures/server-entry/basic.tsx @@ -0,0 +1,23 @@ +import type { AppLoadContext, EntryContext } from 'react-router'; +import { ServerRouter } from 'react-router'; +import { renderToString } from 'react-dom/server'; + +// Basic server entry file with no handleRequest or handleError functions +export default function handleRequest( + request: Request, + responseStatusCode: number, + responseHeaders: Headers, + routerContext: EntryContext, + loadContext: AppLoadContext +) { + const html = renderToString( + + ); + + responseHeaders.set('Content-Type', 'text/html'); + + return new Response(`${html}`, { + status: responseStatusCode, + headers: responseHeaders, + }); +} diff --git a/packages/cli/test/lib/wizard/react-router/codemods/fixtures/server-entry/entry-server-basic.ts b/packages/cli/test/lib/wizard/react-router/codemods/fixtures/server-entry/entry-server-basic.ts new file mode 100644 index 0000000000..f68bd1509b --- /dev/null +++ b/packages/cli/test/lib/wizard/react-router/codemods/fixtures/server-entry/entry-server-basic.ts @@ -0,0 +1,5 @@ +import { createRequestHandler } from "@react-router/node"; + +export default createRequestHandler({ + build: require("./build"), +}); diff --git a/packages/cli/test/lib/wizard/react-router/codemods/fixtures/server-entry/variable-export.tsx b/packages/cli/test/lib/wizard/react-router/codemods/fixtures/server-entry/variable-export.tsx new file mode 100644 index 0000000000..24caa74de2 --- /dev/null +++ b/packages/cli/test/lib/wizard/react-router/codemods/fixtures/server-entry/variable-export.tsx @@ -0,0 +1,31 @@ +import type { AppLoadContext, EntryContext } from 'react-router'; +import { ServerRouter } from 'react-router'; +import { renderToString } from 'react-dom/server'; + +// handleError declared as variable and exported directly +export const handleError = async ( + error: unknown, + { request }: { request: Request } +): Promise => { + console.error('Unhandled error:', error); + return new Response('Internal Server Error', { status: 500 }); +}; + +export default function handleRequest( + request: Request, + responseStatusCode: number, + responseHeaders: Headers, + routerContext: EntryContext, + loadContext: AppLoadContext +) { + const html = renderToString( + + ); + + responseHeaders.set('Content-Type', 'text/html'); + + return new Response(`${html}`, { + status: responseStatusCode, + headers: responseHeaders, + }); +} diff --git a/packages/cli/test/lib/wizard/react-router/codemods/react-router-config.test.ts b/packages/cli/test/lib/wizard/react-router/codemods/react-router-config.test.ts new file mode 100644 index 0000000000..7f1356a72a --- /dev/null +++ b/packages/cli/test/lib/wizard/react-router/codemods/react-router-config.test.ts @@ -0,0 +1,221 @@ +import { existsSync, promises } from "node:fs"; +import path from "node:path"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { instrumentReactRouterConfig } from "../../../../../src/lib/wizard/react-router/codemods/react-router-config.js"; + +vi.mock("@clack/prompts", () => ({ + log: { + info: vi.fn(), + warn: vi.fn(), + success: vi.fn(), + }, +})); +vi.mock("node:fs", async () => { + const actual = await vi.importActual("node:fs"); + return { + ...actual, + existsSync: vi.fn(), + promises: { + ...actual.promises, + readFile: vi.fn(), + writeFile: vi.fn(), + }, + }; +}); + +describe("React Router Config File Instrumentation", () => { + const mockCwd = "/mock/project"; + + beforeEach(() => { + vi.clearAllMocks(); + vi.spyOn(process, "cwd").mockReturnValue(mockCwd); + }); + + afterEach(() => { + vi.restoreAllMocks(); + }); + + describe("instrumentReactRouterConfig", () => { + it("imports sentryOnBuildEnd from the given path when creating the config", async () => { + const writtenFiles: Record = {}; + vi.mocked(existsSync).mockReturnValue(false); + vi.mocked(promises.writeFile).mockImplementation((filePath, content) => { + writtenFiles[filePath as string] = content as string; + return Promise.resolve(); + }); + + await instrumentReactRouterConfig(true, "@sentry/react-router/vite"); + + const written = Object.values(writtenFiles)[0]; + expect(written).toContain( + 'import { sentryOnBuildEnd } from "@sentry/react-router/vite";', + ); + expect(written).not.toContain('from "@sentry/react-router";'); + }); + + it("imports sentryOnBuildEnd from the given path when modifying an existing config", async () => { + const writtenFiles: Record = {}; + vi.mocked(existsSync).mockReturnValue(true); + vi.mocked(promises.readFile).mockResolvedValue( + `import type { Config } from "@react-router/dev/config"; + +export default { + ssr: true, +} satisfies Config; +`, + ); + vi.mocked(promises.writeFile).mockImplementation((filePath, content) => { + writtenFiles[filePath as string] = content as string; + return Promise.resolve(); + }); + + await instrumentReactRouterConfig(true, "@sentry/react-router/vite"); + + const written = Object.values(writtenFiles)[0]; + expect(written).toContain('from "@sentry/react-router/vite"'); + expect(written).toContain("sentryOnBuildEnd"); + expect(written).not.toContain('from "@sentry/react-router";'); + }); + + it("should create new config file if it does not exist", async () => { + const writtenFiles: Record = {}; + + vi.mocked(existsSync).mockReturnValue(false); + vi.mocked(promises.writeFile).mockImplementation((filePath, content) => { + writtenFiles[filePath as string] = content as string; + return Promise.resolve(); + }); + + const result = await instrumentReactRouterConfig(true); + + expect(result.ssrWasChanged).toBe(false); + + const configPath = path.join(mockCwd, "react-router.config.ts"); + expect(writtenFiles[configPath]).toContain("ssr: true"); + expect(writtenFiles[configPath]).toContain("sentryOnBuildEnd"); + expect(writtenFiles[configPath]).toContain("buildEnd:"); + }); + + it("should create .js config when TypeScript is not used", async () => { + const writtenFiles: Record = {}; + + vi.mocked(existsSync).mockReturnValue(false); + vi.mocked(promises.writeFile).mockImplementation((filePath, content) => { + writtenFiles[filePath as string] = content as string; + return Promise.resolve(); + }); + + await instrumentReactRouterConfig(false); + + const configPath = path.join(mockCwd, "react-router.config.js"); + expect(writtenFiles[configPath]).toBeDefined(); + // Verify JS config doesn't have TypeScript-only syntax + expect(writtenFiles[configPath]).not.toContain("import type"); + expect(writtenFiles[configPath]).not.toContain("satisfies Config"); + expect(writtenFiles[configPath]).toContain("sentryOnBuildEnd"); + expect(writtenFiles[configPath]).toContain("buildEnd:"); + }); + + it("should detect and skip if Sentry content already exists", async () => { + const existingConfig = `import { sentryOnBuildEnd } from '@sentry/react-router'; + +export default { + ssr: true, + buildEnd: async ({ viteConfig, reactRouterConfig, buildManifest }) => { + await sentryOnBuildEnd({ viteConfig, reactRouterConfig, buildManifest }); + } +};`; + + vi.mocked(existsSync).mockReturnValue(true); + vi.mocked(promises.readFile).mockResolvedValue(existingConfig); + + const result = await instrumentReactRouterConfig(true); + + expect(result.ssrWasChanged).toBe(false); + }); + + it("should add buildEnd hook to existing config", async () => { + const existingConfig = `export default { + ssr: true, + async: false +};`; + + const writtenFiles: Record = {}; + + vi.mocked(existsSync).mockReturnValue(true); + vi.mocked(promises.readFile).mockResolvedValue(existingConfig); + vi.mocked(promises.writeFile).mockImplementation((filePath, content) => { + writtenFiles[filePath as string] = content as string; + return Promise.resolve(); + }); + + const result = await instrumentReactRouterConfig(true); + + expect(result.ssrWasChanged).toBe(false); + + const writtenConfig = Object.values(writtenFiles)[0]; + expect(writtenConfig).toContain("sentryOnBuildEnd"); + expect(writtenConfig).toContain("buildEnd:"); + }); + + it("should set ssr: true if missing", async () => { + const existingConfig = `export default { + async: false +};`; + + const writtenFiles: Record = {}; + + vi.mocked(existsSync).mockReturnValue(true); + vi.mocked(promises.readFile).mockResolvedValue(existingConfig); + vi.mocked(promises.writeFile).mockImplementation((filePath, content) => { + writtenFiles[filePath as string] = content as string; + return Promise.resolve(); + }); + + const result = await instrumentReactRouterConfig(true); + + expect(result.ssrWasChanged).toBe(true); + + const writtenConfig = Object.values(writtenFiles)[0]; + expect(writtenConfig).toContain("ssr: true"); + }); + + it("should report ssrWasChanged when changing ssr from false to true", async () => { + const existingConfig = `export default { + ssr: false +};`; + + const writtenFiles: Record = {}; + + vi.mocked(existsSync).mockReturnValue(true); + vi.mocked(promises.readFile).mockResolvedValue(existingConfig); + vi.mocked(promises.writeFile).mockImplementation((filePath, content) => { + writtenFiles[filePath as string] = content as string; + return Promise.resolve(); + }); + + const result = await instrumentReactRouterConfig(true); + + expect(result.ssrWasChanged).toBe(true); + + const writtenConfig = Object.values(writtenFiles)[0]; + expect(writtenConfig).toContain("ssr: true"); + }); + + it("should throw error if buildEnd already exists", async () => { + const existingConfig = `export default { + ssr: true, + buildEnd: async () => { + console.log('existing hook'); + } +};`; + + vi.mocked(existsSync).mockReturnValue(true); + vi.mocked(promises.readFile).mockResolvedValue(existingConfig); + + await expect(instrumentReactRouterConfig(true)).rejects.toThrow( + "A buildEnd hook already exists", + ); + }); + }); +}); diff --git a/packages/cli/test/lib/wizard/react-router/codemods/server-entry.test.ts b/packages/cli/test/lib/wizard/react-router/codemods/server-entry.test.ts new file mode 100644 index 0000000000..72b6afb78d --- /dev/null +++ b/packages/cli/test/lib/wizard/react-router/codemods/server-entry.test.ts @@ -0,0 +1,683 @@ +import { describe, expect, it, vi, beforeEach, afterEach } from "vitest"; +import { + existsSync, + mkdirSync, + readFileSync, + rmSync, + writeFileSync, +} from "node:fs"; +import path from "node:path"; +import recast from "recast"; +import { + instrumentServerEntry, + instrumentHandleRequest, + instrumentHandleError, +} from "../../../../../src/lib/wizard/react-router/codemods/server-entry.js"; + +import { loadFile, generateCode } from "magicast"; + +vi.mock("@clack/prompts", () => { + const mock = { + log: { + warn: vi.fn(), + info: vi.fn(), + success: vi.fn(), + }, + }; + return { + default: mock, + ...mock, + }; +}); + +vi.mock("../../../../../src/lib/wizard/utils/debug.js", () => ({ + debug: vi.fn(), +})); + +describe("instrumentServerEntry", () => { + const fixturesDir = path.join(__dirname, "fixtures", "server-entry"); + let tmpDir: string; + let tmpFile: string; + + beforeEach(() => { + vi.clearAllMocks(); + + // Create unique tmp directory for each test + tmpDir = path.join( + __dirname, + "fixtures", + "tmp", + `test-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`, + ); + tmpFile = path.join(tmpDir, "entry.server.tsx"); + + // Ensure tmp directory exists + mkdirSync(tmpDir, { recursive: true }); + }); + + afterEach(() => { + // Clean up tmp directory + if (existsSync(tmpDir)) { + rmSync(tmpDir, { recursive: true }); + } + }); + + it("should add Sentry import and wrap handleRequest function", async () => { + const basicContent = readFileSync( + path.join(fixturesDir, "basic.tsx"), + "utf8", + ); + + writeFileSync(tmpFile, basicContent); + + await instrumentServerEntry(tmpFile); + + const modifiedContent = readFileSync(tmpFile, "utf8"); + + // Should add Sentry import + expect(modifiedContent).toContain( + 'import * as Sentry from "@sentry/react-router";', + ); + + // Should wrap the existing handleRequest function + expect(modifiedContent).toContain( + "export default Sentry.wrapSentryHandleRequest(handleRequest);", + ); + + // Should add the Sentry import at the top of the file (after existing imports) + const lines = modifiedContent.split("\n"); + const sentryImportLine = lines.findIndex((line) => + line.includes('import * as Sentry from "@sentry/react-router";'), + ); + expect(sentryImportLine).toBeGreaterThanOrEqual(0); + + // Should make handleRequest async + expect(modifiedContent).toMatch(/async function handleRequest/); + + // Should create default handleError since none exists + expect(modifiedContent).toContain( + "export const handleError = Sentry.createSentryHandleError({", + ); + expect(modifiedContent).toContain("logErrors: false"); + }); + + it("should handle already instrumented server entry without duplication", async () => { + const alreadyInstrumentedContent = readFileSync( + path.join(fixturesDir, "already-instrumented.tsx"), + "utf8", + ); + + writeFileSync(tmpFile, alreadyInstrumentedContent); + + await instrumentServerEntry(tmpFile); + + const modifiedContent = readFileSync(tmpFile, "utf8"); + + // Should not add duplicate imports or wrapping since already instrumented + expect(modifiedContent).toContain( + "import * as Sentry from '@sentry/react-router';", + ); + expect(modifiedContent).toContain( + "export default Sentry.wrapSentryHandleRequest(handleRequest);", + ); + + // Should NOT add a new createSentryHandleError export since handleError already has captureException + expect(modifiedContent).not.toContain( + "export const handleError = Sentry.createSentryHandleError({", + ); + + // Should preserve the existing handleError function with captureException + expect(modifiedContent).toContain("Sentry.captureException(error);"); + expect(modifiedContent).toContain("export async function handleError"); + }); + + it("should handle variable export pattern with existing export", async () => { + const variableExportContent = readFileSync( + path.join(fixturesDir, "variable-export.tsx"), + "utf8", + ); + + writeFileSync(tmpFile, variableExportContent); + + await instrumentServerEntry(tmpFile); + + const modifiedContent = readFileSync(tmpFile, "utf8"); + + // Should add Sentry import and wrap handleRequest + expect(modifiedContent).toContain( + 'import * as Sentry from "@sentry/react-router";', + ); + expect(modifiedContent).toContain( + "export default Sentry.wrapSentryHandleRequest(handleRequest);", + ); + + // Should instrument the existing handleError variable with captureException + expect(modifiedContent).toContain("Sentry.captureException(error);"); + + // Should preserve the variable export pattern + expect(modifiedContent).toContain("export const handleError"); + }); + + it("should not add duplicate async keyword when handleRequest is already async", async () => { + const asyncContent = ` +import { ServerRouter } from 'react-router'; +import { renderToString } from 'react-dom/server'; + +export default async function handleRequest(request: Request) { + const html = renderToString(); + return new Response(html); +} +`; + writeFileSync(tmpFile, asyncContent); + + await instrumentServerEntry(tmpFile); + + const modifiedContent = readFileSync(tmpFile, "utf8"); + + // Should have async function handleRequest (not async async) + expect(modifiedContent).toMatch(/async function handleRequest/); + expect(modifiedContent).not.toMatch(/async\s+async/); + expect(modifiedContent).toContain( + "export default Sentry.wrapSentryHandleRequest(handleRequest);", + ); + }); +}); + +describe("instrumentHandleRequest", () => { + let tmpDir: string; + + beforeEach(() => { + tmpDir = path.join( + __dirname, + "fixtures", + "tmp", + `handle-request-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`, + ); + mkdirSync(tmpDir, { recursive: true }); + }); + + afterEach(() => { + if (existsSync(tmpDir)) { + rmSync(tmpDir, { recursive: true }); + } + }); + + it("should add required imports when creating new handleRequest", async () => { + const content = `// Empty server entry file`; + const tempFile = path.join(tmpDir, "entry.server.tsx"); + writeFileSync(tempFile, content); + + const mod = await loadFile(tempFile); + instrumentHandleRequest(mod); + + // Check if required imports were added + const imports = mod.imports.$items; + const hasServerRouter = imports.some( + (item: any) => + item.imported === "ServerRouter" && item.from === "react-router", + ); + const hasRenderToPipeableStream = imports.some( + (item: any) => + item.imported === "renderToPipeableStream" && + item.from === "react-dom/server", + ); + + expect(hasServerRouter).toBe(true); + expect(hasRenderToPipeableStream).toBe(true); + }); + + it("should not duplicate imports if they already exist", async () => { + const content = ` +import { ServerRouter } from 'react-router'; +import { renderToPipeableStream } from 'react-dom/server'; +import { createReadableStreamFromReadable } from '@react-router/node'; +`; + const tempFile = path.join(tmpDir, "entry.server.tsx"); + writeFileSync(tempFile, content); + + const mod = await loadFile(tempFile); + const originalImportsCount = mod.imports.$items.length; + + instrumentHandleRequest(mod); + + // Should not add duplicate imports + expect(mod.imports.$items.length).toBe(originalImportsCount); + }); +}); + +describe("instrumentHandleError", () => { + let tmpDir: string; + + beforeEach(() => { + tmpDir = path.join( + __dirname, + "fixtures", + "tmp", + `handle-error-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`, + ); + mkdirSync(tmpDir, { recursive: true }); + }); + + afterEach(() => { + if (existsSync(tmpDir)) { + rmSync(tmpDir, { recursive: true }); + } + }); + + it("should not modify existing handleError with captureException", async () => { + const content = ` +export function handleError(error: unknown) { + Sentry.captureException(error); + console.error(error); +} +`; + const tempFile = path.join(tmpDir, "entry.server.tsx"); + writeFileSync(tempFile, content); + + const mod = await loadFile(tempFile); + const originalBodyLength = (mod.$ast as any).body.length; + + instrumentHandleError(mod); + + // Should not modify since captureException already exists + expect((mod.$ast as any).body.length).toBe(originalBodyLength); + }); + + it("should not modify existing handleError with createSentryHandleError", async () => { + const content = ` +export const handleError = Sentry.createSentryHandleError({ + logErrors: false +}); +`; + const tempFile = path.join(tmpDir, "entry.server.tsx"); + writeFileSync(tempFile, content); + + const mod = await loadFile(tempFile); + const originalBodyLength = (mod.$ast as any).body.length; + + instrumentHandleError(mod); + + // Should not modify since createSentryHandleError already exists + expect((mod.$ast as any).body.length).toBe(originalBodyLength); + }); + + it("should add captureException to existing handleError function declaration without breaking AST", async () => { + const content = ` +export function handleError(error: unknown) { + console.error('Custom error handling:', error); + // some other logic here +} +`; + const tempFile = path.join(tmpDir, "entry.server.tsx"); + writeFileSync(tempFile, content); + + const mod = await loadFile(tempFile); + + // This should not throw an error due to broken AST manipulation + expect(() => instrumentHandleError(mod)).not.toThrow(); + + // Verify the function was modified correctly + const modifiedCode = generateCode(mod.$ast).code; + expect(modifiedCode).toContain("Sentry.captureException(error)"); + expect(modifiedCode).toContain( + "console.error('Custom error handling:', error)", + ); + }); + + it("should add captureException to existing handleError variable declaration without breaking AST", async () => { + const content = ` +export const handleError = (error: unknown, { request }: { request: Request }) => { + console.log('Handling error:', error.message); + return new Response('Error occurred', { status: 500 }); +}; +`; + const tempFile = path.join(tmpDir, "entry.server.tsx"); + writeFileSync(tempFile, content); + + const mod = await loadFile(tempFile); + + // This should not throw an error due to broken AST manipulation + expect(() => instrumentHandleError(mod)).not.toThrow(); + + // Verify the function was modified correctly + const modifiedCode = generateCode(mod.$ast).code; + expect(modifiedCode).toContain("Sentry.captureException(error)"); + expect(modifiedCode).toContain( + "console.log('Handling error:', error.message)", + ); + }); + + it("should handle existing handleError with only error parameter and add request parameter", async () => { + const content = ` +export const handleError = (error: unknown) => { + console.error('Simple error handler:', error); +}; +`; + const tempFile = path.join(tmpDir, "entry.server.tsx"); + writeFileSync(tempFile, content); + + const mod = await loadFile(tempFile); + + // This should not throw an error due to broken AST manipulation + expect(() => instrumentHandleError(mod)).not.toThrow(); + + // Verify the function signature was updated correctly + const modifiedCode = generateCode(mod.$ast).code; + expect(modifiedCode).toContain("Sentry.captureException(error)"); + expect(modifiedCode).toContain("if (!request.signal.aborted)"); + // Should add request parameter + expect(modifiedCode).toMatch( + /handleError.*=.*\(\s*error.*,\s*\{\s*request\s*\}/, + ); + }); +}); + +describe("instrumentHandleError AST manipulation edge cases", () => { + let tmpDir: string; + + beforeEach(() => { + tmpDir = path.join( + __dirname, + "fixtures", + "tmp", + `ast-edge-cases-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`, + ); + mkdirSync(tmpDir, { recursive: true }); + }); + + afterEach(() => { + if (existsSync(tmpDir)) { + rmSync(tmpDir, { recursive: true }); + } + }); + + it("should handle function declaration with existing try-catch block", async () => { + const content = ` +export function handleError(error: unknown, { request }: { request: Request }) { + try { + console.error('Error occurred:', error); + logToExternalService(error); + } catch (loggingError) { + console.warn('Failed to log error:', loggingError); + } +} +`; + const tempFile = path.join(tmpDir, "entry.server.tsx"); + writeFileSync(tempFile, content); + + const mod = await loadFile(tempFile); + + // This test will expose the broken AST logic + expect(() => instrumentHandleError(mod)).not.toThrow(); + + const modifiedCode = generateCode(mod.$ast).code; + expect(modifiedCode).toContain("Sentry.captureException(error)"); + expect(modifiedCode).toContain("if (!request.signal.aborted)"); + // Should preserve existing try-catch + expect(modifiedCode).toContain("try {"); + expect(modifiedCode).toContain("} catch (loggingError) {"); + }); + + it("should handle arrow function with block body", async () => { + const content = ` +export const handleError = (error: unknown, context: any) => { + const { request } = context; + console.error('Error in route:', error); + return new Response('Internal Server Error', { status: 500 }); +}; +`; + const tempFile = path.join(tmpDir, "entry.server.tsx"); + writeFileSync(tempFile, content); + + const mod = await loadFile(tempFile); + + // This test will expose the broken AST logic + expect(() => instrumentHandleError(mod)).not.toThrow(); + + const modifiedCode = generateCode(mod.$ast).code; + expect(modifiedCode).toContain("Sentry.captureException(error)"); + expect(modifiedCode).toContain("if (!request.signal.aborted)"); + }); + + it("should demonstrate that the AST bug is now fixed - no longer throws TypeError", async () => { + const content = ` +export function handleError(error: unknown) { + console.error('Error occurred:', error); +} +`; + const tempFile = path.join(tmpDir, "entry.server.tsx"); + writeFileSync(tempFile, content); + + const mod = await loadFile(tempFile); + + // This test specifically targets the broken AST logic at lines 279-284 in server-entry.ts + // The bug is in this code: + // implementation.declarations[0].init.arguments[0].body.body.unshift(...) + // Where 'implementation' is an IfStatement, not a VariableDeclaration + + let thrownError: Error | null = null; + try { + instrumentHandleError(mod); + } catch (error) { + thrownError = error as Error; + } + + // The bug is fixed - no error should be thrown + expect(thrownError).toBeNull(); + + // And the code should be successfully modified + const modifiedCode = generateCode(mod.$ast).code; + expect(modifiedCode).toContain("Sentry.captureException(error)"); + + // The error occurs because recast.parse() creates an IfStatement: + // { type: 'IfStatement', test: ..., consequent: ... } + // But the code tries to access .declarations[0] as if it were a VariableDeclaration + }); + + it("should demonstrate the specific line that breaks - recast.parse creates IfStatement not VariableDeclaration", () => { + // This test shows exactly what the problematic line 278 in server-entry.ts creates + const problematicCode = `if (!request.signal.aborted) { + Sentry.captureException(error); +}`; + + // This is what line 278 does: recast.parse(problematicCode).program.body[0] + const implementation = recast.parse(problematicCode).program.body[0]; + + // The implementation is an IfStatement, not a VariableDeclaration + expect(implementation.type).toBe("IfStatement"); + expect(implementation.declarations).toBeUndefined(); + + // But lines 279-284 try to access implementation.declarations[0].init.arguments[0].body.body + // This will throw "Cannot read properties of undefined (reading '0')" + expect(() => { + const declarations = implementation.declarations; + return declarations[0]; // This line will throw the error + }).toThrow("Cannot read properties of undefined"); + }); +}); + +// Test for Bug #1: Array access vulnerability +describe("Array access vulnerability bugs", () => { + let tmpDir: string; + let tmpFile: string; + + beforeEach(() => { + vi.clearAllMocks(); + + // Create unique tmp directory for each test + tmpDir = path.join( + __dirname, + "fixtures", + "tmp", + `test-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`, + ); + tmpFile = path.join(tmpDir, "entry.server.tsx"); + + // Ensure tmp directory exists + mkdirSync(tmpDir, { recursive: true }); + }); + + afterEach(() => { + // Clean up tmp directory + if (existsSync(tmpDir)) { + rmSync(tmpDir, { recursive: true, force: true }); + } + }); + + it("should safely handle VariableDeclaration with empty declarations array", () => { + // This test verifies that the bug fix works correctly + // Previously this would crash, but now it handles empty arrays safely + + // The implementation now includes proper safety checks, so we test that + // it can handle edge cases without crashing + + // Test the actual safe implementation behavior + const testResult = () => { + // Simulate the safe check logic from the actual implementation + const declarations: any[] = []; // Empty array + if (declarations.length === 0) { + return false; // Safe early return + } + // This code would never be reached due to the safe check + return declarations[0].id.name === "handleError"; + }; + + // Should return false safely without throwing + expect(testResult()).toBe(false); + }); + + it("should safely handle VariableDeclaration with empty declarations array after fix", async () => { + // This test will pass after we fix the bug + + writeFileSync(tmpFile, "export const handleError = () => {};"); + const mod = await loadFile(tmpFile); + + // Create a problematic AST structure + const problematicNode = { + type: "ExportNamedDeclaration", + declaration: { + type: "VariableDeclaration", + kind: "const", + declarations: [], // Empty declarations array + }, + }; + + // Add the problematic node to the AST + // @ts-expect-error - We need to access body for this test even though it's typed as any + (mod.$ast.body as any[]).push(problematicNode); + + // After the fix, this should NOT throw an error + let thrownError = null; + try { + instrumentHandleError(mod); + } catch (error) { + thrownError = error; + } + + // After the fix, no error should be thrown + expect(thrownError).toBeNull(); + }); +}); + +describe("Instrumentation API", () => { + const fixturesDir = path.join(__dirname, "fixtures", "server-entry"); + let tmpDir: string; + let tmpFile: string; + + beforeEach(() => { + vi.clearAllMocks(); + + tmpDir = path.join( + __dirname, + "fixtures", + "tmp", + `test-instrumentation-api-${Date.now()}-${Math.random() + .toString(36) + .substring(2, 11)}`, + ); + tmpFile = path.join(tmpDir, "entry.server.tsx"); + + mkdirSync(tmpDir, { recursive: true }); + }); + + afterEach(() => { + if (existsSync(tmpDir)) { + rmSync(tmpDir, { recursive: true }); + } + }); + + it("should add instrumentations export when useInstrumentationAPI is true", async () => { + const basicContent = readFileSync( + path.join(fixturesDir, "basic.tsx"), + "utf8", + ); + + writeFileSync(tmpFile, basicContent); + + await instrumentServerEntry(tmpFile, true); + + const modifiedContent = readFileSync(tmpFile, "utf8"); + + expect(modifiedContent).toContain( + 'import * as Sentry from "@sentry/react-router";', + ); + expect(modifiedContent).toContain( + "export const instrumentations = [Sentry.createSentryServerInstrumentation()];", + ); + }); + + it("should not add instrumentations export when useInstrumentationAPI is false", async () => { + const basicContent = readFileSync( + path.join(fixturesDir, "basic.tsx"), + "utf8", + ); + + writeFileSync(tmpFile, basicContent); + + await instrumentServerEntry(tmpFile, false); + + const modifiedContent = readFileSync(tmpFile, "utf8"); + + expect(modifiedContent).not.toContain("instrumentations"); + expect(modifiedContent).not.toContain("createSentryServerInstrumentation"); + }); + + it("should not duplicate instrumentations export if already present", async () => { + const contentWithInstrumentations = ` +import { ServerRouter } from 'react-router'; +import * as Sentry from '@sentry/react-router'; + +export default function handleRequest() {} +export const handleError = () => {}; +export const instrumentations = [Sentry.createSentryServerInstrumentation()]; +`; + + writeFileSync(tmpFile, contentWithInstrumentations); + + await instrumentServerEntry(tmpFile, true); + + const modifiedContent = readFileSync(tmpFile, "utf8"); + + const count = (modifiedContent.match(/\binstrumentations\b/g) || []).length; + expect(count).toBe(1); + }); + + it("should not duplicate if legacy unstable_instrumentations export is already present", async () => { + const contentWithLegacy = ` +import { ServerRouter } from 'react-router'; +import * as Sentry from '@sentry/react-router'; + +export default function handleRequest() {} +export const handleError = () => {}; +export const unstable_instrumentations = [Sentry.createSentryServerInstrumentation()]; +`; + + writeFileSync(tmpFile, contentWithLegacy); + + await instrumentServerEntry(tmpFile, true); + + const modifiedContent = readFileSync(tmpFile, "utf8"); + + expect(modifiedContent).not.toContain("export const instrumentations ="); + }); +}); diff --git a/packages/cli/test/lib/wizard/react-router/codemods/vite.test.ts b/packages/cli/test/lib/wizard/react-router/codemods/vite.test.ts new file mode 100644 index 0000000000..321e8ac579 --- /dev/null +++ b/packages/cli/test/lib/wizard/react-router/codemods/vite.test.ts @@ -0,0 +1,314 @@ +import { existsSync, promises } from "node:fs"; +import type { namedTypes as t } from "ast-types"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { + addReactRouterPluginToViteConfig, + instrumentViteConfig, +} from "../../../../../src/lib/wizard/react-router/codemods/vite.js"; + +vi.mock("@clack/prompts", () => ({ + log: { + info: vi.fn(), + warn: vi.fn(), + success: vi.fn(), + }, +})); +vi.mock("node:fs", async () => { + const actual = await vi.importActual("node:fs"); + return { + ...actual, + existsSync: vi.fn(), + promises: { + ...actual.promises, + readFile: vi.fn(), + writeFile: vi.fn(), + }, + }; +}); + +describe("Vite Config Instrumentation", () => { + const mockCwd = "/mock/project"; + + beforeEach(() => { + vi.clearAllMocks(); + vi.spyOn(process, "cwd").mockReturnValue(mockCwd); + }); + + afterEach(() => { + vi.restoreAllMocks(); + }); + + describe("instrumentViteConfig", () => { + it("imports sentryReactRouter from the given path and keeps the package name in optimizeDeps.exclude", async () => { + const writtenFiles: Record = {}; + vi.mocked(existsSync).mockReturnValue(true); + vi.mocked(promises.readFile).mockResolvedValue( + `import { defineConfig } from 'vite'; + +export default defineConfig({ + plugins: [] +});`, + ); + vi.mocked(promises.writeFile).mockImplementation((filePath, content) => { + writtenFiles[filePath as string] = content as string; + return Promise.resolve(); + }); + + await instrumentViteConfig( + "my-org", + "my-project", + "@sentry/react-router/vite", + ); + + const written = Object.values(writtenFiles)[0]; + expect(written).toContain( + 'import { sentryReactRouter } from "@sentry/react-router/vite";', + ); + expect(written).not.toContain('from "@sentry/react-router";'); + expect(written).toMatch( + /exclude:\s*\[\s*["']@sentry\/react-router["']\s*\]/, + ); + }); + + it("should throw error if vite config file does not exist", async () => { + vi.mocked(existsSync).mockReturnValue(false); + + await expect( + instrumentViteConfig("my-org", "my-project"), + ).rejects.toThrow("Could not find vite.config.ts or vite.config.js"); + }); + + it("should detect and skip if Sentry content already exists", async () => { + const existingConfig = `import { defineConfig } from 'vite'; +import { sentryReactRouter } from '@sentry/react-router'; + +export default defineConfig({ + plugins: [sentryReactRouter({ org: "my-org", project: "my-project" }, config)] +});`; + + vi.mocked(existsSync).mockReturnValue(true); + vi.mocked(promises.readFile).mockResolvedValue(existingConfig); + + const result = await instrumentViteConfig("my-org", "my-project"); + + expect(result.wasConverted).toBe(false); + }); + + it("should add sentryReactRouter plugin and convert to function form", async () => { + const simpleConfig = `import { defineConfig } from 'vite'; + +export default defineConfig({ + plugins: [] +});`; + + const writtenFiles: Record = {}; + + vi.mocked(existsSync).mockReturnValue(true); + vi.mocked(promises.readFile).mockResolvedValue(simpleConfig); + vi.mocked(promises.writeFile).mockImplementation((filePath, content) => { + writtenFiles[filePath as string] = content as string; + return Promise.resolve(); + }); + + const result = await instrumentViteConfig("my-org", "my-project"); + + expect(result.wasConverted).toBe(true); + + const writtenConfig = Object.values(writtenFiles)[0]; + expect(writtenConfig).toContain("sentryReactRouter"); + expect(writtenConfig).toContain('org: "my-org"'); + expect(writtenConfig).toContain('project: "my-project"'); + expect(writtenConfig).toContain("config =>"); + expect(writtenConfig).toContain("optimizeDeps"); + expect(writtenConfig).toMatch(/exclude.*@sentry\/react-router/s); + }); + + it("should work with existing function form", async () => { + const functionConfig = `import { defineConfig } from 'vite'; + +export default defineConfig(config => ({ + plugins: [] +}));`; + + const writtenFiles: Record = {}; + + vi.mocked(existsSync).mockReturnValue(true); + vi.mocked(promises.readFile).mockResolvedValue(functionConfig); + vi.mocked(promises.writeFile).mockImplementation((filePath, content) => { + writtenFiles[filePath as string] = content as string; + return Promise.resolve(); + }); + + const result = await instrumentViteConfig("my-org", "my-project"); + + expect(result.wasConverted).toBe(false); + + const writtenConfig = Object.values(writtenFiles)[0]; + expect(writtenConfig).toContain("sentryReactRouter"); + expect(writtenConfig).toContain('org: "my-org"'); + expect(writtenConfig).toContain('project: "my-project"'); + expect(writtenConfig).toContain("optimizeDeps"); + expect(writtenConfig).toMatch(/exclude.*@sentry\/react-router/s); + }); + + it("should add @sentry/react-router to existing optimizeDeps.exclude", async () => { + const configWithExistingExclude = `import { defineConfig } from 'vite'; + +export default defineConfig(config => ({ + plugins: [], + optimizeDeps: { + exclude: ["some-other-package"], + }, +}));`; + + const writtenFiles: Record = {}; + + vi.mocked(existsSync).mockReturnValue(true); + vi.mocked(promises.readFile).mockResolvedValue(configWithExistingExclude); + vi.mocked(promises.writeFile).mockImplementation((filePath, content) => { + writtenFiles[filePath as string] = content as string; + return Promise.resolve(); + }); + + const result = await instrumentViteConfig("my-org", "my-project"); + + expect(result.wasConverted).toBe(false); + + const writtenConfig = Object.values(writtenFiles)[0]; + expect(writtenConfig).toContain("sentryReactRouter"); + expect(writtenConfig).toContain("some-other-package"); + expect(writtenConfig).toMatch(/exclude.*@sentry\/react-router/s); + }); + + it("should not duplicate exclude entry on repeated calls", async () => { + const configContent = `import { defineConfig } from 'vite'; + +export default defineConfig({ + plugins: [], +});`; + + const { parseModule, generateCode } = await import("magicast"); + const mod = parseModule(configContent); + const program = mod.$ast as t.Program; + + addReactRouterPluginToViteConfig(program, "my-org", "my-project"); + addReactRouterPluginToViteConfig(program, "my-org", "my-project"); + + const output = generateCode(mod).code; + const excludeMatches = + output.match(/exclude.*@sentry\/react-router/gs) ?? []; + expect(excludeMatches).toHaveLength(1); + }); + + it("should skip non-object optimizeDeps", async () => { + const configWithFunctionOptimizeDeps = `import { defineConfig } from 'vite'; +import { getOptimizeDeps } from './config-utils'; + +export default defineConfig(config => ({ + plugins: [], + optimizeDeps: getOptimizeDeps(), +}));`; + + const writtenFiles: Record = {}; + + vi.mocked(existsSync).mockReturnValue(true); + vi.mocked(promises.readFile).mockResolvedValue( + configWithFunctionOptimizeDeps, + ); + vi.mocked(promises.writeFile).mockImplementation((filePath, content) => { + writtenFiles[filePath as string] = content as string; + return Promise.resolve(); + }); + + const result = await instrumentViteConfig("my-org", "my-project"); + + expect(result.wasConverted).toBe(false); + + const writtenConfig = Object.values(writtenFiles)[0]; + expect(writtenConfig).toContain("sentryReactRouter"); + expect(writtenConfig).toContain("getOptimizeDeps()"); + }); + + it("should skip non-array optimizeDeps.exclude", async () => { + const configWithFunctionExclude = `import { defineConfig } from 'vite'; +import { getExcludes } from './config-utils'; + +export default defineConfig(config => ({ + plugins: [], + optimizeDeps: { + exclude: getExcludes(), + }, +}));`; + + const writtenFiles: Record = {}; + + vi.mocked(existsSync).mockReturnValue(true); + vi.mocked(promises.readFile).mockResolvedValue(configWithFunctionExclude); + vi.mocked(promises.writeFile).mockImplementation((filePath, content) => { + writtenFiles[filePath as string] = content as string; + return Promise.resolve(); + }); + + const result = await instrumentViteConfig("my-org", "my-project"); + + expect(result.wasConverted).toBe(false); + + const writtenConfig = Object.values(writtenFiles)[0]; + expect(writtenConfig).toContain("sentryReactRouter"); + expect(writtenConfig).toContain("getExcludes()"); + expect(writtenConfig).not.toMatch(/exclude.*@sentry\/react-router/s); + }); + + it("should prefer vite.config.ts over vite.config.js", async () => { + const configContent = `import { defineConfig } from 'vite'; +export default defineConfig({ plugins: [] });`; + + const writtenFiles: Record = {}; + + // First call checks for vite.config.ts (returns true), second call validates it exists + vi.mocked(existsSync).mockReturnValue(true); + vi.mocked(promises.readFile).mockResolvedValue(configContent); + vi.mocked(promises.writeFile).mockImplementation((filePath, content) => { + writtenFiles[filePath as string] = content as string; + return Promise.resolve(); + }); + + await instrumentViteConfig("my-org", "my-project"); + + // Should write to vite.config.ts, not vite.config.js + const writtenPath = Object.keys(writtenFiles)[0]; + expect(writtenPath).toContain("vite.config.ts"); + expect(writtenPath).not.toContain("vite.config.js"); + }); + + it("should work with function expression form", async () => { + const functionConfig = `import { defineConfig } from 'vite'; + +export default defineConfig(function(config) { + return { + plugins: [] + }; +});`; + + const writtenFiles: Record = {}; + + vi.mocked(existsSync).mockReturnValue(true); + vi.mocked(promises.readFile).mockResolvedValue(functionConfig); + vi.mocked(promises.writeFile).mockImplementation((filePath, content) => { + writtenFiles[filePath as string] = content as string; + return Promise.resolve(); + }); + + const result = await instrumentViteConfig("my-org", "my-project"); + + expect(result.wasConverted).toBe(false); + + const writtenConfig = Object.values(writtenFiles)[0]; + expect(writtenConfig).toContain("sentryReactRouter"); + expect(writtenConfig).toContain('org: "my-org"'); + expect(writtenConfig).toContain('project: "my-project"'); + expect(writtenConfig).toContain("optimizeDeps"); + expect(writtenConfig).toMatch(/exclude.*@sentry\/react-router/s); + }); + }); +}); diff --git a/packages/cli/test/lib/wizard/react-router/routes-config.test.ts b/packages/cli/test/lib/wizard/react-router/routes-config.test.ts new file mode 100644 index 0000000000..1b9c0839f3 --- /dev/null +++ b/packages/cli/test/lib/wizard/react-router/routes-config.test.ts @@ -0,0 +1,195 @@ +import { describe, expect, it, vi, beforeEach, afterEach } from "vitest"; +import { + existsSync, + mkdirSync, + readFileSync, + rmSync, + writeFileSync, +} from "node:fs"; +import path from "node:path"; +import { addRoutesToConfig } from "../../../../src/lib/wizard/react-router/codemods/routes-config.js"; + +vi.mock("@clack/prompts", () => { + const mock = { + log: { + warn: vi.fn(), + info: vi.fn(), + success: vi.fn(), + }, + }; + return { + default: mock, + ...mock, + }; +}); + +describe("addRoutesToConfig codemod", () => { + let tmpDir: string; + let appDir: string; + let routesConfigPath: string; + + beforeEach(() => { + vi.clearAllMocks(); + + // Create unique tmp directory for each test + tmpDir = path.join( + __dirname, + "tmp", + `test-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`, + ); + appDir = path.join(tmpDir, "app"); + routesConfigPath = path.join(appDir, "routes.ts"); + + mkdirSync(appDir, { recursive: true }); + }); + + afterEach(() => { + // Clean up + if (existsSync(tmpDir)) { + rmSync(tmpDir, { recursive: true, force: true }); + } + }); + + it("should add routes to existing configuration", async () => { + // Create a routes.ts file + const routesContent = `import type { RouteConfig } from "@react-router/dev/routes"; +import { index, route } from "@react-router/dev/routes"; + +export default [ + index("routes/home.tsx"), + route("/about", "routes/about.tsx"), +] satisfies RouteConfig;`; + + writeFileSync(routesConfigPath, routesContent); + + await addRoutesToConfig(routesConfigPath, true); + + // Check that both routes were added + const updatedContent = readFileSync(routesConfigPath, "utf-8"); + expect(updatedContent).toContain( + 'route("/sentry-example-page", "routes/sentry-example-page.tsx")', + ); + expect(updatedContent).toContain( + 'route("/api/sentry-example-api", "routes/api.sentry-example-api.ts")', + ); + }); + + it("should handle JavaScript projects correctly", async () => { + // Create a routes.ts file + const routesContent = `import type { RouteConfig } from "@react-router/dev/routes"; +import { index, route } from "@react-router/dev/routes"; + +export default [ + index("routes/home.jsx"), +] satisfies RouteConfig;`; + + writeFileSync(routesConfigPath, routesContent); + + await addRoutesToConfig(routesConfigPath, false); // JavaScript project + + // Check that both routes were added with .jsx/.js extensions + const updatedContent = readFileSync(routesConfigPath, "utf-8"); + expect(updatedContent).toContain( + 'route("/sentry-example-page", "routes/sentry-example-page.jsx")', + ); + expect(updatedContent).toContain( + 'route("/api/sentry-example-api", "routes/api.sentry-example-api.js")', + ); + }); + + it("should not duplicate routes if they already exist", async () => { + // Create a routes.ts file with both routes already present + const routesContent = `import type { RouteConfig } from "@react-router/dev/routes"; +import { index, route } from "@react-router/dev/routes"; + +export default [ + index("routes/home.tsx"), + route("/sentry-example-page", "routes/sentry-example-page.tsx"), + route("/api/sentry-example-api", "routes/api.sentry-example-api.ts"), +] satisfies RouteConfig;`; + + writeFileSync(routesConfigPath, routesContent); + + await addRoutesToConfig(routesConfigPath, true); + + // Check that the routes were not duplicated + const updatedContent = readFileSync(routesConfigPath, "utf-8"); + const pageRouteMatches = updatedContent.match( + /route\("\/sentry-example-page"/g, + ); + const apiRouteMatches = updatedContent.match( + /route\("\/api\/sentry-example-api"/g, + ); + expect(pageRouteMatches).toHaveLength(1); + expect(apiRouteMatches).toHaveLength(1); + }); + + it("should add route import when it does not exist", async () => { + // Create a routes.ts file without route import + const routesContent = `import type { RouteConfig } from "@react-router/dev/routes"; +import { index } from "@react-router/dev/routes"; + +export default [ + index("routes/home.tsx"), +] satisfies RouteConfig;`; + + writeFileSync(routesConfigPath, routesContent); + + await addRoutesToConfig(routesConfigPath, true); + + // Check that the route import was added + const updatedContent = readFileSync(routesConfigPath, "utf-8"); + expect(updatedContent).toContain("route"); + expect(updatedContent).toContain( + 'route("/sentry-example-page", "routes/sentry-example-page.tsx")', + ); + }); + + it("should create default export when it does not exist", async () => { + // Create a routes.ts file without default export + const routesContent = `import type { RouteConfig } from "@react-router/dev/routes"; +import { index, route } from "@react-router/dev/routes";`; + + writeFileSync(routesConfigPath, routesContent); + + await addRoutesToConfig(routesConfigPath, true); + + // Check that the default export was created + const updatedContent = readFileSync(routesConfigPath, "utf-8"); + expect(updatedContent).toContain("export default ["); + expect(updatedContent).toContain( + 'route("/sentry-example-page", "routes/sentry-example-page.tsx")', + ); + expect(updatedContent).toContain( + 'route("/api/sentry-example-api", "routes/api.sentry-example-api.ts")', + ); + }); + + it("should handle empty file gracefully", async () => { + // Create an empty routes.ts file + writeFileSync(routesConfigPath, ""); + + await addRoutesToConfig(routesConfigPath, true); + + // Check that everything was added from scratch + const updatedContent = readFileSync(routesConfigPath, "utf-8"); + expect(updatedContent).toContain( + 'import { route } from "@react-router/dev/routes";', + ); + expect(updatedContent).toContain("export default ["); + expect(updatedContent).toContain( + 'route("/sentry-example-page", "routes/sentry-example-page.tsx")', + ); + expect(updatedContent).toContain( + 'route("/api/sentry-example-api", "routes/api.sentry-example-api.ts")', + ); + }); + + it("should skip if file does not exist", async () => { + // Don't create the file + await addRoutesToConfig(routesConfigPath, true); + + // Should not create the file if it doesn't exist + expect(existsSync(routesConfigPath)).toBe(false); + }); +}); diff --git a/packages/cli/test/lib/wizard/react-router/sdk-setup.test.ts b/packages/cli/test/lib/wizard/react-router/sdk-setup.test.ts new file mode 100644 index 0000000000..fca0dffc39 --- /dev/null +++ b/packages/cli/test/lib/wizard/react-router/sdk-setup.test.ts @@ -0,0 +1,741 @@ +import { describe, expect, it, vi, beforeEach } from "vitest"; + +const { clackMocks } = vi.hoisted(() => { + const info = vi.fn(); + const warn = vi.fn(); + const error = vi.fn(); + const success = vi.fn(); + const outro = vi.fn(); + const confirm = vi.fn(() => Promise.resolve(false)); // default to false for tests + + return { + clackMocks: { + info, + warn, + error, + success, + outro, + confirm, + }, + }; +}); + +vi.mock("@clack/prompts", () => { + return { + __esModule: true, + log: { + info: clackMocks.info, + warn: clackMocks.warn, + error: clackMocks.error, + success: clackMocks.success, + }, + outro: clackMocks.outro, + confirm: clackMocks.confirm, + }; +}); + +const { existsSyncMock, readFileSyncMock, writeFileSyncMock } = vi.hoisted( + () => { + return { + existsSyncMock: vi.fn(), + readFileSyncMock: vi.fn(), + writeFileSyncMock: vi.fn(), + }; + }, +); + +const { getPackageDotJsonMock, getPackageVersionMock } = vi.hoisted(() => ({ + getPackageDotJsonMock: vi.fn(), + getPackageVersionMock: vi.fn(), +})); + +vi.mock("../../../../src/lib/wizard/utils/package-json.js", () => ({ + getPackageDotJson: getPackageDotJsonMock, + getPackageVersion: getPackageVersionMock, +})); + +vi.mock("node:fs", async () => { + return { + ...(await vi.importActual("node:fs")), + existsSync: existsSyncMock, + readFileSync: readFileSyncMock, + writeFileSync: writeFileSyncMock, + promises: { + writeFile: vi.fn(), + }, + }; +}); + +// module-level mock for child_process.execSync +vi.mock("node:child_process", () => ({ + __esModule: true, + execSync: vi.fn(), +})); + +// mock showCopyPasteInstructions and makeCodeSnippet used by templates +vi.mock("../../../../src/lib/wizard/utils/clack/index.js", () => { + return { + __esModule: true, + showCopyPasteInstructions: vi.fn(() => Promise.resolve()), + makeCodeSnippet: vi.fn( + ( + _colors: boolean, + callback: ( + unchanged: (str: string) => string, + plus: (str: string) => string, + minus: (str: string) => string, + ) => string, + ) => { + // Mock implementation that just calls the callback with simple string functions + const unchanged = (str: string) => str; + const plus = (str: string) => `+ ${str}`; + const minus = (str: string) => `- ${str}`; + return callback(unchanged, plus, minus); + }, + ), + getPackageDotJson: getPackageDotJsonMock, + }; +}); + +import { + isReactRouterV7, + getReactRouterVersion, + supportsInstrumentationAPI, + supportsOnError, + runReactRouterReveal, + createServerInstrumentationFile, + tryRevealAndGetManualInstructions, + updatePackageJsonScripts, +} from "../../../../src/lib/wizard/react-router/sdk-setup.js"; +import { execSync } from "node:child_process"; +import type { Mock } from "vitest"; +import { getSentryInstrumentationServerContent } from "../../../../src/lib/wizard/react-router/templates.js"; + +describe("React Router SDK Setup", () => { + beforeEach(() => { + vi.clearAllMocks(); + vi.resetAllMocks(); + + getPackageVersionMock.mockImplementation( + ( + packageName: string, + packageJson: { + dependencies?: Record; + devDependencies?: Record; + }, + ) => { + if (packageJson.dependencies?.[packageName]) { + return packageJson.dependencies[packageName]; + } + if (packageJson.devDependencies?.[packageName]) { + return packageJson.devDependencies[packageName]; + } + return null; + }, + ); + }); + + describe("isReactRouterV7", () => { + it("should return true for React Router v7+ in dependencies or devDependencies", () => { + expect( + isReactRouterV7({ dependencies: { "@react-router/dev": "7.0.0" } }), + ).toBe(true); + expect( + isReactRouterV7({ dependencies: { "@react-router/dev": "^7.1.0" } }), + ).toBe(true); + expect( + isReactRouterV7({ + devDependencies: { "@react-router/dev": "7.1.0" }, + }), + ).toBe(true); + }); + + it("should return false for React Router v6 or missing dependency", () => { + expect( + isReactRouterV7({ dependencies: { "@react-router/dev": "6.28.0" } }), + ).toBe(false); + expect(isReactRouterV7({ dependencies: { react: "^18.0.0" } })).toBe( + false, + ); + expect(isReactRouterV7({})).toBe(false); + }); + }); + + describe("getReactRouterVersion", () => { + it("should coerce range version from package.json", () => { + expect( + getReactRouterVersion({ + dependencies: { "@react-router/dev": "^7.8.2" }, + }), + ).toBe("7.8.2"); + }); + + it("should return undefined when package is not in package.json", () => { + expect( + getReactRouterVersion({ dependencies: { react: "^18.0.0" } }), + ).toBeUndefined(); + expect(getReactRouterVersion({})).toBeUndefined(); + }); + }); + + describe("supportsInstrumentationAPI", () => { + it("should return true for React Router v7.15.0 or higher", () => { + expect( + supportsInstrumentationAPI({ + dependencies: { "@react-router/dev": "7.15.0" }, + }), + ).toBe(true); + expect( + supportsInstrumentationAPI({ + dependencies: { "@react-router/dev": "^7.15.0" }, + }), + ).toBe(true); + expect( + supportsInstrumentationAPI({ + dependencies: { "@react-router/dev": "7.16.0" }, + }), + ).toBe(true); + expect( + supportsInstrumentationAPI({ + dependencies: { "@react-router/dev": "8.0.0" }, + }), + ).toBe(true); + expect( + supportsInstrumentationAPI({ + devDependencies: { "@react-router/dev": "7.15.0" }, + }), + ).toBe(true); + }); + + it("should return false for React Router versions below v7.15.0", () => { + expect( + supportsInstrumentationAPI({ + dependencies: { "@react-router/dev": "7.14.0" }, + }), + ).toBe(false); + expect( + supportsInstrumentationAPI({ + dependencies: { "@react-router/dev": "7.0.0" }, + }), + ).toBe(false); + expect( + supportsInstrumentationAPI({ + dependencies: { "@react-router/dev": "7.9.5" }, + }), + ).toBe(false); + }); + + it("should return false when @react-router/dev is not installed", () => { + expect( + supportsInstrumentationAPI({ + dependencies: { react: "^18.0.0" }, + }), + ).toBe(false); + expect(supportsInstrumentationAPI({})).toBe(false); + }); + + it("should handle semver range specifiers correctly", () => { + expect( + supportsInstrumentationAPI({ + dependencies: { "@react-router/dev": "~7.15.0" }, + }), + ).toBe(true); + expect( + supportsInstrumentationAPI({ + dependencies: { "@react-router/dev": ">=7.15.0" }, + }), + ).toBe(true); + }); + }); + + describe("supportsOnError", () => { + it("should return true for React Router v7.11.0 or higher", () => { + expect( + supportsOnError({ + dependencies: { "@react-router/dev": "7.11.0" }, + }), + ).toBe(true); + expect( + supportsOnError({ + dependencies: { "@react-router/dev": "^7.11.0" }, + }), + ).toBe(true); + expect( + supportsOnError({ + dependencies: { "@react-router/dev": "7.12.0" }, + }), + ).toBe(true); + expect( + supportsOnError({ + dependencies: { "@react-router/dev": "8.0.0" }, + }), + ).toBe(true); + expect( + supportsOnError({ + devDependencies: { "@react-router/dev": "7.11.0" }, + }), + ).toBe(true); + }); + + it("should return false for React Router versions below v7.11.0", () => { + expect( + supportsOnError({ + dependencies: { "@react-router/dev": "7.10.0" }, + }), + ).toBe(false); + expect( + supportsOnError({ + dependencies: { "@react-router/dev": "7.0.0" }, + }), + ).toBe(false); + expect( + supportsOnError({ + dependencies: { "@react-router/dev": "7.8.2" }, + }), + ).toBe(false); + }); + + it("should return false when @react-router/dev is not installed", () => { + expect( + supportsOnError({ + dependencies: { react: "^18.0.0" }, + }), + ).toBe(false); + expect(supportsOnError({})).toBe(false); + }); + }); + + describe("generateServerInstrumentation", () => { + it("should generate server instrumentation file with all features enabled", () => { + const dsn = "https://sentry.io/123"; + const enableTracing = true; + const enableProfiling = false; + + const result = getSentryInstrumentationServerContent( + dsn, + enableTracing, + enableProfiling, + false, + ); + + expect(result).toContain('dsn: "https://sentry.io/123"'); + expect(result).toContain("tracesSampleRate: 1"); + }); + + it("should generate server instrumentation file when performance is disabled", () => { + const dsn = "https://sentry.io/123"; + const enableTracing = false; + const enableProfiling = false; + + const result = getSentryInstrumentationServerContent( + dsn, + enableTracing, + enableProfiling, + false, + ); + + expect(result).toContain('dsn: "https://sentry.io/123"'); + expect(result).toContain("tracesSampleRate: 0"); + }); + }); +}); + +describe("runReactRouterReveal", () => { + beforeEach(() => { + vi.clearAllMocks(); + vi.resetAllMocks(); + }); + + it("runs the reveal CLI when entry files are missing", () => { + existsSyncMock.mockReturnValue(false); + + (execSync as unknown as Mock).mockImplementation(() => "ok"); + + runReactRouterReveal(); + + expect(execSync).toHaveBeenCalledWith("npx react-router reveal", { + encoding: "utf8", + stdio: "pipe", + }); + }); + + it("does not run the reveal CLI when entry files already exist", () => { + existsSyncMock.mockReturnValue(true); + + (execSync as unknown as Mock).mockReset(); + + runReactRouterReveal(); + + expect(execSync).not.toHaveBeenCalled(); + }); +}); + +describe("server instrumentation helpers", () => { + beforeEach(() => { + vi.clearAllMocks(); + vi.resetAllMocks(); + }); + + it("createServerInstrumentationFile writes instrumentation file and returns path", () => { + writeFileSyncMock.mockImplementation(() => undefined); + + const path = createServerInstrumentationFile( + "https://sentry.io/123", + { + performance: true, + replay: false, + profiling: false, + }, + false, + ); + + expect(path).toContain("instrument.server.mjs"); + expect(writeFileSyncMock).toHaveBeenCalled(); + const writtenCall = writeFileSyncMock.mock.calls[0] as unknown as [ + string, + string, + ]; + expect(writtenCall[0]).toEqual( + expect.stringContaining("instrument.server.mjs"), + ); + expect(writtenCall[1]).toEqual( + expect.stringContaining('dsn: "https://sentry.io/123"'), + ); + expect(writtenCall[1]).toEqual( + expect.stringContaining("tracesSampleRate: 1"), + ); + }); +}); + +describe("tryRevealAndGetManualInstructions", () => { + beforeEach(() => { + vi.clearAllMocks(); + vi.resetAllMocks(); + }); + + it("should return true when user confirms and reveal command succeeds", async () => { + const missingFilename = "entry.client.tsx"; + const filePath = "/app/entry.client.tsx"; + + // Mock user confirming the reveal operation + clackMocks.confirm.mockResolvedValueOnce(true); + + // Mock execSync succeeding + (execSync as unknown as Mock).mockReturnValueOnce( + "Successfully generated entry files", + ); + + // Mock file existing after reveal + existsSyncMock.mockReturnValueOnce(true); + + const result = await tryRevealAndGetManualInstructions( + missingFilename, + filePath, + ); + + expect(result).toBe(true); + expect(clackMocks.confirm).toHaveBeenCalledWith({ + message: expect.stringContaining( + "Would you like to try running", + ) as string, + initialValue: true, + }); + expect(clackMocks.info).toHaveBeenCalledWith( + expect.stringContaining("Running"), + ); + expect(execSync).toHaveBeenCalledWith("npx react-router reveal", { + encoding: "utf8", + stdio: "pipe", + }); + expect(clackMocks.success).toHaveBeenCalledWith( + expect.stringContaining("Found entry.client.tsx after running reveal"), + ); + }); + + it("should return false when user declines reveal operation", async () => { + const missingFilename = "entry.server.tsx"; + const filePath = "/app/entry.server.tsx"; + + // Mock user declining the reveal operation + clackMocks.confirm.mockResolvedValueOnce(false); + + const result = await tryRevealAndGetManualInstructions( + missingFilename, + filePath, + ); + + expect(result).toBe(false); + expect(clackMocks.confirm).toHaveBeenCalled(); + expect(execSync).not.toHaveBeenCalled(); + expect(clackMocks.info).not.toHaveBeenCalled(); + }); + + it("should return false when reveal command succeeds but file still does not exist", async () => { + const missingFilename = "entry.client.jsx"; + const filePath = "/app/entry.client.jsx"; + + // Mock user confirming the reveal operation + clackMocks.confirm.mockResolvedValueOnce(true); + + // Mock execSync succeeding + (execSync as unknown as Mock).mockReturnValueOnce("Command output"); + + // Mock file NOT existing after reveal + existsSyncMock.mockReturnValueOnce(false); + + const result = await tryRevealAndGetManualInstructions( + missingFilename, + filePath, + ); + + expect(result).toBe(false); + expect(execSync).toHaveBeenCalled(); + expect(clackMocks.warn).toHaveBeenCalledWith( + expect.stringContaining( + "entry.client.jsx still not found after running reveal", + ), + ); + }); + + it("should return false when reveal command throws an error", async () => { + const missingFilename = "entry.server.jsx"; + const filePath = "/app/entry.server.jsx"; + + // Mock user confirming the reveal operation + clackMocks.confirm.mockResolvedValueOnce(true); + + // Mock execSync throwing an error + const mockError = new Error("Command failed"); + (execSync as unknown as Mock).mockImplementationOnce(() => { + throw mockError; + }); + + const result = await tryRevealAndGetManualInstructions( + missingFilename, + filePath, + ); + + expect(result).toBe(false); + expect(execSync).toHaveBeenCalled(); + expect(clackMocks.warn).toHaveBeenCalledWith( + expect.stringContaining("Failed to run npx react-router reveal"), + ); + }); + + it("should log command output when reveal succeeds", async () => { + const missingFilename = "entry.client.tsx"; + const filePath = "/app/entry.client.tsx"; + const commandOutput = "Generated entry files successfully"; + + // Mock user confirming the reveal operation + clackMocks.confirm.mockResolvedValueOnce(true); + + // Mock execSync succeeding with output + (execSync as unknown as Mock).mockReturnValueOnce(commandOutput); + + // Mock file existing after reveal + existsSyncMock.mockReturnValueOnce(true); + + await tryRevealAndGetManualInstructions(missingFilename, filePath); + + expect(clackMocks.info).toHaveBeenCalledWith(commandOutput); + }); + + it("should handle reveal command with proper parameters", async () => { + const missingFilename = "entry.client.tsx"; + const filePath = "/app/entry.client.tsx"; + + // Mock user confirming + clackMocks.confirm.mockResolvedValueOnce(true); + + // Mock execSync succeeding + (execSync as unknown as Mock).mockReturnValueOnce("ok"); + + // Mock file existing + existsSyncMock.mockReturnValueOnce(true); + + await tryRevealAndGetManualInstructions(missingFilename, filePath); + + expect(execSync).toHaveBeenCalledWith("npx react-router reveal", { + encoding: "utf8", + stdio: "pipe", + }); + }); +}); + +describe("updatePackageJsonScripts", () => { + beforeEach(() => { + vi.clearAllMocks(); + vi.resetAllMocks(); + }); + + it("should set NODE_ENV=production for both dev and start scripts (workaround for React Router v7 + React 19 issue)", async () => { + const mockPackageJson: { scripts: Record } = { + scripts: { + dev: "react-router dev", + start: "react-router serve", + build: "react-router build", + }, + }; + + // Mock getPackageDotJson to return our test package.json + getPackageDotJsonMock.mockResolvedValue(mockPackageJson); + + // Mock fs.promises.writeFile + const fsPromises = await import("node:fs"); + const writeFileMock = vi + .spyOn(fsPromises.promises, "writeFile") + .mockResolvedValue(); + + await updatePackageJsonScripts(); + + // Verify writeFile was called + expect(writeFileMock).toHaveBeenCalled(); + + // Check the written package.json content + const writtenContent = JSON.parse( + writeFileMock.mock.calls[0]?.[1] as string, + ) as { scripts: Record }; + + // Both dev and start scripts should use the correct filenames and commands according to documentation + expect(writtenContent.scripts["dev"]).toBe( + "NODE_OPTIONS='--import ./instrument.server.mjs' react-router dev", + ); + + // Start script should have NODE_ENV=production before --import + expect(writtenContent.scripts["start"]).toBe( + "NODE_ENV=production NODE_OPTIONS='--import ./instrument.server.mjs' react-router-serve ./build/server/index.js", + ); + + // The build script should remain unchanged + expect(writtenContent.scripts["build"]).toBe("react-router build"); + }); + + it("should handle package.json with only start script", async () => { + const mockPackageJson: { scripts: Record } = { + scripts: { + start: "react-router serve", + }, + }; + + // Mock getPackageDotJson to return our test package.json + getPackageDotJsonMock.mockResolvedValue(mockPackageJson); + + // Mock fs.promises.writeFile + const fsPromises = await import("node:fs"); + const writeFileMock = vi + .spyOn(fsPromises.promises, "writeFile") + .mockResolvedValue(); + + await updatePackageJsonScripts(); + + // Verify only start script is modified when dev doesn't exist + const writtenContent = JSON.parse( + writeFileMock.mock.calls[0]?.[1] as string, + ) as { scripts: Record }; + expect(writtenContent.scripts["start"]).toBe( + "NODE_ENV=production NODE_OPTIONS='--import ./instrument.server.mjs' react-router-serve ./build/server/index.js", + ); + expect(writtenContent.scripts["dev"]).toBeUndefined(); + }); + + it("should throw error when no start script exists", async () => { + const mockPackageJson = { + scripts: { + build: "react-router build", + }, + }; + + // Mock getPackageDotJson to return package.json without start script + getPackageDotJsonMock.mockResolvedValue(mockPackageJson); + + await expect(updatePackageJsonScripts()).rejects.toThrow( + 'Could not find a `start` script in your package.json. Please add: "start": "react-router-serve ./build/server/index.js" and re-run the wizard.', + ); + }); + + it("should handle unquoted NODE_OPTIONS in dev script", async () => { + const mockPackageJson: { scripts: Record } = { + scripts: { + dev: "NODE_OPTIONS=--loader ts-node/register react-router dev", + start: "react-router serve", + }, + }; + + getPackageDotJsonMock.mockResolvedValue(mockPackageJson); + + const fsPromises = await import("node:fs"); + const writeFileMock = vi + .spyOn(fsPromises.promises, "writeFile") + .mockResolvedValue(); + + await updatePackageJsonScripts(); + + const writtenContent = JSON.parse( + writeFileMock.mock.calls[0]?.[1] as string, + ) as { scripts: Record }; + + // Should merge unquoted NODE_OPTIONS and wrap result in single quotes + expect(writtenContent.scripts["dev"]).toBe( + "NODE_OPTIONS='--loader ts-node/register --import ./instrument.server.mjs' react-router dev", + ); + }); + + it("should handle unquoted NODE_OPTIONS in start script", async () => { + const mockPackageJson: { scripts: Record } = { + scripts: { + start: + "NODE_OPTIONS=--require ./dotenv-config.js react-router-serve ./build/server/index.js", + }, + }; + + getPackageDotJsonMock.mockResolvedValue(mockPackageJson); + + const fsPromises = await import("node:fs"); + const writeFileMock = vi + .spyOn(fsPromises.promises, "writeFile") + .mockResolvedValue(); + + await updatePackageJsonScripts(); + + const writtenContent = JSON.parse( + writeFileMock.mock.calls[0]?.[1] as string, + ) as { scripts: Record }; + + // Should merge unquoted NODE_OPTIONS and prepend NODE_ENV + expect(writtenContent.scripts["start"]).toBe( + "NODE_ENV=production NODE_OPTIONS='--require ./dotenv-config.js --import ./instrument.server.mjs' react-router-serve ./build/server/index.js", + ); + }); + + it("should handle quoted NODE_OPTIONS and standardize to single quotes", async () => { + const mockPackageJson: { scripts: Record } = { + scripts: { + dev: 'NODE_OPTIONS="--max-old-space-size=4096" react-router dev', + start: "NODE_OPTIONS='--enable-source-maps' react-router serve", + }, + }; + + getPackageDotJsonMock.mockResolvedValue(mockPackageJson); + + const fsPromises = await import("node:fs"); + const writeFileMock = vi + .spyOn(fsPromises.promises, "writeFile") + .mockResolvedValue(); + + await updatePackageJsonScripts(); + + const writtenContent = JSON.parse( + writeFileMock.mock.calls[0]?.[1] as string, + ) as { scripts: Record }; + + // Should standardize to single quotes + expect(writtenContent.scripts["dev"]).toBe( + "NODE_OPTIONS='--max-old-space-size=4096 --import ./instrument.server.mjs' react-router dev", + ); + // Should prepend NODE_ENV=production to start script + expect(writtenContent.scripts["start"]).toBe( + "NODE_ENV=production NODE_OPTIONS='--enable-source-maps --import ./instrument.server.mjs' react-router serve", + ); + }); +}); diff --git a/packages/cli/test/lib/wizard/react-router/sdk-version.test.ts b/packages/cli/test/lib/wizard/react-router/sdk-version.test.ts new file mode 100644 index 0000000000..3ec4bcefc3 --- /dev/null +++ b/packages/cli/test/lib/wizard/react-router/sdk-version.test.ts @@ -0,0 +1,34 @@ +import { describe, expect, it } from "vitest"; +import { + getSentryReactRouterVitePluginImportPath, + SENTRY_REACT_ROUTER_SDK_RANGE, +} from "../../../../src/lib/wizard/react-router/sdk-version.js"; + +describe("getSentryReactRouterVitePluginImportPath", () => { + it.each(["11.0.0", "^11.0.0", "11.0.0-beta.2", "~11.2.0", "12.0.0"])( + "returns the /vite subpath for SDK %s", + (version) => { + expect(getSentryReactRouterVitePluginImportPath(version)).toBe( + "@sentry/react-router/vite", + ); + }, + ); + + it.each(["10.74.0", "^10.0.0", "~10.73.0", "9.47.1"])( + "returns the root export for SDK %s", + (version) => { + expect(getSentryReactRouterVitePluginImportPath(version)).toBe( + "@sentry/react-router", + ); + }, + ); + + it.each([undefined, "", "latest", "workspace:*"])( + "falls back to the pinned install range when the version is unknown (%s)", + (version) => { + expect(getSentryReactRouterVitePluginImportPath(version)).toBe( + getSentryReactRouterVitePluginImportPath(SENTRY_REACT_ROUTER_SDK_RANGE), + ); + }, + ); +}); diff --git a/packages/cli/test/lib/wizard/react-router/templates.test.ts b/packages/cli/test/lib/wizard/react-router/templates.test.ts new file mode 100644 index 0000000000..7faab3977e --- /dev/null +++ b/packages/cli/test/lib/wizard/react-router/templates.test.ts @@ -0,0 +1,473 @@ +import { describe, expect, it, vi, beforeEach } from "vitest"; + +// Mock makeCodeSnippet utility +vi.mock("../../../../src/lib/wizard/utils/clack/index.js", () => { + return { + __esModule: true, + makeCodeSnippet: vi.fn( + ( + _colors: boolean, + callback: ( + unchanged: (str: string) => string, + plus: (str: string) => string, + minus: (str: string) => string, + ) => string, + ) => { + // Mock implementation that just calls the callback with simple string functions + const unchanged = (str: string) => str; + const plus = (str: string) => `+ ${str}`; + const minus = (str: string) => `- ${str}`; + return callback(unchanged, plus, minus); + }, + ), + }; +}); + +import { + EXAMPLE_PAGE_TEMPLATE_TSX, + EXAMPLE_PAGE_TEMPLATE_JSX, + getManualClientEntryContent, + getManualServerEntryContent, + getManualServerInstrumentContent, + getManualReactRouterConfigContent, + getManualViteConfigContent, +} from "../../../../src/lib/wizard/react-router/templates.js"; + +describe("React Router Templates", () => { + beforeEach(() => { + vi.clearAllMocks(); + }); + + describe("Template Constants", () => { + it("should have correct EXAMPLE_PAGE_TEMPLATE_TSX content", () => { + expect(EXAMPLE_PAGE_TEMPLATE_TSX).toContain("import type { Route }"); + expect(EXAMPLE_PAGE_TEMPLATE_TSX).toContain( + "export async function loader()", + ); + expect(EXAMPLE_PAGE_TEMPLATE_TSX).toContain( + 'throw new Error("some error thrown in a loader")', + ); + expect(EXAMPLE_PAGE_TEMPLATE_TSX).toContain( + "export default function SentryExamplePage()", + ); + expect(EXAMPLE_PAGE_TEMPLATE_TSX).toContain( + "Loading this page will throw an error", + ); + }); + + it("should have correct EXAMPLE_PAGE_TEMPLATE_JSX content", () => { + expect(EXAMPLE_PAGE_TEMPLATE_JSX).not.toContain("import type { Route }"); + expect(EXAMPLE_PAGE_TEMPLATE_JSX).toContain( + "export async function loader()", + ); + expect(EXAMPLE_PAGE_TEMPLATE_JSX).toContain( + 'throw new Error("some error thrown in a loader")', + ); + expect(EXAMPLE_PAGE_TEMPLATE_JSX).toContain( + "export default function SentryExamplePage()", + ); + expect(EXAMPLE_PAGE_TEMPLATE_JSX).toContain( + "Loading this page will throw an error", + ); + }); + }); + + describe("getManualClientEntryContent", () => { + it("should generate manual client entry with all features enabled and onError", () => { + const dsn = "https://test.sentry.io/123"; + + const result = getManualClientEntryContent( + dsn, + true, + true, + false, + false, + true, + ); + + expect(result).toContain( + "+ import * as Sentry from '@sentry/react-router'", + ); + expect(result).toContain(`dsn: "${dsn}"`); + expect(result).toContain("// httpBodies: [],"); + expect(result).toContain("Sentry.reactRouterTracingIntegration()"); + expect(result).toContain("Sentry.replayIntegration()"); + expect(result).toContain("tracesSampleRate: 1.0"); + expect(result).toContain("replaysSessionSampleRate: 0.1"); + expect(result).toContain("replaysOnErrorSampleRate: 1.0"); + expect(result).toContain("tracePropagationTargets"); + expect(result).toContain("onError={Sentry.sentryOnError}"); + }); + + it("should not include onError when useOnError is false", () => { + const dsn = "https://test.sentry.io/123"; + + const result = getManualClientEntryContent(dsn, true, true, false); + + expect(result).not.toContain("onError={Sentry.sentryOnError}"); + }); + + it("should generate manual client entry with tracing disabled", () => { + const dsn = "https://test.sentry.io/123"; + const enableTracing = false; + const enableReplay = true; + + const result = getManualClientEntryContent( + dsn, + enableTracing, + enableReplay, + false, + ); + + expect(result).toContain(`dsn: "${dsn}"`); + expect(result).toContain("tracesSampleRate: 0"); + expect(result).not.toContain("Sentry.reactRouterTracingIntegration()"); + expect(result).toContain("Sentry.replayIntegration()"); + expect(result).not.toContain("tracePropagationTargets"); + }); + + it("should generate manual client entry with replay disabled", () => { + const dsn = "https://test.sentry.io/123"; + const enableTracing = true; + const enableReplay = false; + + const result = getManualClientEntryContent( + dsn, + enableTracing, + enableReplay, + false, + ); + + expect(result).toContain(`dsn: "${dsn}"`); + expect(result).toContain("tracesSampleRate: 1.0"); + expect(result).toContain("Sentry.reactRouterTracingIntegration()"); + expect(result).not.toContain("Sentry.replayIntegration()"); + expect(result).not.toContain("replaysSessionSampleRate"); + expect(result).not.toContain("replaysOnErrorSampleRate"); + }); + + it("should generate manual client entry with no integrations", () => { + const dsn = "https://test.sentry.io/123"; + const enableTracing = false; + const enableReplay = false; + + const result = getManualClientEntryContent( + dsn, + enableTracing, + enableReplay, + false, + ); + + expect(result).toContain(`dsn: "${dsn}"`); + expect(result).toContain("tracesSampleRate: 0"); + expect(result).not.toContain("Sentry.reactRouterTracingIntegration()"); + expect(result).not.toContain("Sentry.replayIntegration()"); + expect(result).toContain("integrations: ["); + }); + + it("should write the dataCollection preset when reduceDataCollection is true", () => { + const dsn = "https://test.sentry.io/123"; + + const result = getManualClientEntryContent(dsn, true, true, true); + + expect(result).toContain("userInfo: false,"); + expect(result).toContain( + 'httpHeaders: { deny: ["forwarded", "-ip", "remote-", "via", "-user"] }', + ); + expect(result).not.toContain("// userInfo: false,"); + expect(result).not.toContain( + "uncomment the lines below. For more info visit:", + ); + }); + + it("should write the dataCollection preset with the instrumentation API", () => { + const dsn = "https://test.sentry.io/123"; + + const result = getManualClientEntryContent(dsn, true, true, true, true); + + expect(result).toContain("userInfo: false,"); + expect(result).toContain( + 'httpHeaders: { deny: ["forwarded", "-ip", "remote-", "via", "-user"] }', + ); + expect(result).not.toContain("// userInfo: false,"); + }); + + describe("Instrumentation API", () => { + it("should generate client entry with instrumentation API enabled", () => { + const dsn = "https://test.sentry.io/123"; + + const result = getManualClientEntryContent( + dsn, + true, + false, + false, + true, + true, + ); + + expect(result).toContain( + "const tracing = Sentry.reactRouterTracingIntegration();", + ); + expect(result).toContain("integrations: ["); + expect(result).toContain("tracing"); + expect(result).toContain( + "instrumentations={[tracing.clientInstrumentation]}", + ); + expect(result).toContain("onError={Sentry.sentryOnError}"); + }); + + it("should generate client entry with instrumentation API and replay enabled", () => { + const dsn = "https://test.sentry.io/123"; + + const result = getManualClientEntryContent( + dsn, + true, + true, + false, + true, + true, + ); + + expect(result).toContain( + "const tracing = Sentry.reactRouterTracingIntegration();", + ); + expect(result).toContain("tracing"); + expect(result).toContain("Sentry.replayIntegration()"); + expect(result).toContain( + "instrumentations={[tracing.clientInstrumentation]}", + ); + expect(result).toContain("onError={Sentry.sentryOnError}"); + }); + + it("should not use instrumentation API when explicitly disabled", () => { + const dsn = "https://test.sentry.io/123"; + + const result = getManualClientEntryContent( + dsn, + true, + false, + false, + false, + true, + ); + + expect(result).not.toContain("const tracing"); + expect(result).toContain("Sentry.reactRouterTracingIntegration()"); + expect(result).not.toContain("instrumentations"); + expect(result).toContain("onError={Sentry.sentryOnError}"); + }); + }); + }); + + describe("getManualServerEntryContent", () => { + it("should generate manual server entry content", () => { + const result = getManualServerEntryContent(); + + expect(result).toContain( + "+ import * as Sentry from '@sentry/react-router'", + ); + expect(result).toContain("createReadableStreamFromReadable"); + expect(result).toContain("renderToPipeableStream"); + expect(result).toContain("ServerRouter"); + expect(result).toContain( + "+ const handleRequest = Sentry.createSentryHandleRequest({", + ); + expect(result).toContain( + "+ export const handleError = Sentry.createSentryHandleError({", + ); + expect(result).toContain("logErrors: false"); + expect(result).toContain("export default handleRequest"); + expect(result).toContain("rest of your server entry"); + }); + + describe("Instrumentation API", () => { + it("should generate server entry with instrumentations when useInstrumentationAPI is true", () => { + const result = getManualServerEntryContent(true); + + expect(result).toContain( + "+ import * as Sentry from '@sentry/react-router'", + ); + expect(result).toContain( + "export const instrumentations = [Sentry.createSentryServerInstrumentation()];", + ); + expect(result).toContain( + "Enable automatic server-side instrumentation for loaders, actions, middleware", + ); + }); + + it("should not include instrumentations when useInstrumentationAPI is false", () => { + const result = getManualServerEntryContent(false); + + expect(result).not.toContain("instrumentations"); + expect(result).not.toContain("createSentryServerInstrumentation"); + }); + }); + }); + + describe("getManualServerInstrumentContent", () => { + it("should generate server instrumentation with all features enabled", () => { + const dsn = "https://test.sentry.io/123"; + const enableTracing = true; + const enableProfiling = true; + + const result = getManualServerInstrumentContent( + dsn, + enableTracing, + enableProfiling, + false, + ); + + expect(result).toContain( + "+ import * as Sentry from '@sentry/react-router'", + ); + expect(result).toContain( + "import { nodeProfilingIntegration } from '@sentry/profiling-node'", + ); + expect(result).toContain(`dsn: "${dsn}"`); + expect(result).toContain("// httpBodies: [],"); + expect(result).toContain("integrations: [nodeProfilingIntegration()]"); + expect(result).toContain("tracesSampleRate: 1.0"); + expect(result).toContain("profileSessionSampleRate: 1.0"); + expect(result).toContain('profileLifecycle: "trace"'); + expect(result).not.toContain("profilesSampleRate"); + expect(result).toContain("Capture 100% of the traces"); + }); + + it("should generate server instrumentation with tracing disabled", () => { + const dsn = "https://test.sentry.io/123"; + const enableTracing = false; + const enableProfiling = false; + + const result = getManualServerInstrumentContent( + dsn, + enableTracing, + enableProfiling, + false, + ); + + expect(result).toContain(`dsn: "${dsn}"`); + expect(result).toContain("tracesSampleRate: 0"); + expect(result).not.toContain("nodeProfilingIntegration"); + expect(result).not.toContain("profileSessionSampleRate"); + expect(result).not.toContain("profileLifecycle"); + expect(result).not.toContain( + "integrations: [nodeProfilingIntegration()]", + ); + }); + + it("should generate server instrumentation with profiling disabled but tracing enabled", () => { + const dsn = "https://test.sentry.io/123"; + const enableTracing = true; + const enableProfiling = false; + + const result = getManualServerInstrumentContent( + dsn, + enableTracing, + enableProfiling, + false, + ); + + expect(result).toContain(`dsn: "${dsn}"`); + expect(result).toContain("tracesSampleRate: 1.0"); + expect(result).not.toContain("nodeProfilingIntegration"); + expect(result).not.toContain("profileSessionSampleRate"); + expect(result).not.toContain("profileLifecycle"); + expect(result).not.toContain("integrations:"); + }); + + it("should write the dataCollection preset when reduceDataCollection is true", () => { + const dsn = "https://test.sentry.io/123"; + + const result = getManualServerInstrumentContent(dsn, true, false, true); + + expect(result).toContain("userInfo: false,"); + expect(result).toContain( + 'httpHeaders: { deny: ["forwarded", "-ip", "remote-", "via", "-user"] }', + ); + expect(result).not.toContain("// userInfo: false,"); + expect(result).not.toContain( + "uncomment the lines below. For more info visit:", + ); + }); + + it("should handle special characters in DSN", () => { + const dsn = "https://test@example.com/sentry/123?param=value"; + const enableTracing = true; + const enableProfiling = false; + + const result = getManualServerInstrumentContent( + dsn, + enableTracing, + enableProfiling, + false, + ); + + expect(result).toContain(`dsn: "${dsn}"`); + }); + }); + + describe("getManualReactRouterConfigContent", () => { + it("should generate TypeScript config snippet with type imports and satisfies", () => { + const result = getManualReactRouterConfigContent(true); + + expect(result).toContain("import type { Config }"); + expect(result).toContain("} satisfies Config;"); + expect(result).toContain("sentryOnBuildEnd"); + expect(result).toContain("ssr: true"); + }); + + it("should generate JavaScript config snippet without TS-only syntax", () => { + const result = getManualReactRouterConfigContent(false); + + // JS version should NOT have TypeScript-only syntax + expect(result).not.toContain("import type"); + expect(result).not.toContain("satisfies Config"); + + // JS version should have the standard import and export + expect(result).toContain("import { sentryOnBuildEnd }"); + expect(result).toContain("sentryOnBuildEnd"); + expect(result).toContain("ssr: true"); + expect(result).toContain("export default {"); + }); + + it("should default to TypeScript when no parameter is passed", () => { + const result = getManualReactRouterConfigContent(); + + expect(result).toContain("import type { Config }"); + expect(result).toContain("} satisfies Config;"); + }); + + it("imports sentryOnBuildEnd from the given path", () => { + const ts = getManualReactRouterConfigContent( + true, + "@sentry/react-router/vite", + ); + const js = getManualReactRouterConfigContent( + false, + "@sentry/react-router/vite", + ); + + expect(ts).toContain( + "import { sentryOnBuildEnd } from '@sentry/react-router/vite';", + ); + expect(js).toContain( + "import { sentryOnBuildEnd } from '@sentry/react-router/vite';", + ); + }); + }); + + describe("getManualViteConfigContent", () => { + it("imports sentryReactRouter from the given path and keeps the package in optimizeDeps.exclude", () => { + const result = getManualViteConfigContent( + "my-org", + "my-project", + "@sentry/react-router/vite", + ); + + expect(result).toContain( + "import { sentryReactRouter } from '@sentry/react-router/vite';", + ); + expect(result).toContain("exclude: ['@sentry/react-router']"); + }); + }); +}); diff --git a/packages/cli/test/lib/wizard/remix/build-script.test.ts b/packages/cli/test/lib/wizard/remix/build-script.test.ts new file mode 100644 index 0000000000..1ad6c3283e --- /dev/null +++ b/packages/cli/test/lib/wizard/remix/build-script.test.ts @@ -0,0 +1,142 @@ +import { promises } from "node:fs"; + +import { updateBuildScript } from "../../../../src/lib/wizard/remix/sdk-setup.js"; +import { getPackageDotJson } from "../../../../src/lib/wizard/utils/clack/index.js"; + +import { vi, it, describe, expect, afterEach } from "vitest"; + +const writeFileSpy = vi + .spyOn(promises, "writeFile") + .mockImplementation(() => Promise.resolve()); + +vi.mock("@clack/prompts", () => { + const mock = { + log: { + info: vi.fn(), + success: vi.fn(), + warn: vi.fn(), + }, + confirm: vi.fn().mockResolvedValue(true), + isCancel: vi.fn().mockReturnValue(false), + }; + return { ...mock, default: mock }; +}); + +vi.mock("../../../../src/lib/wizard/utils/clack/index.js", async () => ({ + ...(await vi.importActual("../../../../src/lib/wizard/utils/clack/index.js")), + getPackageDotJson: vi.fn().mockResolvedValue({ + scripts: { + build: "remix build", + }, + version: "1.0.0", + }), +})); + +describe("updateBuildScript", () => { + afterEach(() => { + vi.clearAllMocks(); + }); + + it("uses npx @sentry/remix --upload-sourcemaps for the upload command", async () => { + await updateBuildScript({ + org: "my-org", + project: "my-project", + isHydrogen: false, + }); + + expect(writeFileSpy).toHaveBeenCalledWith( + expect.stringContaining("package.json"), + expect.stringContaining( + "npx @sentry/remix --upload-sourcemaps --org my-org --project my-project", + ), + ); + }); + + it("replaces the remix build command with sourcemap flag and upload", async () => { + await updateBuildScript({ + org: "my-org", + project: "my-project", + isHydrogen: false, + }); + + expect(writeFileSpy).toHaveBeenCalledWith( + expect.stringContaining("package.json"), + expect.stringContaining( + "remix build --sourcemap && npx @sentry/remix --upload-sourcemaps", + ), + ); + }); + + it("includes --url flag when a custom url is provided", async () => { + await updateBuildScript({ + org: "my-org", + project: "my-project", + url: "https://self-hosted.example.com", + isHydrogen: false, + }); + + expect(writeFileSpy).toHaveBeenCalledWith( + expect.stringContaining("package.json"), + expect.stringContaining("--url https://self-hosted.example.com"), + ); + }); + + it("uses shopify hydrogen build for hydrogen apps", async () => { + vi.mocked(getPackageDotJson).mockResolvedValue({ + scripts: { + build: "shopify hydrogen build", + }, + version: "1.0.0", + }); + + await updateBuildScript({ + org: "my-org", + project: "my-project", + isHydrogen: true, + }); + + expect(writeFileSpy).toHaveBeenCalledWith( + expect.stringContaining("package.json"), + expect.stringContaining( + "shopify hydrogen build --sourcemap && npx @sentry/remix --upload-sourcemaps --org my-org --project my-project --buildPath ./dist", + ), + ); + }); + + it("sets build script when none exists", async () => { + vi.mocked(getPackageDotJson).mockResolvedValue({ + scripts: {}, + version: "1.0.0", + }); + + await updateBuildScript({ + org: "my-org", + project: "my-project", + isHydrogen: false, + }); + + expect(writeFileSpy).toHaveBeenCalledWith( + expect.stringContaining("package.json"), + expect.stringContaining( + "remix build --sourcemap && npx @sentry/remix --upload-sourcemaps", + ), + ); + }); + + it("throws when build script has an unknown command", async () => { + vi.mocked(getPackageDotJson).mockResolvedValue({ + scripts: { + build: "some-custom-build-tool", + }, + version: "1.0.0", + }); + + await expect( + updateBuildScript({ + org: "my-org", + project: "my-project", + isHydrogen: false, + }), + ).rejects.toThrow("build` script doesn't contain a known build command"); + }); +}); diff --git a/packages/cli/test/lib/wizard/remix/client-entry.test.ts b/packages/cli/test/lib/wizard/remix/client-entry.test.ts new file mode 100644 index 0000000000..21d6373066 --- /dev/null +++ b/packages/cli/test/lib/wizard/remix/client-entry.test.ts @@ -0,0 +1,184 @@ +import { parseModule } from "magicast"; +import { updateEntryClientMod } from "../../../../src/lib/wizard/remix/sdk-setup.js"; +import { describe, expect, it } from "vitest"; + +describe("initializeSentryOnEntryClient", () => { + it("should initialize Sentry on client entry with all features enabled", () => { + // Empty entry.client.tsx file for testing + const originalEntryClientMod = parseModule(""); + + const dsn = "https://sentry.io/123"; + const selectedFeatures = { + performance: true, + replay: true, + }; + + const result = updateEntryClientMod( + originalEntryClientMod, + dsn, + selectedFeatures, + false, + ); + + expect(result.generate().code).toMatchInlineSnapshot(` + "import { useEffect,} from "react"; + + import { + useLocation, + useMatches, + } from "@remix-run/react"; + + import { init, replayIntegration, browserTracingIntegration,} from "@sentry/remix"; + + init({ + dsn: "https://sentry.io/123", + tracesSampleRate: 1, + + integrations: [browserTracingIntegration({ + useEffect, + useLocation, + useMatches + }), replayIntegration({ + maskAllText: true, + blockAllMedia: true + })], + + replaysSessionSampleRate: 0.1, + replaysOnErrorSampleRate: 1 + })" + `); + }); + + it("should initialize Sentry on client entry when performance disabled", () => { + // Empty entry.client.tsx file for testing + const originalEntryClientMod = parseModule(""); + + const dsn = "https://sentry.io/123"; + const selectedFeatures = { + performance: false, + replay: true, + }; + + const result = updateEntryClientMod( + originalEntryClientMod, + dsn, + selectedFeatures, + false, + ); + + expect(result.generate().code).toMatchInlineSnapshot(` + "import { init, replayIntegration,} from "@sentry/remix"; + + init({ + dsn: "https://sentry.io/123", + + integrations: [replayIntegration({ + maskAllText: true, + blockAllMedia: true + })], + + replaysSessionSampleRate: 0.1, + replaysOnErrorSampleRate: 1 + })" + `); + }); + + it("should initialize Sentry on client entry when replay disabled", () => { + // Empty entry.client.tsx file for testing + const originalEntryClientMod = parseModule(""); + + const dsn = "https://sentry.io/123"; + const selectedFeatures = { + performance: true, + replay: false, + }; + + const result = updateEntryClientMod( + originalEntryClientMod, + dsn, + selectedFeatures, + false, + ); + + expect(result.generate().code).toMatchInlineSnapshot(` + "import { useEffect,} from "react"; + + import { + useLocation, + useMatches, + } from "@remix-run/react"; + + import { init, browserTracingIntegration,} from "@sentry/remix"; + + init({ + dsn: "https://sentry.io/123", + tracesSampleRate: 1, + + integrations: [browserTracingIntegration({ + useEffect, + useLocation, + useMatches + })] + })" + `); + }); + + it("should add the dataCollection preset when reduced data collection is requested", () => { + // Empty entry.client.tsx file for testing + const originalEntryClientMod = parseModule(""); + + const dsn = "https://sentry.io/123"; + const selectedFeatures = { + performance: true, + replay: true, + }; + + const result = updateEntryClientMod( + originalEntryClientMod, + dsn, + selectedFeatures, + true, + ); + + expect(result.generate().code).toMatchInlineSnapshot(` + "import { useEffect,} from "react"; + + import { + useLocation, + useMatches, + } from "@remix-run/react"; + + import { init, replayIntegration, browserTracingIntegration,} from "@sentry/remix"; + + init({ + dsn: "https://sentry.io/123", + tracesSampleRate: 1, + + integrations: [browserTracingIntegration({ + useEffect, + useLocation, + useMatches + }), replayIntegration({ + maskAllText: true, + blockAllMedia: true + })], + + replaysSessionSampleRate: 0.1, + replaysOnErrorSampleRate: 1, + // Turns off collection of data that could identify users. Adjust per category: + // https://docs.sentry.io/platforms/javascript/configuration/options/#dataCollection + dataCollection: { + userInfo: false, + graphQL: { document: false, variables: false }, + genAI: { inputs: false, outputs: false }, + databaseQueryData: false, + queues: false, + httpBodies: [], + httpHeaders: { deny: ["forwarded", "-ip", "remote-", "via", "-user"] }, + cookies: { deny: ["forwarded", "-ip", "remote-", "via", "-user"] }, + urlQueryParams: { deny: ["forwarded", "-ip", "remote-", "via", "-user"] }, + }, + })" + `); + }); +}); diff --git a/packages/cli/test/lib/wizard/remix/fixtures/root-already-wrapped.tsx b/packages/cli/test/lib/wizard/remix/fixtures/root-already-wrapped.tsx new file mode 100644 index 0000000000..7257d8ae71 --- /dev/null +++ b/packages/cli/test/lib/wizard/remix/fixtures/root-already-wrapped.tsx @@ -0,0 +1,8 @@ +import { Outlet } from '@remix-run/react'; +import { withSentry } from '@sentry/remix'; + +function App() { + return ; +} + +export default withSentry(App); diff --git a/packages/cli/test/lib/wizard/remix/fixtures/root-no-error-boundary.tsx b/packages/cli/test/lib/wizard/remix/fixtures/root-no-error-boundary.tsx new file mode 100644 index 0000000000..1f66dd4694 --- /dev/null +++ b/packages/cli/test/lib/wizard/remix/fixtures/root-no-error-boundary.tsx @@ -0,0 +1,5 @@ +import { Outlet } from '@remix-run/react'; + +export default function App() { + return ; +} diff --git a/packages/cli/test/lib/wizard/remix/fixtures/root-variable-error-boundary.tsx b/packages/cli/test/lib/wizard/remix/fixtures/root-variable-error-boundary.tsx new file mode 100644 index 0000000000..b2e3d0940c --- /dev/null +++ b/packages/cli/test/lib/wizard/remix/fixtures/root-variable-error-boundary.tsx @@ -0,0 +1,11 @@ +import { Outlet } from '@remix-run/react'; + +const ErrorBoundary = () => { + return
Error occurred
; +}; + +export { ErrorBoundary }; + +export default function App() { + return ; +} diff --git a/packages/cli/test/lib/wizard/remix/fixtures/root-with-error-boundary.tsx b/packages/cli/test/lib/wizard/remix/fixtures/root-with-error-boundary.tsx new file mode 100644 index 0000000000..18b3edbf47 --- /dev/null +++ b/packages/cli/test/lib/wizard/remix/fixtures/root-with-error-boundary.tsx @@ -0,0 +1,9 @@ +import { Outlet } from '@remix-run/react'; + +export function ErrorBoundary() { + return
Error occurred
; +} + +export default function App() { + return ; +} diff --git a/packages/cli/test/lib/wizard/remix/fixtures/root-with-sentry-error-boundary.tsx b/packages/cli/test/lib/wizard/remix/fixtures/root-with-sentry-error-boundary.tsx new file mode 100644 index 0000000000..9957fb6b55 --- /dev/null +++ b/packages/cli/test/lib/wizard/remix/fixtures/root-with-sentry-error-boundary.tsx @@ -0,0 +1,11 @@ +import { Outlet } from '@remix-run/react'; +import { captureRemixErrorBoundaryError } from '@sentry/remix'; + +export function ErrorBoundary() { + captureRemixErrorBoundaryError(); + return
Error occurred
; +} + +export default function App() { + return ; +} diff --git a/packages/cli/test/lib/wizard/remix/root.test.ts b/packages/cli/test/lib/wizard/remix/root.test.ts new file mode 100644 index 0000000000..35c643585e --- /dev/null +++ b/packages/cli/test/lib/wizard/remix/root.test.ts @@ -0,0 +1,311 @@ +import { parseModule } from "magicast"; +import { describe, expect, it, vi, beforeEach, afterEach } from "vitest"; +import { + copyFileSync, + existsSync, + mkdirSync, + readFileSync, + readdirSync, + rmdirSync, + statSync, + unlinkSync, +} from "node:fs"; +import path from "node:path"; +import { + wrapAppWithSentry, + isWithSentryAlreadyUsed, + instrumentRoot, +} from "../../../../src/lib/wizard/remix/codemods/root.js"; + +vi.mock("@clack/prompts", () => { + const mock = { + log: { + warn: vi.fn(), + info: vi.fn(), + success: vi.fn(), + }, + }; + return { + default: mock, + ...mock, + }; +}); + +vi.mock("../../../../src/lib/wizard/utils/clack/mcp-config.js", () => ({ + offerProjectScopedMcpConfig: vi.fn().mockResolvedValue(undefined), +})); + +describe("wrapAppWithSentry", () => { + it("should wrap the app with Sentry", () => { + // Empty root.tsx file for testing + const originalRootAst = parseModule(` + import { Outlet } from '@remix-run/react'; + + export default function App() { + return ; + } + `); + + wrapAppWithSentry(originalRootAst, "root.tsx"); + + const result = originalRootAst.generate().code; + + expect(result).toMatchInlineSnapshot(` + "import {withSentry} from '@sentry/remix'; + import { Outlet } from '@remix-run/react'; + + function App() { + return ; + } + + export default withSentry(App);" + `); + }); +}); + +describe("isWithSentryAlreadyUsed", () => { + it("should return false when withSentry is not used", () => { + const rootAst = parseModule(` + import { Outlet } from '@remix-run/react'; + + export default function App() { + return ; + } + `); + + expect(isWithSentryAlreadyUsed(rootAst)).toBe(false); + }); + + it("should return true when withSentry is used in default export", () => { + const rootAst = parseModule(` + import { withSentry } from '@sentry/remix'; + import { Outlet } from '@remix-run/react'; + + function App() { + return ; + } + + export default withSentry(App); + `); + + expect(isWithSentryAlreadyUsed(rootAst)).toBe(true); + }); + + it("should return true when withSentry is used in a variable assignment", () => { + const rootAst = parseModule(` + import { withSentry } from '@sentry/remix'; + import { Outlet } from '@remix-run/react'; + + function App() { + return ; + } + + const WrappedApp = withSentry(App); + export default WrappedApp; + `); + + expect(isWithSentryAlreadyUsed(rootAst)).toBe(true); + }); + + it("should return true when withSentry is used inside a function", () => { + const rootAst = parseModule(` + import { withSentry } from '@sentry/remix'; + import { Outlet } from '@remix-run/react'; + + function App() { + return ; + } + + function createApp() { + return withSentry(App); + } + + export default createApp(); + `); + + expect(isWithSentryAlreadyUsed(rootAst)).toBe(true); + }); + + it("should return false when withSentry is imported but not used", () => { + const rootAst = parseModule(` + import { withSentry } from '@sentry/remix'; + import { Outlet } from '@remix-run/react'; + + export default function App() { + return ; + } + `); + + expect(isWithSentryAlreadyUsed(rootAst)).toBe(false); + }); + + it("should return false when a different function with similar name is used", () => { + const rootAst = parseModule(` + import { Outlet } from '@remix-run/react'; + + function withSentryLike() { + return null; + } + + export default function App() { + withSentryLike(); + return ; + } + `); + + expect(isWithSentryAlreadyUsed(rootAst)).toBe(false); + }); +}); + +describe("instrumentRoot", () => { + const fixturesDir = path.join(__dirname, "fixtures"); + const tmpDir = path.join(fixturesDir, "tmp"); + + beforeEach(() => { + vi.clearAllMocks(); + // Mock process.cwd() to return the fixtures directory + vi.spyOn(process, "cwd").mockReturnValue(fixturesDir); + }); + + afterEach(() => { + // Clean up any temporary files + if (existsSync(tmpDir)) { + try { + // Remove files first, then directory + const appDir = path.join(tmpDir, "app"); + if (existsSync(appDir)) { + const files = readdirSync(appDir); + files.forEach((file) => { + unlinkSync(path.join(appDir, file)); + }); + rmdirSync(appDir); + } + + const files = readdirSync(tmpDir); + files.forEach((file) => { + const filePath = path.join(tmpDir, file); + const stat = statSync(filePath); + if (stat.isDirectory()) { + rmdirSync(filePath); + } else { + unlinkSync(filePath); + } + }); + } catch (error) { + // Ignore cleanup errors in tests + } + } + }); + + it("should add ErrorBoundary and wrap app with Sentry when no ErrorBoundary exists and withSentry is not used", async () => { + // Copy fixture to tmp directory for testing + const srcFile = path.join(fixturesDir, "root-no-error-boundary.tsx"); + const appDir = path.join(tmpDir, "app"); + + // Create app directory and copy file + mkdirSync(appDir, { recursive: true }); + copyFileSync(srcFile, path.join(appDir, "root.tsx")); + + // Mock process.cwd() to return tmpDir + vi.spyOn(process, "cwd").mockReturnValue(tmpDir); + + await instrumentRoot("root.tsx"); + + // Check that the file was modified correctly + const modifiedContent = readFileSync(path.join(appDir, "root.tsx"), "utf8"); + + expect(modifiedContent).toContain( + 'import { captureRemixErrorBoundaryError, withSentry } from "@sentry/remix";', + ); + expect(modifiedContent).toContain( + "import { Outlet, useRouteError } from '@remix-run/react';", + ); + expect(modifiedContent).toContain("withSentry(App)"); + expect(modifiedContent).toContain("const ErrorBoundary = () => {"); + }); + + it("should wrap app with Sentry when ErrorBoundary exists but no Sentry content", async () => { + const srcFile = path.join(fixturesDir, "root-with-error-boundary.tsx"); + const appDir = path.join(tmpDir, "app"); + + mkdirSync(appDir, { recursive: true }); + copyFileSync(srcFile, path.join(appDir, "root.tsx")); + + vi.spyOn(process, "cwd").mockReturnValue(tmpDir); + + await instrumentRoot("root.tsx"); + + const modifiedContent = readFileSync(path.join(appDir, "root.tsx"), "utf8"); + + expect(modifiedContent).toContain( + 'import { captureRemixErrorBoundaryError, withSentry } from "@sentry/remix";', + ); + expect(modifiedContent).toContain("withSentry(App)"); + }); + + it("should wrap app with Sentry when ErrorBoundary exists with Sentry content but withSentry is not used", async () => { + const srcFile = path.join( + fixturesDir, + "root-with-sentry-error-boundary.tsx", + ); + const appDir = path.join(tmpDir, "app"); + + mkdirSync(appDir, { recursive: true }); + copyFileSync(srcFile, path.join(appDir, "root.tsx")); + + vi.spyOn(process, "cwd").mockReturnValue(tmpDir); + + await instrumentRoot("root.tsx"); + + const modifiedContent = readFileSync(path.join(appDir, "root.tsx"), "utf8"); + + expect(modifiedContent).toContain( + "import { captureRemixErrorBoundaryError, withSentry } from '@sentry/remix';", + ); + expect(modifiedContent).toContain("withSentry(App)"); + }); + + it("should not wrap app when withSentry is already used", async () => { + const srcFile = path.join(fixturesDir, "root-already-wrapped.tsx"); + const appDir = path.join(tmpDir, "app"); + + mkdirSync(appDir, { recursive: true }); + copyFileSync(srcFile, path.join(appDir, "root.tsx")); + + vi.spyOn(process, "cwd").mockReturnValue(tmpDir); + + await instrumentRoot("root.tsx"); + + const modifiedContent = readFileSync(path.join(appDir, "root.tsx"), "utf8"); + + // Should not add withSentry import or wrap again + expect(modifiedContent).toContain("withSentry(App)"); + + // Count occurrences of withSentry to ensure it's not duplicated + const withSentryOccurrences = (modifiedContent.match(/withSentry/g) || []) + .length; + expect(withSentryOccurrences).toBe(2); // One import, one usage + + // The content should remain largely the same since withSentry is already used + expect(modifiedContent).toContain("export default withSentry(App)"); + }); + + it("should handle ErrorBoundary as variable declaration", async () => { + const srcFile = path.join(fixturesDir, "root-variable-error-boundary.tsx"); + const appDir = path.join(tmpDir, "app"); + + mkdirSync(appDir, { recursive: true }); + copyFileSync(srcFile, path.join(appDir, "root.tsx")); + + vi.spyOn(process, "cwd").mockReturnValue(tmpDir); + + await instrumentRoot("root.tsx"); + + const modifiedContent = readFileSync(path.join(appDir, "root.tsx"), "utf8"); + + expect(modifiedContent).toContain( + 'import { captureRemixErrorBoundaryError, withSentry } from "@sentry/remix";', + ); + expect(modifiedContent).toContain("withSentry(App)"); + }); +}); diff --git a/packages/cli/test/lib/wizard/remix/server-instrumentation.test.ts b/packages/cli/test/lib/wizard/remix/server-instrumentation.test.ts new file mode 100644 index 0000000000..2a5d2effa6 --- /dev/null +++ b/packages/cli/test/lib/wizard/remix/server-instrumentation.test.ts @@ -0,0 +1,79 @@ +import { describe, expect, it } from "vitest"; +import { generateServerInstrumentationFile } from "../../../../src/lib/wizard/remix/sdk-setup.js"; + +describe("generateServerInstrumentationFile", () => { + it("should generate server instrumentation file", () => { + const result = generateServerInstrumentationFile( + "https://sentry.io/123", + { + performance: true, + replay: true, + }, + false, + ); + + expect(result.instrumentationFileMod.generate().code) + .toMatchInlineSnapshot(` + "import * as Sentry from "@sentry/remix"; + + Sentry.init({ + dsn: "https://sentry.io/123", + tracesSampleRate: 1 + })" + `); + }); + + it("should generate server instrumentation file when performance is disabled", () => { + const result = generateServerInstrumentationFile( + "https://sentry.io/123", + { + performance: false, + replay: true, + }, + false, + ); + + expect(result.instrumentationFileMod.generate().code) + .toMatchInlineSnapshot(` + "import * as Sentry from "@sentry/remix"; + + Sentry.init({ + dsn: "https://sentry.io/123" + })" + `); + }); + + it("should add the dataCollection preset when reduced data collection is requested", () => { + const result = generateServerInstrumentationFile( + "https://sentry.io/123", + { + performance: true, + replay: true, + }, + true, + ); + + expect(result.instrumentationFileMod.generate().code) + .toMatchInlineSnapshot(` + "import * as Sentry from "@sentry/remix"; + + Sentry.init({ + dsn: "https://sentry.io/123", + tracesSampleRate: 1, + // Turns off collection of data that could identify users. Adjust per category: + // https://docs.sentry.io/platforms/javascript/configuration/options/#dataCollection + dataCollection: { + userInfo: false, + graphQL: { document: false, variables: false }, + genAI: { inputs: false, outputs: false }, + databaseQueryData: false, + queues: false, + httpBodies: [], + httpHeaders: { deny: ["forwarded", "-ip", "remote-", "via", "-user"] }, + cookies: { deny: ["forwarded", "-ip", "remote-", "via", "-user"] }, + urlQueryParams: { deny: ["forwarded", "-ip", "remote-", "via", "-user"] }, + }, + })" + `); + }); +}); diff --git a/packages/cli/test/lib/wizard/sveltekit/sdk-setup/svelte-config.test.ts b/packages/cli/test/lib/wizard/sveltekit/sdk-setup/svelte-config.test.ts new file mode 100644 index 0000000000..0a21edf567 --- /dev/null +++ b/packages/cli/test/lib/wizard/sveltekit/sdk-setup/svelte-config.test.ts @@ -0,0 +1,664 @@ +import { describe, it, expect } from "vitest"; +import { _enableTracingAndInstrumentationInConfig } from "../../../../../src/lib/wizard/sveltekit/sdk-setup/svelte-config.js"; + +describe("_enableTracingAndInstrumentationInConfig", () => { + it("leaves already correct config unchanged", () => { + const originalConfig = `export default { + preprocess: vitePreprocess(), + + kit: { + adapter: adapter(), + experimental: { + tracing: { + server: true, + }, + instrumentation: { + server: true, + }, + }, + }, +};`; + + const modifiedConfig = _enableTracingAndInstrumentationInConfig( + originalConfig, + true, + ); + + expect(modifiedConfig.result).toBe(originalConfig); + }); + + describe("successfully handles", () => { + it("default config as variable declaration", () => { + const originalConfig = `/** @type {import('@sveltejs/kit').Config} */ +const config = { + preprocess: vitePreprocess(), + + kit: { + adapter: adapter(), + }, +}; + +export default config; +`; + + const modifiedConfig = _enableTracingAndInstrumentationInConfig( + originalConfig, + true, + ); + + expect(modifiedConfig.result).toMatchInlineSnapshot(` + "/** @type {import('@sveltejs/kit').Config} */ + const config = { + preprocess: vitePreprocess(), + + kit: { + adapter: adapter(), + + experimental: { + tracing: { + server: true, + }, + + instrumentation: { + server: true, + }, + }, + }, + }; + + export default config;" + `); + }); + + it("default config named declaration object", () => { + const originalConfig = ` +export default config = { + preprocess: vitePreprocess(), + + kit: { + adapter: adapter(), + }, +}; +`; + + const modifiedConfig = _enableTracingAndInstrumentationInConfig( + originalConfig, + true, + ); + + expect(modifiedConfig.result).toMatchInlineSnapshot(` + "export default config = { + preprocess: vitePreprocess(), + + kit: { + adapter: adapter(), + + experimental: { + tracing: { + server: true, + }, + + instrumentation: { + server: true, + }, + }, + }, + };" + `); + }); + + it("default config as in-place object", () => { + const originalConfig = ` +export default { + preprocess: vitePreprocess(), + + kit: { + adapter: adapter(), + }, +}; +`; + + const modifiedConfig = _enableTracingAndInstrumentationInConfig( + originalConfig, + true, + ); + + expect(modifiedConfig.result).toMatchInlineSnapshot(` + "export default { + preprocess: vitePreprocess(), + + kit: { + adapter: adapter(), + + experimental: { + tracing: { + server: true, + }, + + instrumentation: { + server: true, + }, + }, + }, + };" + `); + }); + + it("config with tracing disabled", () => { + const originalConfig = ` +export default { + preprocess: vitePreprocess(), + + kit: { + adapter: adapter(), + }, +}; +`; + + const modifiedConfig = _enableTracingAndInstrumentationInConfig( + originalConfig, + false, + ); + + expect(modifiedConfig.result).toMatchInlineSnapshot(` + "export default { + preprocess: vitePreprocess(), + + kit: { + adapter: adapter(), + + experimental: { + tracing: { + server: false, + }, + + instrumentation: { + server: true, + }, + }, + }, + };" + `); + }); + + it("config with pre-existing `kit.experimental` property", () => { + const originalConfig = ` +export default { + preprocess: vitePreprocess(), + + kit: { + adapter: adapter(), + experimental: { + remoteFunctions: true, + } + }, +}; +`; + + const modifiedConfig = _enableTracingAndInstrumentationInConfig( + originalConfig, + true, + ); + + expect(modifiedConfig.result).toMatchInlineSnapshot(` + "export default { + preprocess: vitePreprocess(), + + kit: { + adapter: adapter(), + experimental: { + remoteFunctions: true, + + tracing: { + server: true, + }, + + instrumentation: { + server: true, + }, + } + }, + };" + `); + }); + + it("config with pre-existing and empty `kit.experimental.tracing` property", () => { + const originalConfig = ` +export default { + preprocess: vitePreprocess(), + + kit: { + adapter: adapter(), + experimental: { + remoteFunctions: true, + tracing: { + }, + } + }, +}; +`; + + const modifiedConfig = _enableTracingAndInstrumentationInConfig( + originalConfig, + true, + ); + + expect(modifiedConfig.result).toMatchInlineSnapshot(` + "export default { + preprocess: vitePreprocess(), + + kit: { + adapter: adapter(), + experimental: { + remoteFunctions: true, + + tracing: { + server: true, + }, + + instrumentation: { + server: true, + }, + } + }, + };" + `); + }); + + it("config with pre-existing and empty `kit.experimental.instrumentation` property", () => { + const originalConfig = ` +export default { + preprocess: vitePreprocess(), + + kit: { + adapter: adapter(), + experimental: { + remoteFunctions: true, + tracing: { + }, + instrumentation: { + }, + } + }, +}; +`; + + const modifiedConfig = _enableTracingAndInstrumentationInConfig( + originalConfig, + true, + ); + + expect(modifiedConfig.result).toMatchInlineSnapshot(` + "export default { + preprocess: vitePreprocess(), + + kit: { + adapter: adapter(), + experimental: { + remoteFunctions: true, + tracing: { + server: true, + }, + instrumentation: { + server: true, + }, + } + }, + };" + `); + }); + + it("config with pre-existing and filled `kit.experimental.(instrumentation|tracing).server` properties", () => { + const originalConfig = ` +export default { + preprocess: vitePreprocess(), + + kit: { + adapter: adapter(), + experimental: { + remoteFunctions: true, + tracing: { + server: false, + }, + instrumentation: { + server: false, + }, + } + }, +}; +`; + + const modifiedConfig = _enableTracingAndInstrumentationInConfig( + originalConfig, + true, + ); + + expect(modifiedConfig.result).toMatchInlineSnapshot(` + "export default { + preprocess: vitePreprocess(), + + kit: { + adapter: adapter(), + experimental: { + remoteFunctions: true, + tracing: { + server: true, + }, + instrumentation: { + server: true, + }, + } + }, + };" + `); + }); + + it("config with pre-existing and filled `kit.experimental.(instrumentation|tracing).server` properties with instrumentation disabled", () => { + const originalConfig = ` +export default { + preprocess: vitePreprocess(), + + kit: { + adapter: adapter(), + experimental: { + remoteFunctions: true, + tracing: { + server: true, + }, + instrumentation: { + server: false, + }, + } + }, +}; +`; + + const modifiedConfig = _enableTracingAndInstrumentationInConfig( + originalConfig, + true, + ); + + expect(modifiedConfig.result).toMatchInlineSnapshot(` + "export default { + preprocess: vitePreprocess(), + + kit: { + adapter: adapter(), + experimental: { + remoteFunctions: true, + tracing: { + server: true, + }, + instrumentation: { + server: true, + }, + } + }, + };" + `); + }); + + it("config with pre-existing and filled `kit.experimental.(instrumentation|tracing).server` properties with tracing disabled", () => { + const originalConfig = ` +export default { + preprocess: vitePreprocess(), + + kit: { + adapter: adapter(), + experimental: { + remoteFunctions: true, + tracing: { + server: false, + }, + instrumentation: { + server: true, + }, + } + }, +}; +`; + + const modifiedConfig = _enableTracingAndInstrumentationInConfig( + originalConfig, + true, + ); + + expect(modifiedConfig.result).toMatchInlineSnapshot(` + "export default { + preprocess: vitePreprocess(), + + kit: { + adapter: adapter(), + experimental: { + remoteFunctions: true, + tracing: { + server: true, + }, + instrumentation: { + server: true, + }, + } + }, + };" + `); + }); + }); + + describe("gracefully errors if", () => { + it("config object not found", () => { + const originalConfig = `console.log('hello')`; + + const modifiedConfig = _enableTracingAndInstrumentationInConfig( + originalConfig, + true, + ); + + expect(modifiedConfig.error).toBe("Couldn't find the config object"); + }); + + it("config is not an object", () => { + const originalConfig = ` + export default getSvelteConfig(); + `; + + const modifiedConfig = _enableTracingAndInstrumentationInConfig( + originalConfig, + true, + ); + + expect(modifiedConfig.error).toBe("Couldn't find the config object"); + }); + + it("`kit` property is missing", () => { + const originalConfig = ` + export default { + preprocess: vitePreprocess(), + }; + `; + + const modifiedConfig = _enableTracingAndInstrumentationInConfig( + originalConfig, + true, + ); + + expect(modifiedConfig.error).toBe("Couldn't find the `kit` property"); + }); + + it("`kit` property has unexpected type", () => { + const originalConfig = ` + export default { + preprocess: vitePreprocess(), + + kit: getKitConfig(), + }; + `; + + const modifiedConfig = _enableTracingAndInstrumentationInConfig( + originalConfig, + true, + ); + + expect(modifiedConfig.error).toBe( + "`kit` property has unexpected type: CallExpression", + ); + }); + + it("`kit.experimental` property has unexpected type", () => { + const originalConfig = ` + export default { + preprocess: vitePreprocess(), + + kit: { + adapter: adapter(), + experimental: 'hello', + }, + }; + `; + + const modifiedConfig = _enableTracingAndInstrumentationInConfig( + originalConfig, + true, + ); + + expect(modifiedConfig.error).toBe( + "Property `kit.experimental` has unexpected type: StringLiteral", + ); + }); + + it("`kit.experimental.tracing` property has unexpected type", () => { + const originalConfig = ` + export default { + preprocess: vitePreprocess(), + + kit: { + adapter: adapter(), + experimental: { + tracing: true, + }, + }, + }; + `; + + const modifiedConfig = _enableTracingAndInstrumentationInConfig( + originalConfig, + true, + ); + + expect(modifiedConfig.error).toBe( + "Property `kit.experimental.tracing` has unexpected type: BooleanLiteral", + ); + }); + + it("`kit.experimental.instrumentation` property has unexpected type", () => { + const originalConfig = ` + export default { + preprocess: vitePreprocess(), + + kit: { + adapter: adapter(), + experimental: { + tracing: { + server: true, + }, + instrumentation: 'server', + }, + }, + }; + `; + + const modifiedConfig = _enableTracingAndInstrumentationInConfig( + originalConfig, + true, + ); + + expect(modifiedConfig.error).toBe( + "Property `kit.experimental.instrumentation` has unexpected type: StringLiteral", + ); + }); + + it("`kit.experimental.tracing.server` property has unexpected type", () => { + const originalConfig = ` + export default { + preprocess: vitePreprocess(), + + kit: { + adapter: adapter(), + experimental: { + tracing: { + server: !!process.env['ENABLE_TRACING'], + }, + instrumentation: { + server: true, + }, + }, + }, + }; + `; + + const modifiedConfig = _enableTracingAndInstrumentationInConfig( + originalConfig, + true, + ); + + expect(modifiedConfig.error).toBe( + "Property `kit.experimental.tracing.server` has unexpected type: UnaryExpression", + ); + }); + + it("`kit.experimental.instrumentation.server` property has unexpected type", () => { + const originalConfig = ` + export default { + preprocess: vitePreprocess(), + + kit: { + adapter: adapter(), + experimental: { + tracing: { + server: true, + }, + instrumentation: { + server: 'hello', + }, + }, + }, + }; + `; + + const modifiedConfig = _enableTracingAndInstrumentationInConfig( + originalConfig, + true, + ); + + expect(modifiedConfig.error).toBe( + "Property `kit.experimental.instrumentation.server` has unexpected type: StringLiteral", + ); + }); + + it("config parsing fails", () => { + const originalConfig = ` + export default { + preprocess: vitePreprocess(), + + kit: { + adapter: adapter(), + experimental: { + tracing: { + server: true, + } + instrumentation: { + server: 'hello', + }, + }, + }, + }; + `; + + const modifiedConfig = _enableTracingAndInstrumentationInConfig( + originalConfig, + true, + ); + + expect(modifiedConfig.error).toBe("Failed to parse Svelte config"); + }); + }); +}); diff --git a/packages/cli/test/lib/wizard/sveltekit/sdk-setup/vite.test.ts b/packages/cli/test/lib/wizard/sveltekit/sdk-setup/vite.test.ts new file mode 100644 index 0000000000..3201e15d51 --- /dev/null +++ b/packages/cli/test/lib/wizard/sveltekit/sdk-setup/vite.test.ts @@ -0,0 +1,111 @@ +import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; + +vi.mock("@clack/prompts", () => ({ + log: { + warn: vi.fn(), + warning: vi.fn(), + success: vi.fn(), + info: vi.fn(), + step: vi.fn(), + }, + select: vi.fn(() => Promise.resolve(true)), +})); + +vi.mock("../../../../../src/lib/wizard/utils/clack/index.js", () => ({ + abortIfCancelled: vi.fn((v: unknown) => v), +})); + +import { modifyViteConfig } from "../../../../../src/lib/wizard/sveltekit/sdk-setup/vite.js"; +import type { ProjectInfo } from "../../../../../src/lib/wizard/sveltekit/sdk-setup/types.js"; + +const baseViteConfig = `import { sveltekit } from '@sveltejs/kit/vite'; +import { defineConfig } from 'vite'; + +export default defineConfig({ + plugins: [sveltekit()] +}); +`; + +describe("modifyViteConfig", () => { + let tmpDir: string; + let viteConfigPath: string; + + const projectInfo = (overrides: Partial): ProjectInfo => ({ + dsn: "https://public@dsn.ingest.sentry.io/1337", + org: "my-org", + project: "my-project", + selfHosted: false, + url: "https://sentry.io/", + vitePluginImportPath: "@sentry/sveltekit/vite", + reduceDataCollection: false, + ...overrides, + }); + + beforeEach(() => { + tmpDir = mkdtempSync(path.join(tmpdir(), "sveltekit-vite-test-")); + viteConfigPath = path.join(tmpDir, "vite.config.js"); + writeFileSync(viteConfigPath, baseViteConfig); + }); + + afterEach(() => { + rmSync(tmpDir, { recursive: true, force: true }); + }); + + it("imports sentrySvelteKit from the given path and writes sentryUrl for self-hosted", async () => { + await modifyViteConfig( + viteConfigPath, + projectInfo({ + selfHosted: true, + url: "https://sentry.example.com/", + vitePluginImportPath: "@sentry/sveltekit/vite", + }), + ); + + const result = readFileSync(viteConfigPath, "utf-8"); + expect(result).toContain( + 'import { sentrySvelteKit } from "@sentry/sveltekit/vite";', + ); + expect(result).toContain("sentrySvelteKit({"); + expect(result).toContain('org: "my-org"'); + expect(result).toContain('project: "my-project"'); + expect(result).toContain('sentryUrl: "https://sentry.example.com/"'); + expect(result).not.toMatch(/\burl:/); + // registered before sveltekit() + expect(result.indexOf("sentrySvelteKit(")).toBeLessThan( + result.indexOf("sveltekit()"), + ); + }); + + it("imports from the root export when the installed SDK requires it", async () => { + await modifyViteConfig( + viteConfigPath, + projectInfo({ vitePluginImportPath: "@sentry/sveltekit" }), + ); + + const result = readFileSync(viteConfigPath, "utf-8"); + expect(result).toContain( + 'import { sentrySvelteKit } from "@sentry/sveltekit";', + ); + expect(result).not.toContain("@sentry/sveltekit/vite"); + expect(result).not.toContain("sentryUrl"); + }); + + it("leaves a config that already contains Sentry code untouched", async () => { + const existing = `import { sentrySvelteKit } from "@sentry/sveltekit"; +import { sveltekit } from '@sveltejs/kit/vite'; +import { defineConfig } from 'vite'; + +export default defineConfig({ + plugins: [sentrySvelteKit({ org: "old" }), sveltekit()] +}); +`; + writeFileSync(viteConfigPath, existing); + + await modifyViteConfig(viteConfigPath, projectInfo({})); + + expect(readFileSync(viteConfigPath, "utf-8")).toBe(existing); + }); +}); diff --git a/packages/cli/test/lib/wizard/sveltekit/templates.test.ts b/packages/cli/test/lib/wizard/sveltekit/templates.test.ts new file mode 100644 index 0000000000..94d41f69e5 --- /dev/null +++ b/packages/cli/test/lib/wizard/sveltekit/templates.test.ts @@ -0,0 +1,1201 @@ +import { describe, expect, it, vi } from "vitest"; +import { + getClientHooksTemplate, + getInstrumentationServerTemplate, + getSentryExampleApiRoute, + getSentryExampleSveltePage, + getServerHooksTemplate, +} from "../../../../src/lib/wizard/sveltekit/templates.js"; +import { insertClientInitCall } from "../../../../src/lib/wizard/sveltekit/sdk-setup/setup.js"; +import { parseModule } from "magicast"; + +vi.mock("../../../../src/lib/wizard/utils/clack/mcp-config.js", () => ({ + offerProjectScopedMcpConfig: vi.fn().mockResolvedValue(undefined), +})); + +describe("getClientHooksTemplate", () => { + it("generates client hooks template with all features enabled", () => { + const result = getClientHooksTemplate( + "https://sentry.io/123", + { + performance: true, + replay: true, + }, + false, + ); + + expect(result).toMatchInlineSnapshot(` + "import { handleErrorWithSentry, replayIntegration } from "@sentry/sveltekit"; + import * as Sentry from '@sentry/sveltekit'; + + Sentry.init({ + dsn: 'https://sentry.io/123', + + tracesSampleRate: 1.0, + + // This sets the sample rate to be 10%. You may want this to be 100% while + // in development and sample at a lower rate in production + replaysSessionSampleRate: 0.1, + + // If the entire session is not sampled, use the below sample rate to sample + // sessions when an error occurs. + replaysOnErrorSampleRate: 1.0, + + // If you don't want to use Session Replay, just remove the line below: + integrations: [replayIntegration()], + + dataCollection: { + // To disable sending user data and HTTP bodies, uncomment the lines below. For more info visit: + // https://docs.sentry.io/platforms/javascript/guides/sveltekit/configuration/options/#dataCollection + // userInfo: false, + // httpBodies: [], + }, + }); + + // If you have a custom error handler, pass it to \`handleErrorWithSentry\` + export const handleError = handleErrorWithSentry(); + " + `); + }); + + it("generates client hooks template when performance disabled", () => { + const result = getClientHooksTemplate( + "https://sentry.io/123", + { + performance: false, + replay: true, + }, + false, + ); + + expect(result).toMatchInlineSnapshot(` + "import { handleErrorWithSentry, replayIntegration } from "@sentry/sveltekit"; + import * as Sentry from '@sentry/sveltekit'; + + Sentry.init({ + dsn: 'https://sentry.io/123', + + // This sets the sample rate to be 10%. You may want this to be 100% while + // in development and sample at a lower rate in production + replaysSessionSampleRate: 0.1, + + // If the entire session is not sampled, use the below sample rate to sample + // sessions when an error occurs. + replaysOnErrorSampleRate: 1.0, + + // If you don't want to use Session Replay, just remove the line below: + integrations: [replayIntegration()], + + dataCollection: { + // To disable sending user data and HTTP bodies, uncomment the lines below. For more info visit: + // https://docs.sentry.io/platforms/javascript/guides/sveltekit/configuration/options/#dataCollection + // userInfo: false, + // httpBodies: [], + }, + }); + + // If you have a custom error handler, pass it to \`handleErrorWithSentry\` + export const handleError = handleErrorWithSentry(); + " + `); + }); + + it("generates client hooks template when replay disabled", () => { + const result = getClientHooksTemplate( + "https://sentry.io/123", + { + performance: true, + replay: false, + }, + false, + ); + + expect(result).toMatchInlineSnapshot(` + "import { handleErrorWithSentry, replayIntegration } from "@sentry/sveltekit"; + import * as Sentry from '@sentry/sveltekit'; + + Sentry.init({ + dsn: 'https://sentry.io/123', + + tracesSampleRate: 1.0, + + + + dataCollection: { + // To disable sending user data and HTTP bodies, uncomment the lines below. For more info visit: + // https://docs.sentry.io/platforms/javascript/guides/sveltekit/configuration/options/#dataCollection + // userInfo: false, + // httpBodies: [], + }, + }); + + // If you have a custom error handler, pass it to \`handleErrorWithSentry\` + export const handleError = handleErrorWithSentry(); + " + `); + }); + + it("generates client hooks template with reduced data collection", () => { + const result = getClientHooksTemplate( + "https://sentry.io/123", + { + performance: true, + replay: true, + }, + true, + ); + + expect(result).toMatchInlineSnapshot(` + "import { handleErrorWithSentry, replayIntegration } from "@sentry/sveltekit"; + import * as Sentry from '@sentry/sveltekit'; + + Sentry.init({ + dsn: 'https://sentry.io/123', + + tracesSampleRate: 1.0, + + // This sets the sample rate to be 10%. You may want this to be 100% while + // in development and sample at a lower rate in production + replaysSessionSampleRate: 0.1, + + // If the entire session is not sampled, use the below sample rate to sample + // sessions when an error occurs. + replaysOnErrorSampleRate: 1.0, + + // If you don't want to use Session Replay, just remove the line below: + integrations: [replayIntegration()], + + // Turns off collection of data that could identify users. Adjust per category: + // https://docs.sentry.io/platforms/javascript/configuration/options/#dataCollection + dataCollection: { + userInfo: false, + graphQL: { document: false, variables: false }, + genAI: { inputs: false, outputs: false }, + databaseQueryData: false, + queues: false, + httpBodies: [], + httpHeaders: { deny: ["forwarded", "-ip", "remote-", "via", "-user"] }, + cookies: { deny: ["forwarded", "-ip", "remote-", "via", "-user"] }, + urlQueryParams: { deny: ["forwarded", "-ip", "remote-", "via", "-user"] }, + }, + }); + + // If you have a custom error handler, pass it to \`handleErrorWithSentry\` + export const handleError = handleErrorWithSentry(); + " + `); + }); +}); + +describe("getServerHooksTemplate", () => { + it("generates server hooks template with all features enabled", () => { + const result = getServerHooksTemplate( + "https://sentry.io/123", + { + performance: true, + replay: true, + }, + true, + false, + ); + + expect(result).toMatchInlineSnapshot(` + "import { sequence } from "@sveltejs/kit/hooks"; + import { handleErrorWithSentry, sentryHandle } from "@sentry/sveltekit"; + import * as Sentry from '@sentry/sveltekit'; + + Sentry.init({ + dsn: 'https://sentry.io/123', + + tracesSampleRate: 1.0, + + dataCollection: { + // To disable sending user data and HTTP bodies, uncomment the lines below. For more info visit: + // https://docs.sentry.io/platforms/javascript/guides/sveltekit/configuration/options/#dataCollection + // userInfo: false, + // httpBodies: [], + }, + + // uncomment the line below to enable Spotlight (https://spotlightjs.com) + // spotlight: import.meta.env.DEV, + }); + + // If you have custom handlers, make sure to place them after \`sentryHandle()\` in the \`sequence\` function. + export const handle = sequence(sentryHandle()); + + // If you have a custom error handler, pass it to \`handleErrorWithSentry\` + export const handleError = handleErrorWithSentry(); + " + `); + }); + + it("generates server hooks template when performance disabled", () => { + const result = getServerHooksTemplate( + "https://sentry.io/123", + { + performance: false, + replay: true, + }, + true, + false, + ); + + expect(result).toMatchInlineSnapshot(` + "import { sequence } from "@sveltejs/kit/hooks"; + import { handleErrorWithSentry, sentryHandle } from "@sentry/sveltekit"; + import * as Sentry from '@sentry/sveltekit'; + + Sentry.init({ + dsn: 'https://sentry.io/123', + + dataCollection: { + // To disable sending user data and HTTP bodies, uncomment the lines below. For more info visit: + // https://docs.sentry.io/platforms/javascript/guides/sveltekit/configuration/options/#dataCollection + // userInfo: false, + // httpBodies: [], + }, + + // uncomment the line below to enable Spotlight (https://spotlightjs.com) + // spotlight: import.meta.env.DEV, + }); + + // If you have custom handlers, make sure to place them after \`sentryHandle()\` in the \`sequence\` function. + export const handle = sequence(sentryHandle()); + + // If you have a custom error handler, pass it to \`handleErrorWithSentry\` + export const handleError = handleErrorWithSentry(); + " + `); + }); + + it("generates server hooks template without Sentry.init if includeSentryInit is false", () => { + const result = getServerHooksTemplate( + "https://sentry.io/123", + { + performance: false, + replay: false, + }, + false, + false, + ); + + expect(result).toMatchInlineSnapshot(` + "import { sequence } from "@sveltejs/kit/hooks"; + import { handleErrorWithSentry, sentryHandle } from "@sentry/sveltekit"; + + + // If you have custom handlers, make sure to place them after \`sentryHandle()\` in the \`sequence\` function. + export const handle = sequence(sentryHandle()); + + // If you have a custom error handler, pass it to \`handleErrorWithSentry\` + export const handleError = handleErrorWithSentry(); + " + `); + }); + + it("generates server hooks template with reduced data collection", () => { + const result = getServerHooksTemplate( + "https://sentry.io/123", + { + performance: true, + replay: true, + }, + true, + true, + ); + + expect(result).toMatchInlineSnapshot(` + "import { sequence } from "@sveltejs/kit/hooks"; + import { handleErrorWithSentry, sentryHandle } from "@sentry/sveltekit"; + import * as Sentry from '@sentry/sveltekit'; + + Sentry.init({ + dsn: 'https://sentry.io/123', + + tracesSampleRate: 1.0, + + // Turns off collection of data that could identify users. Adjust per category: + // https://docs.sentry.io/platforms/javascript/configuration/options/#dataCollection + dataCollection: { + userInfo: false, + graphQL: { document: false, variables: false }, + genAI: { inputs: false, outputs: false }, + databaseQueryData: false, + queues: false, + httpBodies: [], + httpHeaders: { deny: ["forwarded", "-ip", "remote-", "via", "-user"] }, + cookies: { deny: ["forwarded", "-ip", "remote-", "via", "-user"] }, + urlQueryParams: { deny: ["forwarded", "-ip", "remote-", "via", "-user"] }, + }, + + // uncomment the line below to enable Spotlight (https://spotlightjs.com) + // spotlight: import.meta.env.DEV, + }); + + // If you have custom handlers, make sure to place them after \`sentryHandle()\` in the \`sequence\` function. + export const handle = sequence(sentryHandle()); + + // If you have a custom error handler, pass it to \`handleErrorWithSentry\` + export const handleError = handleErrorWithSentry(); + " + `); + }); +}); + +describe("getInstrumentationServerTemplate", () => { + it("generates instrumentation.server template with all features enabled", () => { + const result = getInstrumentationServerTemplate( + "https://sentry.io/123", + { + performance: true, + }, + false, + ); + + expect(result).toMatchInlineSnapshot(` + "import * as Sentry from '@sentry/sveltekit'; + + Sentry.init({ + dsn: 'https://sentry.io/123', + + tracesSampleRate: 1.0, + // uncomment the line below to enable Spotlight (https://spotlightjs.com) + // spotlight: import.meta.env.DEV, + });" + `); + }); + + it("generates instrumentation.server template with only tracesSampleRate enabled", () => { + const result = getInstrumentationServerTemplate( + "https://sentry.io/123", + { + performance: true, + }, + false, + ); + + expect(result).toMatchInlineSnapshot(` + "import * as Sentry from '@sentry/sveltekit'; + + Sentry.init({ + dsn: 'https://sentry.io/123', + + tracesSampleRate: 1.0, + // uncomment the line below to enable Spotlight (https://spotlightjs.com) + // spotlight: import.meta.env.DEV, + });" + `); + }); + + it("generates instrumentation.server template without any extra features enabled", () => { + const result = getInstrumentationServerTemplate( + "https://sentry.io/123", + { + performance: false, + }, + false, + ); + + expect(result).toMatchInlineSnapshot(` + "import * as Sentry from '@sentry/sveltekit'; + + Sentry.init({ + dsn: 'https://sentry.io/123', + // uncomment the line below to enable Spotlight (https://spotlightjs.com) + // spotlight: import.meta.env.DEV, + });" + `); + }); + + it("generates instrumentation.server template with reduced data collection", () => { + const result = getInstrumentationServerTemplate( + "https://sentry.io/123", + { + performance: true, + }, + true, + ); + + expect(result).toMatchInlineSnapshot(` + "import * as Sentry from '@sentry/sveltekit'; + + Sentry.init({ + dsn: 'https://sentry.io/123', + + tracesSampleRate: 1.0, + // Turns off collection of data that could identify users. Adjust per category: + // https://docs.sentry.io/platforms/javascript/configuration/options/#dataCollection + dataCollection: { + userInfo: false, + graphQL: { document: false, variables: false }, + genAI: { inputs: false, outputs: false }, + databaseQueryData: false, + queues: false, + httpBodies: [], + httpHeaders: { deny: ["forwarded", "-ip", "remote-", "via", "-user"] }, + cookies: { deny: ["forwarded", "-ip", "remote-", "via", "-user"] }, + urlQueryParams: { deny: ["forwarded", "-ip", "remote-", "via", "-user"] }, + }, + // uncomment the line below to enable Spotlight (https://spotlightjs.com) + // spotlight: import.meta.env.DEV, + });" + `); + }); +}); + +describe("insertClientInitCall", () => { + it("should insert client init call with all features enabled", () => { + const originalHooksMod = parseModule(` + import { handleErrorWithSentry } from "@sentry/sveltekit"; + import * as Sentry from "@sentry/sveltekit"; + + export const handleError = handleErrorWithSentry(); + `); + + insertClientInitCall( + "https://sentry.io/123", + originalHooksMod, + { + performance: true, + replay: true, + }, + false, + ); + + const result = originalHooksMod.generate().code; + + expect(result).toMatchInlineSnapshot(` + "import { handleErrorWithSentry } from "@sentry/sveltekit"; + import * as Sentry from "@sentry/sveltekit"; + + // If you don't want to use Session Replay, remove the \`Replay\` integration, + // \`replaysSessionSampleRate\` and \`replaysOnErrorSampleRate\` options. + Sentry.init({ + dsn: "https://sentry.io/123", + tracesSampleRate: 1, + replaysSessionSampleRate: 0.1, + replaysOnErrorSampleRate: 1, + integrations: [Sentry.replayIntegration()], + dataCollection: { + // To disable sending user data and HTTP bodies, uncomment the lines below. For more info visit: + // https://docs.sentry.io/platforms/javascript/guides/sveltekit/configuration/options/#dataCollection + // userInfo: false, + // httpBodies: [], + }, + }) + + export const handleError = handleErrorWithSentry();" + `); + }); + + it("should insert client init call with performance disabled", () => { + const originalHooksMod = parseModule(` + import { handleErrorWithSentry } from "@sentry/sveltekit"; + import * as Sentry from "@sentry/sveltekit"; + + export const handleError = handleErrorWithSentry(); + `); + + insertClientInitCall( + "https://sentry.io/456", + originalHooksMod, + { + performance: false, + replay: true, + }, + false, + ); + + const result = originalHooksMod.generate().code; + + expect(result).toMatchInlineSnapshot(` + "import { handleErrorWithSentry } from "@sentry/sveltekit"; + import * as Sentry from "@sentry/sveltekit"; + + // If you don't want to use Session Replay, remove the \`Replay\` integration, + // \`replaysSessionSampleRate\` and \`replaysOnErrorSampleRate\` options. + Sentry.init({ + dsn: "https://sentry.io/456", + replaysSessionSampleRate: 0.1, + replaysOnErrorSampleRate: 1, + integrations: [Sentry.replayIntegration()], + dataCollection: { + // To disable sending user data and HTTP bodies, uncomment the lines below. For more info visit: + // https://docs.sentry.io/platforms/javascript/guides/sveltekit/configuration/options/#dataCollection + // userInfo: false, + // httpBodies: [], + }, + }) + + export const handleError = handleErrorWithSentry();" + `); + }); + + it("should insert client init call with replay disabled", () => { + const originalHooksMod = parseModule(` + import { handleErrorWithSentry } from "@sentry/sveltekit"; + import * as Sentry from "@sentry/sveltekit"; + + export const handleError = handleErrorWithSentry(); + `); + + insertClientInitCall( + "https://sentry.io/789", + originalHooksMod, + { + performance: true, + replay: false, + }, + false, + ); + + const result = originalHooksMod.generate().code; + + expect(result).toMatchInlineSnapshot(` + "import { handleErrorWithSentry } from "@sentry/sveltekit"; + import * as Sentry from "@sentry/sveltekit"; + + // If you don't want to use Session Replay, remove the \`Replay\` integration, + // \`replaysSessionSampleRate\` and \`replaysOnErrorSampleRate\` options. + Sentry.init({ + dsn: "https://sentry.io/789", + 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/sveltekit/configuration/options/#dataCollection + // userInfo: false, + // httpBodies: [], + }, + }) + + export const handleError = handleErrorWithSentry();" + `); + }); + + it("should insert client init call with all features disabled", () => { + const originalHooksMod = parseModule(` + import { handleErrorWithSentry } from "@sentry/sveltekit"; + import * as Sentry from "@sentry/sveltekit"; + + export const handleError = handleErrorWithSentry(); + `); + + insertClientInitCall( + "https://sentry.io/minimal", + originalHooksMod, + { + performance: false, + replay: false, + }, + false, + ); + + const result = originalHooksMod.generate().code; + + expect(result).toMatchInlineSnapshot(` + "import { handleErrorWithSentry } from "@sentry/sveltekit"; + import * as Sentry from "@sentry/sveltekit"; + + // If you don't want to use Session Replay, remove the \`Replay\` integration, + // \`replaysSessionSampleRate\` and \`replaysOnErrorSampleRate\` options. + Sentry.init({ + dsn: "https://sentry.io/minimal", + dataCollection: { + // To disable sending user data and HTTP bodies, uncomment the lines below. For more info visit: + // https://docs.sentry.io/platforms/javascript/guides/sveltekit/configuration/options/#dataCollection + // userInfo: false, + // httpBodies: [], + }, + }) + + export const handleError = handleErrorWithSentry();" + `); + }); + + it("should insert init call after imports", () => { + const originalHooksMod = parseModule(` + import { handleErrorWithSentry } from "@sentry/sveltekit"; + import { somethingElse } from "some-package"; + import * as Sentry from "@sentry/sveltekit"; + + export const handleError = handleErrorWithSentry(); + export const someOtherExport = somethingElse(); + `); + + insertClientInitCall( + "https://sentry.io/order-test", + originalHooksMod, + { + performance: true, + replay: false, + }, + false, + ); + + const result = originalHooksMod.generate().code; + + expect(result).toMatchInlineSnapshot(` + "import { handleErrorWithSentry } from "@sentry/sveltekit"; + import { somethingElse } from "some-package"; + import * as Sentry from "@sentry/sveltekit"; + + // If you don't want to use Session Replay, remove the \`Replay\` integration, + // \`replaysSessionSampleRate\` and \`replaysOnErrorSampleRate\` options. + Sentry.init({ + dsn: "https://sentry.io/order-test", + 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/sveltekit/configuration/options/#dataCollection + // userInfo: false, + // httpBodies: [], + }, + }) + + export const handleError = handleErrorWithSentry(); + export const someOtherExport = somethingElse();" + `); + }); + + it("should insert client init call with reduced data collection", () => { + const originalHooksMod = parseModule(` + import { handleErrorWithSentry } from "@sentry/sveltekit"; + import * as Sentry from "@sentry/sveltekit"; + + export const handleError = handleErrorWithSentry(); + `); + + insertClientInitCall( + "https://sentry.io/123", + originalHooksMod, + { + performance: true, + replay: true, + }, + true, + ); + + const result = originalHooksMod.generate().code; + + expect(result).toMatchInlineSnapshot(` + "import { handleErrorWithSentry } from "@sentry/sveltekit"; + import * as Sentry from "@sentry/sveltekit"; + + // If you don't want to use Session Replay, remove the \`Replay\` integration, + // \`replaysSessionSampleRate\` and \`replaysOnErrorSampleRate\` options. + Sentry.init({ + dsn: "https://sentry.io/123", + tracesSampleRate: 1, + replaysSessionSampleRate: 0.1, + replaysOnErrorSampleRate: 1, + integrations: [Sentry.replayIntegration()], + // Turns off collection of data that could identify users. Adjust per category: + // https://docs.sentry.io/platforms/javascript/configuration/options/#dataCollection + dataCollection: { + userInfo: false, + graphQL: { document: false, variables: false }, + genAI: { inputs: false, outputs: false }, + databaseQueryData: false, + queues: false, + httpBodies: [], + httpHeaders: { deny: ["forwarded", "-ip", "remote-", "via", "-user"] }, + cookies: { deny: ["forwarded", "-ip", "remote-", "via", "-user"] }, + urlQueryParams: { deny: ["forwarded", "-ip", "remote-", "via", "-user"] }, + }, + }) + + export const handleError = handleErrorWithSentry();" + `); + }); +}); + +describe("getSentryExampleSveltePage", () => { + it("generates example page template with Svelte 5", () => { + const result = getSentryExampleSveltePage({ + selfHosted: false, + url: "https://sentry.io", + orgSlug: "test-org", + projectId: "test-project", + isUsingSvelte5: true, + }); + + expect(result).toMatchInlineSnapshot(` + " + + + + 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. +

+ + + + {#if hasSentError} +

+ Sample error was sent to Sentry. +

+ {:else if !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.

+
+ {:else} +
+ {/if} +
+
+
+ + + " + `); + }); + + it("generates example page template pre-Svelte 5", () => { + const result = getSentryExampleSveltePage({ + selfHosted: false, + url: "https://sentry.io", + orgSlug: "test-org", + projectId: "test-project", + isUsingSvelte5: false, + }); + + expect(result).toMatchInlineSnapshot(` + " + + + + 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. +

+ + + + {#if hasSentError} +

+ Sample error was sent to Sentry. +

+ {:else if !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.

+
+ {:else} +
+ {/if} +
+
+
+ + + " + `); + }); + + it("generates an issues link for self-hosted", () => { + const result = getSentryExampleSveltePage({ + selfHosted: true, + url: "https://sAntry.com/", + orgSlug: "test-org", + projectId: "test-project", + isUsingSvelte5: true, + }); + + expect(result).toContain( + "https://sAntry.com/organizations/test-org/issues/?project=test-project", + ); + }); + + it("generates an issues link for saas", () => { + const result = getSentryExampleSveltePage({ + selfHosted: false, + url: "https://sentry.io", + orgSlug: "test-org", + projectId: "test-project", + isUsingSvelte5: true, + }); + + expect(result).toContain( + "https://test-org.sentry.io/issues/?project=test-project", + ); + }); +}); + +describe("getSentryExampleApiRoute", () => { + it("generates the correct API route template", () => { + const result = getSentryExampleApiRoute(); + expect(result).toMatchInlineSnapshot(` + "// This is just a very simple API route that throws an example error. + // Feel free to delete this file and the entire sentry route. + + export const GET = async () => { + throw new Error("Sentry Example API Route Error"); + }; + " + `); + }); +}); diff --git a/packages/cli/test/lib/wizard/sveltekit/utils.test.ts b/packages/cli/test/lib/wizard/sveltekit/utils.test.ts new file mode 100644 index 0000000000..8fc6b39204 --- /dev/null +++ b/packages/cli/test/lib/wizard/sveltekit/utils.test.ts @@ -0,0 +1,143 @@ +import { describe, it, expect } from "vitest"; +import { + getKitVersionBucket, + getSentrySvelteKitVitePluginImportPath, + getSvelteVersionBucket, + SENTRY_SVELTEKIT_SDK_RANGE, +} from "../../../../src/lib/wizard/sveltekit/utils.js"; + +describe("getKitVersionBucket", () => { + it('returns "none" if version is undefined', () => { + expect(getKitVersionBucket(undefined)).toBe("none"); + }); + + it('returns "none" if version is empty string', () => { + expect(getKitVersionBucket("")).toBe("none"); + }); + + it('returns "invalid" if version is contradictory', () => { + expect(getKitVersionBucket(">1.0.0 <1.0.0")).toBe("invalid"); + }); + + it('returns "invalid" if version is invalid', () => { + expect(getKitVersionBucket("latest")).toBe("invalid"); + }); + + it.each(["0.1.0", "0.9.9", "^0.5.0", "~0.12.0", "0"])( + 'returns "0.x" for versions < 1.0.0', + (version: string) => { + expect(getKitVersionBucket(version)).toBe("0.x"); + }, + ); + + it.each(["1.0.0", "1.1.0", "1.23.9", "^1.0.0", "~1.20.0", ">=1.0.0 <1.24.0"])( + 'returns ">=1.0.0 <1.24.0" for versions >= 1.0.0 and < 1.24.0', + (version: string) => { + expect(getKitVersionBucket(version)).toBe(">=1.0.0 <1.24.0"); + }, + ); + + it.each([ + "1.24.0", + "1.25.0", + "2.0.0", + "2.30.9", + "^1.24.0", + "~2.0.0", + ">=1.24.0 <2.31.0", + ])( + 'returns ">=1.24.0 <2.31.0" for versions >= 1.24.0 and < 2.31.0', + (version: string) => { + expect(getKitVersionBucket(version)).toBe(">=1.24.0 <2.31.0"); + }, + ); + + it.each(["2.31.0", "2.32.0", "3.0.0", "^2.31.0", "~3.0.0", ">=2.31.0"])( + 'returns ">=2.31.0" for versions >= 2.31.0', + (version: string) => { + expect(getKitVersionBucket(version)).toBe(">=2.31.0"); + }, + ); +}); + +describe("getSvelteVersionBucket", () => { + it('returns "none" if version is undefined', () => { + expect(getSvelteVersionBucket(undefined)).toBe("none"); + }); + + it('returns "none" if version is empty string', () => { + expect(getSvelteVersionBucket("")).toBe("none"); + }); + + it('returns "invalid" if version is contradictory', () => { + expect(getSvelteVersionBucket(">1.0.0 <1.0.0")).toBe("invalid"); + }); + + it('returns "invalid" if version is invalid', () => { + expect(getSvelteVersionBucket("latest")).toBe("invalid"); + }); + + it.each(["0.1.0", "1.0.0", "2.9.9", "^2.5.0", "~2.0.0"])( + 'returns "<3.0.0" for versions < 3.0.0', + (version: string) => { + expect(getSvelteVersionBucket(version)).toBe("<3.0.0"); + }, + ); + + it.each(["3.0.0", "3.1.0", "3.59.9", "^3.0.0", "~3.50.0"])( + 'returns "3.x" for versions >= 3.0.0 and < 4.0.0', + (version: string) => { + expect(getSvelteVersionBucket(version)).toBe("3.x"); + }, + ); + + it.each(["4.0.0", "4.1.0", "4.99.9", "^4.0.0", "~4.50.0"])( + 'returns "4.x" for versions >= 4.0.0 and < 5.0.0', + (version: string) => { + expect(getSvelteVersionBucket(version)).toBe("4.x"); + }, + ); + + it.each(["5.0.0", "5.1.0", "5.99.9", "^5.0.0", "~5.50.0"])( + 'returns "5.x" for versions >= 5.0.0 and < 6.0.0', + (version: string) => { + expect(getSvelteVersionBucket(version)).toBe("5.x"); + }, + ); + + it.each(["6.0.0", "6.1.0", "10.0.0", "^6.0.0", "~10.0.0"])( + 'returns ">5.x" for versions >= 6.0.0', + (version: string) => { + expect(getSvelteVersionBucket(version)).toBe(">5.x"); + }, + ); +}); + +describe("getSentrySvelteKitVitePluginImportPath", () => { + it.each(["11.0.0", "^11.0.0", "11.0.0-beta.2", "~11.2.0", "12.0.0"])( + "returns the /vite subpath for SDK %s", + (version) => { + expect(getSentrySvelteKitVitePluginImportPath(version)).toBe( + "@sentry/sveltekit/vite", + ); + }, + ); + + it.each(["10.74.0", "^10.0.0", "~10.73.0", "9.47.1"])( + "returns the root export for SDK %s", + (version) => { + expect(getSentrySvelteKitVitePluginImportPath(version)).toBe( + "@sentry/sveltekit", + ); + }, + ); + + it.each([undefined, "", "latest", "workspace:*"])( + "falls back to the pinned install range when the version is unknown (%s)", + (version) => { + expect(getSentrySvelteKitVitePluginImportPath(version)).toBe( + getSentrySvelteKitVitePluginImportPath(SENTRY_SVELTEKIT_SDK_RANGE), + ); + }, + ); +}); diff --git a/packages/cli/test/tsconfig.json b/packages/cli/test/tsconfig.json index 07b7248608..b626e81b70 100644 --- a/packages/cli/test/tsconfig.json +++ b/packages/cli/test/tsconfig.json @@ -3,5 +3,6 @@ "compilerOptions": { "lib": ["ESNext", "DOM"] }, - "include": ["**/*.ts", "**/*.tsx"] + "include": ["**/*.ts", "**/*.tsx"], + "exclude": ["lib/wizard/**/fixtures/**"] } From 07f26e0331396a9d53b4eb079ab82d147e63a9d1 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:31:04 +0000 Subject: [PATCH 05/17] fix(cli): fix wizard CI after the scaffold merge, upload Remix maps with v4 CI failed on the SvelteKit, Remix and React Router flows: - They still passed `promoCode` to `printWelcome()`, which the scaffold removed with the sign-up and partner flags. - The sentry-wizard codemod fixtures under `test/lib/wizard/**/fixtures/` are excluded from the test tsconfig, so the tsconfig policy now lists them as unchecked on purpose, like the cli3to4 codemod fixtures. The Remix build script used `npx @sentry/remix --upload-sourcemaps`, which runs the legacy sentry-cli. The wizard must not depend on sentry-cli, so the script now runs `sentry sourcemap upload` on the same build path and URL prefix, and the wizard installs `sentry` as a dev dependency so the script works in CI. The org, project and self-hosted URL move from script flags into `.sentryclirc`, which v4 reads; the wizard tells the user to set the matching env vars in CI. --- .../react-router/react-router-wizard.ts | 1 - .../cli/src/lib/wizard/remix/remix-wizard.ts | 45 +++++++++-- .../cli/src/lib/wizard/remix/sdk-setup.ts | 17 +++-- .../lib/wizard/sveltekit/sveltekit-wizard.ts | 3 +- .../lib/wizard/remix/build-script.test.ts | 76 ++++--------------- scripts/tsconfig-policy.test.mjs | 5 ++ 6 files changed, 69 insertions(+), 78 deletions(-) diff --git a/packages/cli/src/lib/wizard/react-router/react-router-wizard.ts b/packages/cli/src/lib/wizard/react-router/react-router-wizard.ts index 20854aecef..e699611e6f 100644 --- a/packages/cli/src/lib/wizard/react-router/react-router-wizard.ts +++ b/packages/cli/src/lib/wizard/react-router/react-router-wizard.ts @@ -82,7 +82,6 @@ async function runReactRouterWizardWithTelemetry( ): Promise { printWelcome({ wizardName: "Sentry React Router Wizard", - promoCode: options.promoCode, }); const packageJson = await getPackageDotJson(); diff --git a/packages/cli/src/lib/wizard/remix/remix-wizard.ts b/packages/cli/src/lib/wizard/remix/remix-wizard.ts index 9c427af1d2..f57fe043eb 100644 --- a/packages/cli/src/lib/wizard/remix/remix-wizard.ts +++ b/packages/cli/src/lib/wizard/remix/remix-wizard.ts @@ -14,6 +14,7 @@ import { addDotEnvSentryBuildPluginFile, addSentryCliConfig, askShouldCreateExamplePage, + type CliSetupConfig, confirmContinueIfNoOrDirtyGitRepo, ensurePackageIsInstalled, featureSelectionPrompt, @@ -53,6 +54,16 @@ import { isHydrogenApp } from "./utils.js"; import { abortIfSpotlightNotSupported } from "../utils/abort-if-sportlight-not-supported.js"; import { warnIfNodeVersionUnsupportedBySdkV11 } from "../utils/node-version.js"; +/** + * `.sentryclirc` with `[defaults] url` as well, so `sentry sourcemap upload` + * in the build script reaches a self-hosted Sentry. + */ +const sentryCliRcWithUrl: CliSetupConfig = { + ...rcCliSetupConfig, + likelyAlreadyHasUrl: (contents) => /^\s*url\s*=./m.test(contents), + urlContent: (url) => `[defaults]\nurl=${url}`, +}; + export async function runRemixWizard(options: WizardOptions): Promise { return await withTelemetry( { @@ -67,11 +78,10 @@ export async function runRemixWizard(options: WizardOptions): Promise { async function runRemixWizardWithTelemetry( options: WizardOptions, ): Promise { - const { promoCode, telemetryEnabled, forceInstall } = options; + const { telemetryEnabled, forceInstall } = options; printWelcome({ wizardName: "Sentry Remix Wizard", - promoCode, telemetryEnabled, }); @@ -162,14 +172,33 @@ async function runRemixWizardWithTelemetry( } else { await traceStep("Update build script for sourcemap uploads", async () => { try { - await updateBuildScript({ - org: selectedProject.organization.slug, - project: selectedProject.slug, - url: selfHosted ? sentryUrl : undefined, - isHydrogen: isHydrogenApp(packageJson), + // The build script runs the project's own `sentry` CLI, so CI + // can run it too. + await installPackage({ + packageName: "sentry", + alreadyInstalled: hasPackageInstalled("sentry", packageJson), + devDependency: true, + forceInstall, }); - await addSentryCliConfig({ authToken }, rcCliSetupConfig); + await updateBuildScript({ isHydrogen: isHydrogenApp(packageJson) }); + + await addSentryCliConfig( + { + authToken, + org: selectedProject.organization.slug, + project: selectedProject.slug, + url: selfHosted ? sentryUrl : undefined, + }, + sentryCliRcWithUrl, + ); + clack.log.info( + `${chalk.cyan(".sentryclirc")} stays out of git. In CI, set ${chalk.cyan( + "SENTRY_AUTH_TOKEN", + )}, ${chalk.cyan("SENTRY_ORG")} and ${chalk.cyan( + "SENTRY_PROJECT", + )} for the upload.`, + ); } catch (e) { clack.log .warn(`Could not update build script to generate and upload sourcemaps. diff --git a/packages/cli/src/lib/wizard/remix/sdk-setup.ts b/packages/cli/src/lib/wizard/remix/sdk-setup.ts index ef128c2625..0b31540d96 100644 --- a/packages/cli/src/lib/wizard/remix/sdk-setup.ts +++ b/packages/cli/src/lib/wizard/remix/sdk-setup.ts @@ -331,10 +331,12 @@ export async function instrumentRootRoute(isTS?: boolean): Promise { ); } +/** + * Make the `build` script build with source maps and upload them with + * `sentry sourcemap upload`, which injects the debug IDs. The org, project + * and URL come from `.sentryclirc`, which the wizard writes next to it. + */ export async function updateBuildScript(args: { - org: string; - project: string; - url?: string | undefined; isHydrogen: boolean; }): Promise { const packageJson = await getPackageDotJson(); @@ -347,10 +349,11 @@ export async function updateBuildScript(args: { ? "shopify hydrogen build" : "remix build"; - const instrumentedBuildCommand = - `${buildCommand} --sourcemap && npx @sentry/remix --upload-sourcemaps --org ${args.org} --project ${args.project}` + - (args.url ? ` --url ${args.url}` : "") + - (args.isHydrogen ? " --buildPath ./dist" : ""); + // The same build path and URL prefix `@sentry/remix --upload-sourcemaps` + // used. + const buildPath = args.isHydrogen ? "./dist" : "./public/build"; + // oxlint-disable-next-line sentry-cli/no-hardcoded-sentry-command -- a package.json script that runs the project's own `sentry` devDependency, not a hint + const instrumentedBuildCommand = `${buildCommand} --sourcemap && sentry sourcemap upload ${buildPath} --url-prefix "~/build/"`; if (!packageJson.scripts["build"]) { packageJson.scripts["build"] = instrumentedBuildCommand; diff --git a/packages/cli/src/lib/wizard/sveltekit/sveltekit-wizard.ts b/packages/cli/src/lib/wizard/sveltekit/sveltekit-wizard.ts index 58ed06cf04..51f3d03876 100644 --- a/packages/cli/src/lib/wizard/sveltekit/sveltekit-wizard.ts +++ b/packages/cli/src/lib/wizard/sveltekit/sveltekit-wizard.ts @@ -66,11 +66,10 @@ export async function runSvelteKitWizard( export async function runSvelteKitWizardWithTelemetry( options: WizardOptions, ): Promise { - const { promoCode, telemetryEnabled, forceInstall } = options; + const { telemetryEnabled, forceInstall } = options; printWelcome({ wizardName: "Sentry SvelteKit Wizard", - promoCode, telemetryEnabled, }); diff --git a/packages/cli/test/lib/wizard/remix/build-script.test.ts b/packages/cli/test/lib/wizard/remix/build-script.test.ts index 1ad6c3283e..6d7c8ec7a1 100644 --- a/packages/cli/test/lib/wizard/remix/build-script.test.ts +++ b/packages/cli/test/lib/wizard/remix/build-script.test.ts @@ -37,51 +37,19 @@ describe("updateBuildScript", () => { vi.clearAllMocks(); }); - it("uses npx @sentry/remix --upload-sourcemaps for the upload command", async () => { - await updateBuildScript({ - org: "my-org", - project: "my-project", - isHydrogen: false, - }); - - expect(writeFileSpy).toHaveBeenCalledWith( - expect.stringContaining("package.json"), - expect.stringContaining( - "npx @sentry/remix --upload-sourcemaps --org my-org --project my-project", - ), - ); - }); - - it("replaces the remix build command with sourcemap flag and upload", async () => { - await updateBuildScript({ - org: "my-org", - project: "my-project", - isHydrogen: false, - }); + it("uploads with sentry sourcemap upload", async () => { + await updateBuildScript({ isHydrogen: false }); - expect(writeFileSpy).toHaveBeenCalledWith( - expect.stringContaining("package.json"), - expect.stringContaining( - "remix build --sourcemap && npx @sentry/remix --upload-sourcemaps", - ), - ); - }); - - it("includes --url flag when a custom url is provided", async () => { - await updateBuildScript({ - org: "my-org", - project: "my-project", - url: "https://self-hosted.example.com", - isHydrogen: false, + expect(JSON.parse(writeFileSpy.mock.calls[0]?.[1] as string)).toEqual({ + scripts: { + build: + 'remix build --sourcemap && sentry sourcemap upload ./public/build --url-prefix "~/build/"', + }, + version: "1.0.0", }); - - expect(writeFileSpy).toHaveBeenCalledWith( - expect.stringContaining("package.json"), - expect.stringContaining("--url https://self-hosted.example.com"), - ); }); - it("uses shopify hydrogen build for hydrogen apps", async () => { + it("uploads ./dist for hydrogen apps", async () => { vi.mocked(getPackageDotJson).mockResolvedValue({ scripts: { build: "shopify hydrogen build", @@ -89,16 +57,12 @@ describe("updateBuildScript", () => { version: "1.0.0", }); - await updateBuildScript({ - org: "my-org", - project: "my-project", - isHydrogen: true, - }); + await updateBuildScript({ isHydrogen: true }); expect(writeFileSpy).toHaveBeenCalledWith( expect.stringContaining("package.json"), expect.stringContaining( - "shopify hydrogen build --sourcemap && npx @sentry/remix --upload-sourcemaps --org my-org --project my-project --buildPath ./dist", + 'shopify hydrogen build --sourcemap && sentry sourcemap upload ./dist --url-prefix \\"~/build/\\"', ), ); }); @@ -109,16 +73,12 @@ describe("updateBuildScript", () => { version: "1.0.0", }); - await updateBuildScript({ - org: "my-org", - project: "my-project", - isHydrogen: false, - }); + await updateBuildScript({ isHydrogen: false }); expect(writeFileSpy).toHaveBeenCalledWith( expect.stringContaining("package.json"), expect.stringContaining( - "remix build --sourcemap && npx @sentry/remix --upload-sourcemaps", + "remix build --sourcemap && sentry sourcemap upload ./public/build", ), ); }); @@ -131,12 +91,8 @@ describe("updateBuildScript", () => { version: "1.0.0", }); - await expect( - updateBuildScript({ - org: "my-org", - project: "my-project", - isHydrogen: false, - }), - ).rejects.toThrow("build` script doesn't contain a known build command"); + await expect(updateBuildScript({ isHydrogen: false })).rejects.toThrow( + "build` script doesn't contain a known build command", + ); }); }); diff --git a/scripts/tsconfig-policy.test.mjs b/scripts/tsconfig-policy.test.mjs index 1d36a8cc59..8c8e647cce 100644 --- a/scripts/tsconfig-policy.test.mjs +++ b/scripts/tsconfig-policy.test.mjs @@ -23,6 +23,11 @@ const UNCHECKED = [ reason: "codemod input and expected-output fixtures, compared as text by `jssg test`", }, + { + pattern: /^packages\/cli\/test\/lib\/wizard\/.*\/fixtures\//, + reason: + "wizard codemod input fixtures copied from sentry-wizard, read as text by the codemod tests", + }, { pattern: /^packages\/logger\/test\/package\/consumer\//, reason: From 39e20d513acc8f5c30e2611396fad46aa89bdac7 Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Thu, 26 Nov 2026 18:10:45 +0000 Subject: [PATCH 06/17] fix(cli): address review findings in sentry wizard - Skip the `.sentryclirc` URL check, like `sentry init`: the wizard picks its instance (`--url`, `--saas` or a prompt) before it logs in. - Use the stored login's instance for `sentryUrl` when none was chosen, and log in again when the stored login is for another instance. - Link self-hosted users to `/settings//auth-tokens/`. - Leave an unparseable MCP config alone (show the copy-paste fallback), and let a cancel inside the MCP setup stop the wizard. - Resolve `catalog:` and `catalog:default` against both pnpm default catalog forms. - Find an existing `SENTRY_AUTH_TOKEN` after the comment header of `.env.sentry-build-plugin`, so re-runs don't add a second one. - Run Windows formatters with Node in the standalone binary, where `process.execPath` is `sentry`. - Ask before updating an `@sentry/nextjs` listed in devDependencies, and treat an unknown SDK version as the `^11` the wizard installs. Co-Authored-By: BYK <126780+BYK@users.noreply.github.com> --- packages/cli/src/commands/wizard.ts | 3 + .../src/lib/wizard/nextjs/nextjs-wizard.ts | 5 +- .../cli/src/lib/wizard/utils/clack/index.ts | 28 ++--- .../src/lib/wizard/utils/clack/mcp-config.ts | 22 +++- .../cli/src/lib/wizard/utils/package-json.ts | 12 ++- .../cli/src/lib/wizard/utils/project-data.ts | 16 ++- .../lib/wizard/utils/clack/mcp-config.test.ts | 101 ++++++++++++------ .../lib/wizard/utils/package-json.test.ts | 18 ++++ .../lib/wizard/utils/project-data.test.ts | 72 ++++++++++++- 9 files changed, 211 insertions(+), 66 deletions(-) diff --git a/packages/cli/src/commands/wizard.ts b/packages/cli/src/commands/wizard.ts index 2b291ef787..71f4b7fefd 100644 --- a/packages/cli/src/commands/wizard.ts +++ b/packages/cli/src/commands/wizard.ts @@ -79,6 +79,9 @@ function envValue(name: string): string | undefined { export const wizardCommand = buildCommand({ auth: false, + // The wizard picks the Sentry instance itself (`--url`, `--saas` or a + // prompt) before it logs in, like `sentry init`. + skipRcUrlCheck: true, docs: { brief: topLevelBrief("wizard"), fullDescription: diff --git a/packages/cli/src/lib/wizard/nextjs/nextjs-wizard.ts b/packages/cli/src/lib/wizard/nextjs/nextjs-wizard.ts index fd14f9bb03..cb02e11492 100644 --- a/packages/cli/src/lib/wizard/nextjs/nextjs-wizard.ts +++ b/packages/cli/src/lib/wizard/nextjs/nextjs-wizard.ts @@ -155,7 +155,7 @@ The wizard will continue, but you may need to upgrade Next.js for the SDK to wor await installPackage({ packageName: "@sentry/nextjs@^11", packageNameDisplayLabel: "@sentry/nextjs", - alreadyInstalled: !!packageJson.dependencies?.["@sentry/nextjs"], + alreadyInstalled: sdkAlreadyInstalled, forceInstall, }); @@ -185,7 +185,8 @@ The wizard will import ${chalk.cyan( // From v11 on, the SDK collects rich context by default, so offer to // reduce collection of data that can identify users. const reduceDataCollection = - sdkSupportsDataCollection(installedSdkVersion, "^10.73.0") && + // An unknown version (e.g. `workspace:*`) is the `^11` the wizard asked for. + sdkSupportsDataCollection(installedSdkVersion, "^11") && (await askShouldReduceDataCollection()); let selectedProject: SentryProjectData; diff --git a/packages/cli/src/lib/wizard/utils/clack/index.ts b/packages/cli/src/lib/wizard/utils/clack/index.ts index 0bdb01dc8c..a076b5049b 100644 --- a/packages/cli/src/lib/wizard/utils/clack/index.ts +++ b/packages/cli/src/lib/wizard/utils/clack/index.ts @@ -24,6 +24,7 @@ import { sentry } from "../../../app-identity.js"; import { CLI_VERSION } from "../../../constants.js"; import { reportCliError } from "../../../error-reporting.js"; import { WizardExitError } from "../../../errors.js"; +import { isSea } from "../../../react-native/wrap-call.js"; import { Sentry, traceStep } from "../../telemetry.js"; import { debug } from "../debug.js"; import { getUncommittedOrUntrackedFilePaths, isInGitRepo } from "../git.js"; @@ -717,9 +718,7 @@ SENTRY_AUTH_TOKEN=${authToken} if (dotEnvFileExists) { const dotEnvFileContent = readFileSync(dotEnvFilePath, "utf8"); - const hasAuthToken = !!dotEnvFileContent.match( - /^\s*SENTRY_AUTH_TOKEN\s*=/g, - ); + const hasAuthToken = /^\s*SENTRY_AUTH_TOKEN\s*=/m.test(dotEnvFileContent); if (hasAuthToken) { clack.log.warn( @@ -887,7 +886,9 @@ function runFormatterCommand( new Error(`Could not resolve the ${packageName} binary.`), ); } - command = process.execPath; + // In the standalone binary, `process.execPath` is `sentry` itself, not + // Node, so run the formatter with the project's Node. + command = isSea() ? "node" : process.execPath; args = [binPath, ...subArgs, "--", ...files]; } else { command = "npx"; @@ -1265,16 +1266,15 @@ export async function getPackageManager( return fallback; } - const selectedPackageManager: PackageManager | symbol = - await abortIfCancelled( - clack.select({ - message: "Please select your package manager.", - options: packageManagers.map((packageManager) => ({ - value: packageManager, - label: packageManager.label, - })), - }), - ); + const selectedPackageManager = await abortIfCancelled( + clack.select({ + message: "Please select your package manager.", + options: packageManagers.map((packageManager) => ({ + value: packageManager, + label: packageManager.label, + })), + }), + ); globalWithSentryWizard.__sentry_wizard_cached_package_manager = selectedPackageManager; diff --git a/packages/cli/src/lib/wizard/utils/clack/mcp-config.ts b/packages/cli/src/lib/wizard/utils/clack/mcp-config.ts index 867c9c0140..0d01374036 100644 --- a/packages/cli/src/lib/wizard/utils/clack/mcp-config.ts +++ b/packages/cli/src/lib/wizard/utils/clack/mcp-config.ts @@ -10,6 +10,7 @@ import { Sentry } from "../../telemetry.js"; import chalk from "chalk"; import { clack } from "./prompts.js"; import { abortIfCancelled, showCopyPasteInstructions } from "./index.js"; +import { WizardExitError } from "../../../errors.js"; import { debug } from "../debug.js"; const SENTRY_MCP_BASE_URL = "https://mcp.sentry.dev/mcp"; @@ -48,14 +49,23 @@ function ensureDir(dirpath: string): void { mkdirSync(dirpath, { recursive: true }); } +/** + * The parsed JSON in `filepath`, or `null` when the file doesn't exist. + * + * @throws {SyntaxError} When the file exists but isn't valid JSON, so the + * caller shows the copy-paste fallback instead of overwriting it + */ async function readJsonIfExists(filepath: string): Promise { + let txt: string; try { - const txt = await promises.readFile(filepath, "utf8"); - return JSON.parse(txt) as unknown; + txt = await promises.readFile(filepath, "utf8"); } catch (error) { - debug(error); - return null; + if ((error as NodeJS.ErrnoException).code === "ENOENT") { + return null; + } + throw error; } + return JSON.parse(txt) as unknown; } async function writeJson(filepath: string, obj: unknown): Promise { @@ -600,6 +610,10 @@ export async function offerProjectScopedMcpConfig( } Sentry.setTag(`mcp-config-${editor}-success`, true); } catch (e) { + if (e instanceof WizardExitError) { + throw e; + } + debug(e); Sentry.setTag(`mcp-config-${editor}-success`, false); Sentry.setTag("mcp-config-fallback", true); clack.log.warn( diff --git a/packages/cli/src/lib/wizard/utils/package-json.ts b/packages/cli/src/lib/wizard/utils/package-json.ts index 1de6728d35..775d4f8212 100644 --- a/packages/cli/src/lib/wizard/utils/package-json.ts +++ b/packages/cli/src/lib/wizard/utils/package-json.ts @@ -135,10 +135,14 @@ function resolveCatalogVersion( return undefined; } - const catalog = - catalogName === "" ? workspace.catalog : workspace.catalogs?.[catalogName]; - - return catalog?.[packageName]; + // pnpm treats `catalog:` and `catalogs.default` as the same catalog. + if (catalogName === "" || catalogName === "default") { + return ( + workspace.catalog?.[packageName] ?? + workspace.catalogs?.["default"]?.[packageName] + ); + } + return workspace.catalogs?.[catalogName]?.[packageName]; } /** diff --git a/packages/cli/src/lib/wizard/utils/project-data.ts b/packages/cli/src/lib/wizard/utils/project-data.ts index 87718dcbb9..0e4b856c32 100644 --- a/packages/cli/src/lib/wizard/utils/project-data.ts +++ b/packages/cli/src/lib/wizard/utils/project-data.ts @@ -42,8 +42,12 @@ import { logger } from "../../logger.js"; import { OAUTH_SCOPES, resolveOAuthScopeString } from "../../oauth.js"; import { resolveOrCreateTeam } from "../../resolve-team.js"; import { ensureScopesForAction } from "../../scope-recovery.js"; -import { getSentryBaseUrl, isSentrySaasUrl } from "../../sentry-urls.js"; -import { registerLoginTrustAnchor } from "../../token-host.js"; +import { isSentrySaasUrl } from "../../sentry-urls.js"; +import { getApiBaseUrl } from "../../sentry-client.js"; +import { + isRequestOriginTrusted, + registerLoginTrustAnchor, +} from "../../token-host.js"; import { slugify } from "../../utils.js"; import { sentry } from "../../app-identity.js"; import type { @@ -130,7 +134,8 @@ export async function getOrAskForProjectData( ); const handoffOrg = await traceStep("login", ensureLoggedIn); - const sentryUrl = withTrailingSlash(getSentryBaseUrl()); + // The chosen instance, or the stored login's when none was chosen. + const sentryUrl = withTrailingSlash(getApiBaseUrl()); const selfHosted = !isSentrySaasUrl(sentryUrl); Sentry.setTag("url", sentryUrl); Sentry.setTag("self-hosted", selfHosted); @@ -261,7 +266,8 @@ async function ensureLoggedIn(): Promise { return handoff.organizationSlug; } - if (getAuthConfig()) { + // A login for another instance than the selected one can't be used. + if (getAuthConfig() && isRequestOriginTrusted(getApiBaseUrl())) { Sentry.setTag("login-method", "stored"); return; } @@ -464,7 +470,7 @@ async function createAuthToken( Sentry.setTag("auth-token-created", false); const settingsUrl = isSentrySaasUrl(sentryUrl) ? `https://${orgSlug}.sentry.io/settings/auth-tokens/` - : `${sentryUrl}organizations/${orgSlug}/settings/auth-tokens/`; + : `${sentryUrl}settings/${orgSlug}/auth-tokens/`; clack.log.warn( `Could not create an auth token for you. We'll add a placeholder (${chalk.cyan( `"${DUMMY_AUTH_TOKEN}"`, diff --git a/packages/cli/test/lib/wizard/utils/clack/mcp-config.test.ts b/packages/cli/test/lib/wizard/utils/clack/mcp-config.test.ts index af614d9793..2a83ff5028 100644 --- a/packages/cli/test/lib/wizard/utils/clack/mcp-config.test.ts +++ b/packages/cli/test/lib/wizard/utils/clack/mcp-config.test.ts @@ -13,8 +13,16 @@ import * as fs from "node:fs"; import * as path from "node:path"; // oxlint-disable-next-line sentry-cli/no-namespace-import -- needed for spyOn mocking import * as childProcess from "node:child_process"; +import { WizardExitError } from "../../../../../src/lib/errors.js"; import { offerProjectScopedMcpConfig } from "../../../../../src/lib/wizard/utils/clack/mcp-config.js"; +/** The error `fs.promises.readFile` rejects with for a missing file. */ +function fileNotFound(): NodeJS.ErrnoException { + return Object.assign(new Error("ENOENT: no such file or directory"), { + code: "ENOENT", + }); +} + // Mock types for better type safety type ConfigContent = { mcpServers?: Record; @@ -115,9 +123,7 @@ describe("mcp-config", () => { (value: unknown) => Promise.resolve(value), ); - const mockReadFile = vi - .fn() - .mockRejectedValue(new Error("File not found")); + const mockReadFile = vi.fn().mockRejectedValue(fileNotFound()); const mockWriteFile = vi.fn().mockResolvedValue(undefined); const mockMkdirSync = vi.fn(); @@ -164,9 +170,7 @@ describe("mcp-config", () => { (value: unknown) => Promise.resolve(value), ); - const mockReadFile = vi - .fn() - .mockRejectedValue(new Error("File not found")); + const mockReadFile = vi.fn().mockRejectedValue(fileNotFound()); const mockWriteFile = vi.fn().mockResolvedValue(undefined); const mockMkdirSync = vi.fn(); @@ -196,9 +200,7 @@ describe("mcp-config", () => { (value: unknown) => Promise.resolve(value), ); - const mockReadFile = vi - .fn() - .mockRejectedValue(new Error("File not found")); + const mockReadFile = vi.fn().mockRejectedValue(fileNotFound()); const mockWriteFile = vi.fn().mockResolvedValue(undefined); const mockMkdirSync = vi.fn(); @@ -349,9 +351,7 @@ describe("mcp-config", () => { (value: unknown) => Promise.resolve(value), ); - const mockReadFile = vi - .fn() - .mockRejectedValue(new Error("File not found")); + const mockReadFile = vi.fn().mockRejectedValue(fileNotFound()); const mockWriteFile = vi.fn().mockResolvedValue(undefined); const mockMkdirSync = vi.fn(); @@ -435,9 +435,7 @@ describe("mcp-config", () => { (value: unknown) => Promise.resolve(value), ); - const mockReadFile = vi - .fn() - .mockRejectedValue(new Error("File not found")); + const mockReadFile = vi.fn().mockRejectedValue(fileNotFound()); const mockWriteFile = vi .fn() .mockRejectedValue(new Error("Permission denied")); @@ -462,7 +460,7 @@ describe("mcp-config", () => { ); }); - it("should handle file write errors gracefully for Cursor", async () => { + it("shows the fallback instead of overwriting an unparseable config", async () => { const { clack, clackUtils } = await getMocks(); vi.mocked(clack.select).mockResolvedValueOnce("yes"); @@ -473,7 +471,52 @@ describe("mcp-config", () => { const mockReadFile = vi .fn() - .mockRejectedValue(new Error("File not found")); + .mockResolvedValue('{ "mcpServers": { "OtherServer": {}, } }'); + const mockWriteFile = vi.fn().mockResolvedValue(undefined); + + vi.spyOn(fs.promises, "readFile").mockImplementation(mockReadFile); + vi.spyOn(fs.promises, "writeFile").mockImplementation(mockWriteFile); + vi.spyOn(fs, "mkdirSync").mockImplementation(vi.fn()); + + await offerProjectScopedMcpConfig(); + + expect(mockWriteFile).not.toHaveBeenCalled(); + expect(clackUtils.showCopyPasteInstructions).toHaveBeenCalledWith( + expect.objectContaining({ filename: path.join(".cursor", "mcp.json") }), + ); + }); + + it("lets a WizardExitError from an editor's setup stop the wizard", async () => { + const { clack, clackUtils } = await getMocks(); + + vi.mocked(clack.select).mockResolvedValueOnce("yes"); + vi.mocked(clack.multiselect).mockResolvedValueOnce(["cursor", "vscode"]); + vi.mocked(clackUtils.abortIfCancelled).mockImplementation( + (value: unknown) => Promise.resolve(value), + ); + + const mockWriteFile = vi.fn().mockRejectedValue(new WizardExitError(0)); + vi.spyOn(fs.promises, "readFile").mockRejectedValue(fileNotFound()); + vi.spyOn(fs.promises, "writeFile").mockImplementation(mockWriteFile); + vi.spyOn(fs, "mkdirSync").mockImplementation(vi.fn()); + + await expect(offerProjectScopedMcpConfig()).rejects.toThrow( + WizardExitError, + ); + expect(mockWriteFile).toHaveBeenCalledTimes(1); + expect(clackUtils.showCopyPasteInstructions).not.toHaveBeenCalled(); + }); + + it("should handle file write errors gracefully for Cursor", async () => { + const { clack, clackUtils } = await getMocks(); + + vi.mocked(clack.select).mockResolvedValueOnce("yes"); + vi.mocked(clack.multiselect).mockResolvedValueOnce(["cursor"]); + vi.mocked(clackUtils.abortIfCancelled).mockImplementation( + (value: unknown) => Promise.resolve(value), + ); + + const mockReadFile = vi.fn().mockRejectedValue(fileNotFound()); const mockWriteFile = vi .fn() .mockRejectedValue(new Error("Permission denied")); @@ -507,9 +550,7 @@ describe("mcp-config", () => { (value: unknown) => Promise.resolve(value), ); - const mockReadFile = vi - .fn() - .mockRejectedValue(new Error("File not found")); + const mockReadFile = vi.fn().mockRejectedValue(fileNotFound()); const mockWriteFile = vi .fn() .mockRejectedValue(new Error("Permission denied")); @@ -539,9 +580,7 @@ describe("mcp-config", () => { (value: unknown) => Promise.resolve(value), ); - const mockReadFile = vi - .fn() - .mockRejectedValue(new Error("File not found")); + const mockReadFile = vi.fn().mockRejectedValue(fileNotFound()); const mockWriteFile = vi .fn() .mockRejectedValue(new Error("Permission denied")); @@ -608,9 +647,7 @@ describe("mcp-config", () => { (value: unknown) => Promise.resolve(value), ); - const mockReadFile = vi - .fn() - .mockRejectedValue(new Error("File not found")); + const mockReadFile = vi.fn().mockRejectedValue(fileNotFound()); const mockWriteFile = vi.fn().mockResolvedValue(undefined); const mockMkdirSync = vi.fn().mockImplementation(() => { throw new Error("Permission denied"); @@ -823,9 +860,7 @@ describe("mcp-config", () => { (value: unknown) => Promise.resolve(value), ); - const mockReadFile = vi - .fn() - .mockRejectedValue(new Error("File not found")); + const mockReadFile = vi.fn().mockRejectedValue(fileNotFound()); const mockWriteFile = vi.fn().mockResolvedValue(undefined); const mockMkdirSync = vi.fn(); @@ -944,9 +979,7 @@ describe("mcp-config", () => { (value: unknown) => Promise.resolve(value), ); - const mockReadFile = vi - .fn() - .mockRejectedValue(new Error("File not found")); + const mockReadFile = vi.fn().mockRejectedValue(fileNotFound()); const mockWriteFile = vi.fn().mockResolvedValue(undefined); const mockMkdirSync = vi.fn(); @@ -1015,9 +1048,7 @@ describe("mcp-config", () => { (value: unknown) => Promise.resolve(value), ); - const mockReadFile = vi - .fn() - .mockRejectedValue(new Error("File not found")); + const mockReadFile = vi.fn().mockRejectedValue(fileNotFound()); const mockWriteFile = vi .fn() .mockResolvedValueOnce(undefined) // Cursor succeeds diff --git a/packages/cli/test/lib/wizard/utils/package-json.test.ts b/packages/cli/test/lib/wizard/utils/package-json.test.ts index f04f2f9fd4..51845812e1 100644 --- a/packages/cli/test/lib/wizard/utils/package-json.test.ts +++ b/packages/cli/test/lib/wizard/utils/package-json.test.ts @@ -123,6 +123,24 @@ catalog: expect(getPackageVersion("@sentry/node", packageJson)).toBe("^7.100.0"); }); + it.each([ + ["catalog:default", "catalog:\n '@sentry/node': ^7.100.0\n"], + ["catalog:", "catalogs:\n default:\n '@sentry/node': ^7.100.0\n"], + ])("resolves %s against either default catalog form", (ref, yaml) => { + mockedFs.existsSync.mockImplementation((filepath: string) => { + return ( + filepath === path.join("/test/workspace", "pnpm-workspace.yaml") + ); + }); + mockedFs.readFileSync.mockReturnValue(yaml); + + const packageJson: PackageDotJson = { + dependencies: { "@sentry/node": ref }, + }; + + expect(getPackageVersion("@sentry/node", packageJson)).toBe("^7.100.0"); + }); + it("resolves named catalog reference", () => { mockedFs.existsSync.mockImplementation((filepath: string) => { return ( diff --git a/packages/cli/test/lib/wizard/utils/project-data.test.ts b/packages/cli/test/lib/wizard/utils/project-data.test.ts index a691410ee2..152d7adb29 100644 --- a/packages/cli/test/lib/wizard/utils/project-data.test.ts +++ b/packages/cli/test/lib/wizard/utils/project-data.test.ts @@ -19,6 +19,9 @@ const mocks = vi.hoisted(() => ({ createOrgAuthToken: vi.fn(), select: vi.fn(), text: vi.fn(), + isRequestOriginTrusted: vi.fn(), + getApiBaseUrl: vi.fn(), + warn: vi.fn(), })); vi.mock("@clack/prompts", () => ({ @@ -31,10 +34,23 @@ vi.mock("@clack/prompts", () => ({ log: { info: vi.fn(), step: vi.fn(), - warn: vi.fn(), + warn: mocks.warn, error: vi.fn(), }, })); +// The stored login (`getAuthConfig`) is mocked, so its host check is too. +vi.mock("../../../../src/lib/token-host.js", async (importOriginal) => ({ + ...(await importOriginal< + typeof import("../../../../src/lib/token-host.js") + >()), + isRequestOriginTrusted: mocks.isRequestOriginTrusted, +})); +vi.mock("../../../../src/lib/sentry-client.js", async (importOriginal) => ({ + ...(await importOriginal< + typeof import("../../../../src/lib/sentry-client.js") + >()), + getApiBaseUrl: mocks.getApiBaseUrl, +})); vi.mock("../../../../src/lib/db/auth.js", async (importOriginal) => ({ ...(await importOriginal()), getAuthConfig: mocks.getAuthConfig, @@ -87,10 +103,15 @@ const KEY = { dsn: { public: "https://abc@o1.ingest.sentry.io/42", secret: "" }, }; -beforeEach(() => { +beforeEach(async () => { vi.clearAllMocks(); + const actualClient = await vi.importActual< + typeof import("../../../../src/lib/sentry-client.js") + >("../../../../src/lib/sentry-client.js"); + mocks.getApiBaseUrl.mockImplementation(actualClient.getApiBaseUrl); vi.stubEnv("SENTRY_HANDOFF", ""); mocks.getAuthConfig.mockReturnValue({ token: "stored" }); + mocks.isRequestOriginTrusted.mockReturnValue(true); mocks.listOrganizations.mockResolvedValue([ORG]); mocks.getProject.mockResolvedValue(PROJECT); mocks.getProjectKeys.mockResolvedValue([KEY]); @@ -236,6 +257,53 @@ describe("getOrAskForProjectData", () => { ).rejects.toThrow(WizardExitError); }); + it("logs in again when the stored login is for another instance", async () => { + mocks.isRequestOriginTrusted.mockReturnValueOnce(false); + mocks.runInteractiveLogin.mockResolvedValue({ method: "oauth" }); + + await getOrAskForProjectData({ + telemetryEnabled: false, + url: "https://sentry.example.com", + orgSlug: "acme", + projectSlug: "web", + }); + + expect(mocks.runInteractiveLogin).toHaveBeenCalled(); + }); + + it("uses the stored login's instance when none is chosen", async () => { + mocks.getApiBaseUrl.mockReturnValue("https://sentry.example.com"); + + const result = await getOrAskForProjectData({ + telemetryEnabled: false, + orgSlug: "acme", + projectSlug: "web", + }); + + expect(mocks.runInteractiveLogin).not.toHaveBeenCalled(); + expect(result).toMatchObject({ + sentryUrl: "https://sentry.example.com/", + selfHosted: true, + }); + }); + + it("links to the self-hosted auth token settings when it can't create one", async () => { + mocks.getApiBaseUrl.mockReturnValue("https://sentry.example.com"); + mocks.createOrgAuthToken.mockRejectedValue(new Error("forbidden")); + + await getOrAskForProjectData({ + telemetryEnabled: false, + orgSlug: "acme", + projectSlug: "web", + }); + + expect(mocks.warn).toHaveBeenCalledWith( + expect.stringContaining( + "https://sentry.example.com/settings/acme/auth-tokens/", + ), + ); + }); + it("claims an agent handoff and uses its org", async () => { vi.stubEnv("SENTRY_HANDOFF", "handoff-code"); mocks.completeAgentHandoff.mockResolvedValue({ organizationSlug: "acme" }); From 52b064274e6da7c15567dde85bf139799f5d8483 Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Thu, 26 Nov 2026 18:36:47 +0000 Subject: [PATCH 07/17] fix(cli): keep the Remix SDK source map upload script MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Revert the Remix build script change from 07f26e03. For Remix without Vite the wizard again sets the build script to `npx @sentry/remix --upload-sourcemaps --org … --project …` and writes only the auth token to `.sentryclirc`, as sentry-wizard does. It no longer installs `sentry` as a dev dependency or prints the CI env var note. The promoCode removal from the welcome screen stays. Co-Authored-By: BYK <126780+BYK@users.noreply.github.com> --- .../cli/src/lib/wizard/remix/remix-wizard.ts | 42 ++-------- .../cli/src/lib/wizard/remix/sdk-setup.ts | 17 ++--- .../lib/wizard/remix/build-script.test.ts | 76 +++++++++++++++---- 3 files changed, 73 insertions(+), 62 deletions(-) diff --git a/packages/cli/src/lib/wizard/remix/remix-wizard.ts b/packages/cli/src/lib/wizard/remix/remix-wizard.ts index f57fe043eb..4a3b9266cd 100644 --- a/packages/cli/src/lib/wizard/remix/remix-wizard.ts +++ b/packages/cli/src/lib/wizard/remix/remix-wizard.ts @@ -14,7 +14,6 @@ import { addDotEnvSentryBuildPluginFile, addSentryCliConfig, askShouldCreateExamplePage, - type CliSetupConfig, confirmContinueIfNoOrDirtyGitRepo, ensurePackageIsInstalled, featureSelectionPrompt, @@ -54,16 +53,6 @@ import { isHydrogenApp } from "./utils.js"; import { abortIfSpotlightNotSupported } from "../utils/abort-if-sportlight-not-supported.js"; import { warnIfNodeVersionUnsupportedBySdkV11 } from "../utils/node-version.js"; -/** - * `.sentryclirc` with `[defaults] url` as well, so `sentry sourcemap upload` - * in the build script reaches a self-hosted Sentry. - */ -const sentryCliRcWithUrl: CliSetupConfig = { - ...rcCliSetupConfig, - likelyAlreadyHasUrl: (contents) => /^\s*url\s*=./m.test(contents), - urlContent: (url) => `[defaults]\nurl=${url}`, -}; - export async function runRemixWizard(options: WizardOptions): Promise { return await withTelemetry( { @@ -172,33 +161,14 @@ async function runRemixWizardWithTelemetry( } else { await traceStep("Update build script for sourcemap uploads", async () => { try { - // The build script runs the project's own `sentry` CLI, so CI - // can run it too. - await installPackage({ - packageName: "sentry", - alreadyInstalled: hasPackageInstalled("sentry", packageJson), - devDependency: true, - forceInstall, + await updateBuildScript({ + org: selectedProject.organization.slug, + project: selectedProject.slug, + url: selfHosted ? sentryUrl : undefined, + isHydrogen: isHydrogenApp(packageJson), }); - await updateBuildScript({ isHydrogen: isHydrogenApp(packageJson) }); - - await addSentryCliConfig( - { - authToken, - org: selectedProject.organization.slug, - project: selectedProject.slug, - url: selfHosted ? sentryUrl : undefined, - }, - sentryCliRcWithUrl, - ); - clack.log.info( - `${chalk.cyan(".sentryclirc")} stays out of git. In CI, set ${chalk.cyan( - "SENTRY_AUTH_TOKEN", - )}, ${chalk.cyan("SENTRY_ORG")} and ${chalk.cyan( - "SENTRY_PROJECT", - )} for the upload.`, - ); + await addSentryCliConfig({ authToken }, rcCliSetupConfig); } catch (e) { clack.log .warn(`Could not update build script to generate and upload sourcemaps. diff --git a/packages/cli/src/lib/wizard/remix/sdk-setup.ts b/packages/cli/src/lib/wizard/remix/sdk-setup.ts index 0b31540d96..ef128c2625 100644 --- a/packages/cli/src/lib/wizard/remix/sdk-setup.ts +++ b/packages/cli/src/lib/wizard/remix/sdk-setup.ts @@ -331,12 +331,10 @@ export async function instrumentRootRoute(isTS?: boolean): Promise { ); } -/** - * Make the `build` script build with source maps and upload them with - * `sentry sourcemap upload`, which injects the debug IDs. The org, project - * and URL come from `.sentryclirc`, which the wizard writes next to it. - */ export async function updateBuildScript(args: { + org: string; + project: string; + url?: string | undefined; isHydrogen: boolean; }): Promise { const packageJson = await getPackageDotJson(); @@ -349,11 +347,10 @@ export async function updateBuildScript(args: { ? "shopify hydrogen build" : "remix build"; - // The same build path and URL prefix `@sentry/remix --upload-sourcemaps` - // used. - const buildPath = args.isHydrogen ? "./dist" : "./public/build"; - // oxlint-disable-next-line sentry-cli/no-hardcoded-sentry-command -- a package.json script that runs the project's own `sentry` devDependency, not a hint - const instrumentedBuildCommand = `${buildCommand} --sourcemap && sentry sourcemap upload ${buildPath} --url-prefix "~/build/"`; + const instrumentedBuildCommand = + `${buildCommand} --sourcemap && npx @sentry/remix --upload-sourcemaps --org ${args.org} --project ${args.project}` + + (args.url ? ` --url ${args.url}` : "") + + (args.isHydrogen ? " --buildPath ./dist" : ""); if (!packageJson.scripts["build"]) { packageJson.scripts["build"] = instrumentedBuildCommand; diff --git a/packages/cli/test/lib/wizard/remix/build-script.test.ts b/packages/cli/test/lib/wizard/remix/build-script.test.ts index 6d7c8ec7a1..1ad6c3283e 100644 --- a/packages/cli/test/lib/wizard/remix/build-script.test.ts +++ b/packages/cli/test/lib/wizard/remix/build-script.test.ts @@ -37,19 +37,51 @@ describe("updateBuildScript", () => { vi.clearAllMocks(); }); - it("uploads with sentry sourcemap upload", async () => { - await updateBuildScript({ isHydrogen: false }); + it("uses npx @sentry/remix --upload-sourcemaps for the upload command", async () => { + await updateBuildScript({ + org: "my-org", + project: "my-project", + isHydrogen: false, + }); - expect(JSON.parse(writeFileSpy.mock.calls[0]?.[1] as string)).toEqual({ - scripts: { - build: - 'remix build --sourcemap && sentry sourcemap upload ./public/build --url-prefix "~/build/"', - }, - version: "1.0.0", + expect(writeFileSpy).toHaveBeenCalledWith( + expect.stringContaining("package.json"), + expect.stringContaining( + "npx @sentry/remix --upload-sourcemaps --org my-org --project my-project", + ), + ); + }); + + it("replaces the remix build command with sourcemap flag and upload", async () => { + await updateBuildScript({ + org: "my-org", + project: "my-project", + isHydrogen: false, }); + + expect(writeFileSpy).toHaveBeenCalledWith( + expect.stringContaining("package.json"), + expect.stringContaining( + "remix build --sourcemap && npx @sentry/remix --upload-sourcemaps", + ), + ); }); - it("uploads ./dist for hydrogen apps", async () => { + it("includes --url flag when a custom url is provided", async () => { + await updateBuildScript({ + org: "my-org", + project: "my-project", + url: "https://self-hosted.example.com", + isHydrogen: false, + }); + + expect(writeFileSpy).toHaveBeenCalledWith( + expect.stringContaining("package.json"), + expect.stringContaining("--url https://self-hosted.example.com"), + ); + }); + + it("uses shopify hydrogen build for hydrogen apps", async () => { vi.mocked(getPackageDotJson).mockResolvedValue({ scripts: { build: "shopify hydrogen build", @@ -57,12 +89,16 @@ describe("updateBuildScript", () => { version: "1.0.0", }); - await updateBuildScript({ isHydrogen: true }); + await updateBuildScript({ + org: "my-org", + project: "my-project", + isHydrogen: true, + }); expect(writeFileSpy).toHaveBeenCalledWith( expect.stringContaining("package.json"), expect.stringContaining( - 'shopify hydrogen build --sourcemap && sentry sourcemap upload ./dist --url-prefix \\"~/build/\\"', + "shopify hydrogen build --sourcemap && npx @sentry/remix --upload-sourcemaps --org my-org --project my-project --buildPath ./dist", ), ); }); @@ -73,12 +109,16 @@ describe("updateBuildScript", () => { version: "1.0.0", }); - await updateBuildScript({ isHydrogen: false }); + await updateBuildScript({ + org: "my-org", + project: "my-project", + isHydrogen: false, + }); expect(writeFileSpy).toHaveBeenCalledWith( expect.stringContaining("package.json"), expect.stringContaining( - "remix build --sourcemap && sentry sourcemap upload ./public/build", + "remix build --sourcemap && npx @sentry/remix --upload-sourcemaps", ), ); }); @@ -91,8 +131,12 @@ describe("updateBuildScript", () => { version: "1.0.0", }); - await expect(updateBuildScript({ isHydrogen: false })).rejects.toThrow( - "build` script doesn't contain a known build command", - ); + await expect( + updateBuildScript({ + org: "my-org", + project: "my-project", + isHydrogen: false, + }), + ).rejects.toThrow("build` script doesn't contain a known build command"); }); }); From 2c987511447e235888f3773f3599aaf82d742b54 Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Thu, 26 Nov 2026 19:01:23 +0000 Subject: [PATCH 08/17] refactor(cli): reuse existing CLI helpers in the wizard AST utils Address review feedback on the shared wizard helpers: - Enable unicorn/no-array-for-each repo-wide and convert every .forEach call site to for...of, including getLastRequireIndex. - Add buildProjectIssuesUrl to lib/sentry-urls.ts, built on getOrgBaseUrl like buildEventSearchUrl, and delete the wizard-specific wizard/utils/url.ts. - Move findFile into lib/dsn/fs-utils.ts and build it on isRegularFile, so a directory or FIFO with a matching name is skipped. It is async now. Co-Authored-By: BYK <126780+BYK@users.noreply.github.com> --- .oxlintrc.json | 1 + apps/games-api/src/leaderboard.test.ts | 4 +- apps/local/src/lib/profile-session.ts | 14 +++--- packages/cli/src/commands/api.ts | 4 +- packages/cli/src/lib/db/completion-cache.ts | 4 +- packages/cli/src/lib/dsn/errors.ts | 4 +- packages/cli/src/lib/dsn/fs-utils.ts | 22 ++++++++++ packages/cli/src/lib/formatters/alerts.ts | 8 ++-- packages/cli/src/lib/formatters/human.ts | 8 ++-- packages/cli/src/lib/games/snake-game.ts | 4 +- packages/cli/src/lib/select-ui/picker.ts | 4 +- packages/cli/src/lib/sentry-urls.ts | 18 ++++++++ packages/cli/src/lib/sixel-image.ts | 4 +- .../cli/src/lib/wizard/utils/ast-utils.ts | 19 +------- packages/cli/src/lib/wizard/utils/url.ts | 29 ------------- packages/cli/test/lib/api/traces.test.ts | 4 +- packages/cli/test/lib/dsn/fs-utils.test.ts | 43 ++++++++++++++++++- .../test/lib/sdk-positionals.property.test.ts | 4 +- .../cli/test/lib/sentry-urls.property.test.ts | 16 +++++++ .../cli/test/lib/wizard/nextjs/utils.test.ts | 4 +- packages/cli/test/mocks/server.ts | 4 +- .../client/components/chat/chat-messages.tsx | 38 ++++++++-------- packages/mcp-core/chart-app/chart.ts | 8 ++-- .../api-client/client-request-paths.test.ts | 6 +-- .../src/internal/issue-side-quests.test.ts | 8 ++-- packages/mcp-core/src/internal/side-quests.ts | 4 +- .../src/internal/source-map-diagnosis.ts | 8 ++-- .../src/tools/catalog/get-event-attachment.ts | 4 +- .../src/tools/support/profile/analyzer.ts | 8 ++-- .../support/profile/flamegraph-output.ts | 6 +-- .../tools/support/search-events/replays.ts | 4 +- .../src/tools/support/search-events/utils.ts | 21 ++++----- 32 files changed, 193 insertions(+), 144 deletions(-) delete mode 100644 packages/cli/src/lib/wizard/utils/url.ts diff --git a/.oxlintrc.json b/.oxlintrc.json index ff2085d067..4304d7920f 100644 --- a/.oxlintrc.json +++ b/.oxlintrc.json @@ -69,6 +69,7 @@ "typescript/no-useless-default-assignment": "error", "jsx-a11y/interactive-supports-focus": "off", "unicorn/prefer-spread": "error", + "unicorn/no-array-for-each": "error", "typescript/no-misused-promises": "error", "typescript/switch-exhaustiveness-check": [ "error", diff --git a/apps/games-api/src/leaderboard.test.ts b/apps/games-api/src/leaderboard.test.ts index 09b62a9838..cfd655cab1 100644 --- a/apps/games-api/src/leaderboard.test.ts +++ b/apps/games-api/src/leaderboard.test.ts @@ -179,7 +179,9 @@ describe("games leaderboard route", () => { "kk", "ll", ]; - names.forEach((n, i) => rows.push([`${n}-${n}-100${i % 10}`, 300 - i])); + for (const [i, n] of names.entries()) { + rows.push([`${n}-${n}-100${i % 10}`, 300 - i]); + } fetchMock.mockResolvedValue(jsonResponse(upstreamBody(rows))); const res = await app.request(PATH, REQ, makeEnv()); diff --git a/apps/local/src/lib/profile-session.ts b/apps/local/src/lib/profile-session.ts index f29d4ae532..2099a05dfb 100644 --- a/apps/local/src/lib/profile-session.ts +++ b/apps/local/src/lib/profile-session.ts @@ -128,8 +128,8 @@ export function mergeProfileChunks( const frameMap = new Map(), stackMap = new Map(); if (Array.isArray(profile["frames"])) - profile["frames"].forEach((frame, index) => { - if (!Object.keys(record(frame)).length) return; + for (const [index, frame] of profile["frames"].entries()) { + if (!Object.keys(record(frame)).length) continue; const key = profileValueKey(frame); let id = frameIds.get(key); if (id === undefined) { @@ -138,15 +138,15 @@ export function mergeProfileChunks( frameIds.set(key, id); } frameMap.set(index, id); - }); + } if (Array.isArray(profile["stacks"])) - profile["stacks"].forEach((stack, index) => { - if (!Array.isArray(stack)) return; + stacks: for (const [index, stack] of profile["stacks"].entries()) { + if (!Array.isArray(stack)) continue; const mapped: number[] = []; for (const frame of stack) { const id = typeof frame === "number" ? frameMap.get(frame) : undefined; - if (id === undefined) return; // Broken indexes cannot silently describe another frame. + if (id === undefined) continue stacks; // Broken indexes cannot silently describe another frame. mapped.push(id); } const key = JSON.stringify(mapped); @@ -157,7 +157,7 @@ export function mergeProfileChunks( stackIds.set(key, id); } stackMap.set(index, id); - }); + } const chunkThreads = new Map[]>(); if (Array.isArray(profile["samples"])) for (const value of profile["samples"]) { diff --git a/packages/cli/src/commands/api.ts b/packages/cli/src/commands/api.ts index 3d2ff084d9..e6f7e0c03c 100644 --- a/packages/cli/src/commands/api.ts +++ b/packages/cli/src/commands/api.ts @@ -1487,9 +1487,9 @@ function logResponse(response: { log.debug( `< HTTP ${response.status}${response.statusText ? ` ${response.statusText}` : ""}`, ); - response.headers.forEach((value, key) => { + for (const [key, value] of response.headers) { log.debug(`< ${key}: ${value}`); - }); + } log.debug("<"); } diff --git a/packages/cli/src/lib/db/completion-cache.ts b/packages/cli/src/lib/db/completion-cache.ts index 3cd00d3cb2..8236087027 100644 --- a/packages/cli/src/lib/db/completion-cache.ts +++ b/packages/cli/src/lib/db/completion-cache.ts @@ -114,7 +114,7 @@ export function cacheCompletionEntities( ) .get(kind, orgSlug) as { latest: number | null } | undefined; const now = Math.max(Date.now(), (latest?.latest ?? 0) + valid.length); - valid.forEach((entity, index) => { + for (const [index, entity] of valid.entries()) { runUpsert( db, "completion_cache", @@ -127,7 +127,7 @@ export function cacheCompletionEntities( }, ["kind", "org_slug", "value"], ); - }); + } db.query( `DELETE FROM completion_cache WHERE kind = ? AND org_slug = ? AND rowid NOT IN ( diff --git a/packages/cli/src/lib/dsn/errors.ts b/packages/cli/src/lib/dsn/errors.ts index 9ad83c3ce8..cccef4c341 100644 --- a/packages/cli/src/lib/dsn/errors.ts +++ b/packages/cli/src/lib/dsn/errors.ts @@ -22,14 +22,14 @@ import type { DsnDetectionResult } from "./types.js"; export function formatConflictError(result: DsnDetectionResult): string { const lines = ["Error: Multiple Sentry DSNs detected in this project.\n"]; - result.all.forEach((dsn, i) => { + for (const [i, dsn] of result.all.entries()) { lines.push(` DSN ${i + 1}: ${dsn.raw}`); lines.push(` Source: ${getDsnSourceDescription(dsn)}`); if (dsn.projectId) { lines.push(` Project ID: ${dsn.projectId}`); } lines.push(""); - }); + } lines.push("To resolve, specify which project to use:"); lines.push(` ${sentry` /`}`); diff --git a/packages/cli/src/lib/dsn/fs-utils.ts b/packages/cli/src/lib/dsn/fs-utils.ts index 9c954d0686..1c28aebffe 100644 --- a/packages/cli/src/lib/dsn/fs-utils.ts +++ b/packages/cli/src/lib/dsn/fs-utils.ts @@ -113,3 +113,25 @@ export async function isRegularFile( return false; } } + +/** + * Find the first of `basePath` + each extension that is a regular file, for + * config files whose extension isn't known yet (`next.config` → + * `next.config.mjs`). + * + * @param basePath - Path without the extension + * @param extensions - Extensions to try, in order, each with its leading dot + * @returns The first matching path, or undefined when none is a regular file + */ +export async function findFile( + basePath: string, + extensions: readonly string[] = [".js", ".ts", ".mjs", ".cjs"], +): Promise { + for (const extension of extensions) { + const candidate = `${basePath}${extension}`; + if (await isRegularFile(candidate, "findFile")) { + return candidate; + } + } + return undefined; +} diff --git a/packages/cli/src/lib/formatters/alerts.ts b/packages/cli/src/lib/formatters/alerts.ts index ecee154539..24e0171353 100644 --- a/packages/cli/src/lib/formatters/alerts.ts +++ b/packages/cli/src/lib/formatters/alerts.ts @@ -81,9 +81,9 @@ function conditionRows(value: unknown, detector: boolean): Row[] { const rows: Row[] = [["Logic", valueText(group["logicType"])]]; const conditions = group["conditions"]; if (Array.isArray(conditions) && conditions.length > 0) { - conditions.forEach((condition, index) => { + for (const [index, condition] of conditions.entries()) { rows.push([`Condition ${index + 1}`, conditionText(condition, detector)]); - }); + } } else { rows.push([ "Conditions", @@ -150,11 +150,11 @@ function workflowSections(workflow: GetOrganizationWorkflowResponse): string[] { ...workflowGroupSections(workflow.triggers, "Triggers"), ]; if (workflow.actionFilters?.length) { - workflow.actionFilters.forEach((group, index) => { + for (const [index, group] of workflow.actionFilters.entries()) { sections.push( ...workflowGroupSections(group, `Action filter ${index + 1}`), ); - }); + } } else { sections.push(table([["Action filters", "none"]])); } diff --git a/packages/cli/src/lib/formatters/human.ts b/packages/cli/src/lib/formatters/human.ts index 2ee356406a..e34818d542 100644 --- a/packages/cli/src/lib/formatters/human.ts +++ b/packages/cli/src/lib/formatters/human.ts @@ -1286,7 +1286,7 @@ function formatSpanSimple(span: TraceSpan, opts: FormatSpanOptions): void { if (currentDepth < maxDepth) { const children = span.children ?? []; const childCount = children.length; - children.forEach((child, i) => { + for (const [i, child] of children.entries()) { formatSpanSimple(child, { lines, prefix: childPrefix, @@ -1294,7 +1294,7 @@ function formatSpanSimple(span: TraceSpan, opts: FormatSpanOptions): void { currentDepth: currentDepth + 1, maxDepth, }); - }); + } } } @@ -1367,7 +1367,7 @@ export function formatSimpleSpanTree( const displaySpans = truncated ? spans.slice(0, MAX_ROOT_SPANS) : spans; const displayCount = displaySpans.length; - displaySpans.forEach((span, i) => { + for (const [i, span] of displaySpans.entries()) { formatSpanSimple(span, { lines, prefix: "", @@ -1375,7 +1375,7 @@ export function formatSimpleSpanTree( currentDepth: 1, maxDepth: effectiveMaxDepth, }); - }); + } if (truncated) { const remaining = totalRootSpans - MAX_ROOT_SPANS; diff --git a/packages/cli/src/lib/games/snake-game.ts b/packages/cli/src/lib/games/snake-game.ts index b4b3f4c052..5be8d6628a 100644 --- a/packages/cli/src/lib/games/snake-game.ts +++ b/packages/cli/src/lib/games/snake-game.ts @@ -313,9 +313,9 @@ export function renderSnake( if (state.food) { cells[state.food.y * state.width + state.food.x] = FOOD; } - state.body.forEach((part, index) => { + for (const [index, part] of state.body.entries()) { cells[part.y * state.width + part.x] = index === 0 ? HEAD : BODY; - }); + } const lines: string[] = []; for (let row = 0; row < snakeTerminalRows(state.height); row++) { diff --git a/packages/cli/src/lib/select-ui/picker.ts b/packages/cli/src/lib/select-ui/picker.ts index 3e5a729799..7060a1a276 100644 --- a/packages/cli/src/lib/select-ui/picker.ts +++ b/packages/cli/src/lib/select-ui/picker.ts @@ -450,14 +450,14 @@ function renderPicker( const accent = chalk.hex(ACCENT); const lines = [""]; - titleLines.forEach((line, index) => { + for (const [index, line] of titleLines.entries()) { const icon = padIcon(index === 0 ? ICONS.diamondOpen : ""); const counter = index === 0 && isWindowed ? chalk.hex(MUTED_DIM)(` (${highlighted + 1}/${filtered.length})`) : ""; lines.push(`${accent.bold(icon)}${chalk.bold(line)}${counter}`); - }); + } lines.push(""); const optionLines = diff --git a/packages/cli/src/lib/sentry-urls.ts b/packages/cli/src/lib/sentry-urls.ts index 3e8dbd5072..902e2fcdc7 100644 --- a/packages/cli/src/lib/sentry-urls.ts +++ b/packages/cli/src/lib/sentry-urls.ts @@ -236,6 +236,24 @@ export function buildEventSearchUrl(orgSlug: string, eventId: string): string { return `${getSentryBaseUrl()}/organizations/${orgSlug}/issues/?query=event.id:${eventId}`; } +/** + * Build URL to a project's issue stream in Sentry. + * + * @param orgSlug - Organization slug + * @param projectId - Numeric project ID + * @returns Full URL to the issues list filtered to the project + */ +export function buildProjectIssuesUrl( + orgSlug: string, + projectId: string, +): string { + const project = encodeURIComponent(projectId); + if (isSaaS()) { + return `${getOrgBaseUrl(orgSlug)}/issues/?project=${project}`; + } + return `${getSentryBaseUrl()}/organizations/${orgSlug}/issues/?project=${project}`; +} + // Settings URLs /** diff --git a/packages/cli/src/lib/sixel-image.ts b/packages/cli/src/lib/sixel-image.ts index 30b175ac3d..a7ac0f3141 100644 --- a/packages/cli/src/lib/sixel-image.ts +++ b/packages/cli/src/lib/sixel-image.ts @@ -601,9 +601,9 @@ export function encodeImageToSixel( // DCS: P1=0 aspect, P2=1 (unpainted = transparent), P3=0 grid; then raster // attributes "1;1;W;H so the terminal reserves the right pixel box. let out = `\x1bP0;1;0q"1;1;${width};${height}`; - palette.forEach(([r, g, b], i) => { + for (const [i, [r, g, b]] of palette.entries()) { out += `#${i};2;${to100(r)};${to100(g)};${to100(b)}`; - }); + } const totalBands = Math.ceil(height / 6); for (let band = 0; band < totalBands; band++) { diff --git a/packages/cli/src/lib/wizard/utils/ast-utils.ts b/packages/cli/src/lib/wizard/utils/ast-utils.ts index 05929e5203..9bf504f456 100644 --- a/packages/cli/src/lib/wizard/utils/ast-utils.ts +++ b/packages/cli/src/lib/wizard/utils/ast-utils.ts @@ -3,8 +3,6 @@ * that edit JavaScript and TypeScript config files. */ -import { existsSync } from "node:fs"; - import recast from "recast"; import { debug } from "./debug.js"; @@ -12,19 +10,6 @@ import type { namedTypes as t } from "ast-types"; const b = recast.types.builders; -/** - * Checks if a file where we don't know its concrete file type yet exists - * and returns the full path to the file with the correct file type. - */ -export function findFile( - filePath: string, - fileTypes: string[] = [".js", ".ts", ".mjs", ".cjs"], -): string | undefined { - return fileTypes - .map((type) => `${filePath}${type}`) - .find((file) => existsSync(file)); -} - /** * checks for require('@sentry/*') syntax */ @@ -237,7 +222,7 @@ export function printJsonC(ast: t.Program): string { */ export function getLastRequireIndex(program: t.Program): number { let lastRequireIdex = -1; - program.body.forEach((s, i) => { + for (const [i, s] of program.body.entries()) { const declaration = s.type === "VariableDeclaration" ? s.declarations[0] : undefined; if ( @@ -248,7 +233,7 @@ export function getLastRequireIndex(program: t.Program): number { ) { lastRequireIdex = i; } - }); + } return lastRequireIdex; } diff --git a/packages/cli/src/lib/wizard/utils/url.ts b/packages/cli/src/lib/wizard/utils/url.ts deleted file mode 100644 index 6d3af99d64..0000000000 --- a/packages/cli/src/lib/wizard/utils/url.ts +++ /dev/null @@ -1,29 +0,0 @@ -/** - * Sentry URLs the wizards print after setup. - */ - -/** - * Returns the url to the Sentry project stream. - * - * Example: https://org-slug.sentry.io/issues/?project=1234567 - */ -export function getIssueStreamUrl({ - url, - orgSlug, - projectId, -}: { - url: string; - orgSlug: string; - projectId: string; -}): string { - const urlObject = new URL(url); - if (urlObject.host === "sentry.io") { - urlObject.host = `${orgSlug}.${urlObject.host}`; - urlObject.pathname = "/issues/"; - } else { - urlObject.pathname = `/organizations/${orgSlug}/issues/`; - } - urlObject.searchParams.set("project", projectId); - - return urlObject.toString(); -} diff --git a/packages/cli/test/lib/api/traces.test.ts b/packages/cli/test/lib/api/traces.test.ts index 1b7b0d06a2..2cdc4babac 100644 --- a/packages/cli/test/lib/api/traces.test.ts +++ b/packages/cli/test/lib/api/traces.test.ts @@ -594,9 +594,9 @@ describe("getSpanDetails", () => { const req = new Request(input, init); capturedUrl = req.url; const url = new URL(capturedUrl); - url.searchParams.forEach((v, k) => { + for (const [k, v] of url.searchParams) { capturedParams[k] = v; - }); + } return new Response(JSON.stringify(body), { status: 200, headers: { "Content-Type": "application/json" }, diff --git a/packages/cli/test/lib/dsn/fs-utils.test.ts b/packages/cli/test/lib/dsn/fs-utils.test.ts index a1b47c0da7..c637ac2761 100644 --- a/packages/cli/test/lib/dsn/fs-utils.test.ts +++ b/packages/cli/test/lib/dsn/fs-utils.test.ts @@ -5,6 +5,10 @@ * errors (ignored, debug-logged) from unexpected ones (reported to Sentry). */ +import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; + import { afterEach, beforeEach, describe, expect, test, vi } from "vitest"; const { reportCliError } = vi.hoisted(() => ({ @@ -16,7 +20,8 @@ vi.mock("@sentry/node", () => ({ startSpan: (_opts: unknown, fn: () => unknown) => fn(), })); -const { handleFileError } = await import("../../../src/lib/dsn/fs-utils.js"); +const { findFile, handleFileError } = + await import("../../../src/lib/dsn/fs-utils.js"); /** Create an Error with a `code` property, mimicking Node/Bun errno errors. */ function errnoError(code: string, message?: string): Error { @@ -184,3 +189,39 @@ describe("handleFileError", () => { }); }); }); + +describe("findFile", () => { + let dir: string; + + beforeEach(async () => { + dir = await mkdtemp(join(tmpdir(), "find-file-")); + }); + + afterEach(async () => { + await rm(dir, { recursive: true, force: true }); + }); + + test("returns the first extension that exists, in order", async () => { + await writeFile(join(dir, "next.config.mjs"), ""); + await writeFile(join(dir, "next.config.cjs"), ""); + + expect(await findFile(join(dir, "next.config"))).toBe( + join(dir, "next.config.mjs"), + ); + }); + + test("skips a directory with a matching name", async () => { + await mkdir(join(dir, "next.config.js")); + await writeFile(join(dir, "next.config.ts"), ""); + + expect(await findFile(join(dir, "next.config"))).toBe( + join(dir, "next.config.ts"), + ); + }); + + test("returns undefined when no extension matches", async () => { + expect( + await findFile(join(dir, "vite.config"), [".js", ".ts"]), + ).toBeUndefined(); + }); +}); diff --git a/packages/cli/test/lib/sdk-positionals.property.test.ts b/packages/cli/test/lib/sdk-positionals.property.test.ts index 15b53cb35c..b1a45e503a 100644 --- a/packages/cli/test/lib/sdk-positionals.property.test.ts +++ b/packages/cli/test/lib/sdk-positionals.property.test.ts @@ -26,9 +26,9 @@ describe("positionals", () => { fcAssert( property(valuesArb, (values) => { const result = positionals(...values); - result.forEach((token, i) => { + for (const [i, token] of result.entries()) { expect(token).toBe(values[i] ?? ""); - }); + } }), { numRuns: DEFAULT_NUM_RUNS }, ); diff --git a/packages/cli/test/lib/sentry-urls.property.test.ts b/packages/cli/test/lib/sentry-urls.property.test.ts index 22027bdf10..1d4227b1ae 100644 --- a/packages/cli/test/lib/sentry-urls.property.test.ts +++ b/packages/cli/test/lib/sentry-urls.property.test.ts @@ -19,6 +19,7 @@ import { buildDashboardsListUrl, buildDashboardUrl, buildEventSearchUrl, + buildProjectIssuesUrl, buildLogsUrl, buildOrgSettingsUrl, buildOrgUrl, @@ -301,6 +302,21 @@ describe("buildEventSearchUrl properties", () => { }); }); +describe("buildProjectIssuesUrl", () => { + test("filters the org-subdomain issue stream to the project on SaaS", () => { + expect(buildProjectIssuesUrl("my-org", "1234567")).toBe( + "https://my-org.sentry.io/issues/?project=1234567", + ); + }); + + test("uses the organizations path on self-hosted", () => { + process.env["SENTRY_URL"] = "https://sentry.example.com"; + expect(buildProjectIssuesUrl("my-org", "42")).toBe( + "https://sentry.example.com/organizations/my-org/issues/?project=42", + ); + }); +}); + describe("buildOrgSettingsUrl properties", () => { test("without hash, output ends with trailing slash", async () => { fcAssert( diff --git a/packages/cli/test/lib/wizard/nextjs/utils.test.ts b/packages/cli/test/lib/wizard/nextjs/utils.test.ts index df026e57ed..cddd023814 100644 --- a/packages/cli/test/lib/wizard/nextjs/utils.test.ts +++ b/packages/cli/test/lib/wizard/nextjs/utils.test.ts @@ -89,13 +89,13 @@ describe("Next.js Utils", () => { const mockAppFolderPath = "/mock/app"; const supportedExtensions = ["jsx", "tsx", "js"]; - supportedExtensions.forEach((ext) => { + for (const ext of supportedExtensions) { (fs.existsSync as Mock).mockImplementation((filePath: string) => { return filePath === `/mock/app/layout.${ext}`; }); expect(hasRootLayoutFile(mockAppFolderPath)).toBe(true); - }); + } }); it("returns false when no layout file exists", () => { diff --git a/packages/cli/test/mocks/server.ts b/packages/cli/test/mocks/server.ts index 364b5b3f90..9e5b466d8c 100644 --- a/packages/cli/test/mocks/server.ts +++ b/packages/cli/test/mocks/server.ts @@ -69,12 +69,12 @@ function matchRoute( if (match) { const [, ...values] = match; const params: Record = {}; - route.paramNames.forEach((name, i) => { + for (const [i, name] of route.paramNames.entries()) { const value = values[i]; if (value !== undefined) { params[name] = value; } - }); + } return { route, params }; } } diff --git a/packages/mcp-cloudflare/src/client/components/chat/chat-messages.tsx b/packages/mcp-cloudflare/src/client/components/chat/chat-messages.tsx index 9aedb5d575..242541ed7f 100644 --- a/packages/mcp-cloudflare/src/client/components/chat/chat-messages.tsx +++ b/packages/mcp-cloudflare/src/client/components/chat/chat-messages.tsx @@ -24,34 +24,32 @@ function processMessages( // Only the very last text part of the very last message should be streaming const lastMessageIndex = messages.length - 1; - messages.forEach((message, messageIndex) => { + for (const [messageIndex, message] of messages.entries()) { const isLastMessage = messageIndex === lastMessageIndex; // Handle messages with parts array if (message.parts.length > 0) { const lastPartIndex = message.parts.length - 1; - message.parts.forEach( - (part: UIMessage["parts"][number], partIndex: number) => { - const isLastPartOfLastMessage = - isLastMessage && partIndex === lastPartIndex; + for (const [partIndex, part] of message.parts.entries()) { + const isLastPartOfLastMessage = + isLastMessage && partIndex === lastPartIndex; - allParts.push({ - part, - messageId: message.id, - messageRole: message.role, - partIndex, - // Stream if it's AI response OR local streaming simulation - isStreaming: - (isLastPartOfLastMessage && - isChatLoading && - part.type === "text") || - (part.type === "text" && !!isMessageStreaming?.(message.id)), - }); - }, - ); + allParts.push({ + part, + messageId: message.id, + messageRole: message.role, + partIndex, + // Stream if it's AI response OR local streaming simulation + isStreaming: + (isLastPartOfLastMessage && + isChatLoading && + part.type === "text") || + (part.type === "text" && !!isMessageStreaming?.(message.id)), + }); + } } - }); + } return allParts; } diff --git a/packages/mcp-core/chart-app/chart.ts b/packages/mcp-core/chart-app/chart.ts index 569d49cdd4..78c9f684ea 100644 --- a/packages/mcp-core/chart-app/chart.ts +++ b/packages/mcp-core/chart-app/chart.ts @@ -256,7 +256,7 @@ export function drawChart( const single = chart.series.length === 1; const path = (pts: readonly Point[]) => pts.map(([px, py], i) => `${i ? "L" : "M"}${px},${py}`).join(""); - chart.series.forEach((series, index) => { + for (const [index, series] of chart.series.entries()) { const color = SERIES_COLORS[index % SERIES_COLORS.length] ?? "#7553ff"; // Runs of buckets with data. A null bucket ends a run, so it draws as a // gap instead of a drop to 0. @@ -306,7 +306,7 @@ export function drawChart( ); } } - }); + } const crosshair = svg( "line", @@ -397,11 +397,11 @@ export function drawChart( } const time = first + ((px - MARGIN.left) / plotWidth) * span; let nearest = 0; - times.forEach((t, i) => { + for (const [i, t] of times.entries()) { if (Math.abs(t - time) < Math.abs((times[nearest] ?? 0) - time)) { nearest = i; } - }); + } showAt(nearest); }); root.addEventListener("pointerleave", hide); diff --git a/packages/mcp-core/src/api-client/client-request-paths.test.ts b/packages/mcp-core/src/api-client/client-request-paths.test.ts index c4b347c859..b0f893bb48 100644 --- a/packages/mcp-core/src/api-client/client-request-paths.test.ts +++ b/packages/mcp-core/src/api-client/client-request-paths.test.ts @@ -35,9 +35,9 @@ describe("client.ts request path invariant", () => { it("interpolates every request path through apiPath", () => { const offenders: string[] = []; - source.split("\n").forEach((line, index) => { + for (const [index, line] of source.split("\n").entries()) { const trimmed = line.trim(); - if (trimmed.startsWith("//") || trimmed.startsWith("*")) return; + if (trimmed.startsWith("//") || trimmed.startsWith("*")) continue; // A template literal opening with a slash is an API request path. for (let i = 0; i < line.length - 1; i++) { @@ -53,7 +53,7 @@ describe("client.ts request path invariant", () => { offenders.push(`${index + 1}: ${trimmed}`); } } - }); + } expect( offenders, diff --git a/packages/mcp-core/src/internal/issue-side-quests.test.ts b/packages/mcp-core/src/internal/issue-side-quests.test.ts index 894aab0c0a..6fa41fde2c 100644 --- a/packages/mcp-core/src/internal/issue-side-quests.test.ts +++ b/packages/mcp-core/src/internal/issue-side-quests.test.ts @@ -24,11 +24,9 @@ function eventWithFourFiles() { if (!("rawStacktrace" in value)) { continue; } - value.rawStacktrace.frames.forEach( - (frame: { absPath: string | null }, index: number) => { - frame.absPath = files[index] ?? frame.absPath; - }, - ); + for (const [index, frame] of value.rawStacktrace.frames.entries()) { + frame.absPath = files[index] ?? frame.absPath; + } } } return EventSchema.parse({ diff --git a/packages/mcp-core/src/internal/side-quests.ts b/packages/mcp-core/src/internal/side-quests.ts index be29b1e1a5..06e18f95d8 100644 --- a/packages/mcp-core/src/internal/side-quests.ts +++ b/packages/mcp-core/src/internal/side-quests.ts @@ -122,9 +122,9 @@ function recordSideQuests(ids: string[], max: number) { "app.side_quests.detected": ids.length, "app.side_quests.shown": shown.length, }; - ids.forEach((id, index) => { + for (const [index, id] of ids.entries()) { attributes[`app.side_quest.${id}`] = index < max ? "shown" : "capped"; - }); + } getActiveSpan()?.setAttributes(attributes); for (const id of shown) { metrics.count("app.side_quest.shown", 1, { diff --git a/packages/mcp-core/src/internal/source-map-diagnosis.ts b/packages/mcp-core/src/internal/source-map-diagnosis.ts index 6ae0968dfc..d1519414f3 100644 --- a/packages/mcp-core/src/internal/source-map-diagnosis.ts +++ b/packages/mcp-core/src/internal/source-map-diagnosis.ts @@ -101,17 +101,17 @@ function getDebugFramesByPath(event: Event, debug: SourceMapDebug) { } return parsed.data.values ?? (parsed.data.value ? [parsed.data.value] : []); }); - values.forEach((value, exceptionIndex) => { + for (const [exceptionIndex, value] of values.entries()) { const rawFrames = value?.rawStacktrace?.frames ?? []; - rawFrames.forEach((rawFrame, frameIndex) => { + for (const [frameIndex, rawFrame] of rawFrames.entries()) { const path = rawFrame.absPath; // the check can return fewer exceptions or frames than the event has const frame = debug.exceptions.at(exceptionIndex)?.frames.at(frameIndex); if (path && frame && !frames.has(path)) { frames.set(path, frame); } - }); - }); + } + } return frames; } diff --git a/packages/mcp-core/src/tools/catalog/get-event-attachment.ts b/packages/mcp-core/src/tools/catalog/get-event-attachment.ts index 44591e0df7..1ab6b10733 100644 --- a/packages/mcp-core/src/tools/catalog/get-event-attachment.ts +++ b/packages/mcp-core/src/tools/catalog/get-event-attachment.ts @@ -221,7 +221,7 @@ export default defineTool({ output += `Found ${attachments.length} attachment(s):\n\n`; - attachments.forEach((attachment, index) => { + for (const [index, attachment] of attachments.entries()) { output += `## Attachment ${index + 1}\n\n`; output += `**ID:** ${attachment.id}\n`; output += `**Name:** ${attachment.name}\n`; @@ -242,7 +242,7 @@ export default defineTool({ availableToolNames: context.availableToolNames, directToolNames: context.directToolNames, })}\n\n`; - }); + } return output; }, diff --git a/packages/mcp-core/src/tools/support/profile/analyzer.ts b/packages/mcp-core/src/tools/support/profile/analyzer.ts index 70c89eeacf..8900f03c64 100644 --- a/packages/mcp-core/src/tools/support/profile/analyzer.ts +++ b/packages/mcp-core/src/tools/support/profile/analyzer.ts @@ -338,15 +338,15 @@ export function compareFrameStats( { baselineIdx?: number; currentIdx?: number } >(); - baselineFrames.forEach((frame, idx) => { + for (const [idx, frame] of baselineFrames.entries()) { const existing = frameMap.get(frame.fingerprint) || {}; frameMap.set(frame.fingerprint, { ...existing, baselineIdx: idx }); - }); + } - currentFrames.forEach((frame, idx) => { + for (const [idx, frame] of currentFrames.entries()) { const existing = frameMap.get(frame.fingerprint) || {}; frameMap.set(frame.fingerprint, { ...existing, currentIdx: idx }); - }); + } // Compare frames that exist in both const comparisons: FrameComparison[] = []; diff --git a/packages/mcp-core/src/tools/support/profile/flamegraph-output.ts b/packages/mcp-core/src/tools/support/profile/flamegraph-output.ts index 848a6963ee..16df286e86 100644 --- a/packages/mcp-core/src/tools/support/profile/flamegraph-output.ts +++ b/packages/mcp-core/src/tools/support/profile/flamegraph-output.ts @@ -178,15 +178,15 @@ export function buildFlamegraphAnalysis( // both overlap across nested frames, so they cannot be summed. const totalNs = sumOf(mainProfile?.sample_durations_ns); let userCodeNs = 0; - mainProfile?.samples.forEach((stack, index) => { + for (const [index, stack] of (mainProfile?.samples ?? []).entries()) { const leafIndex = stack.at(-1); if ( leafIndex !== undefined && flamegraph.shared.frames[leafIndex]?.is_application ) { - userCodeNs += mainProfile.sample_durations_ns[index] ?? 0; + userCodeNs += mainProfile?.sample_durations_ns[index] ?? 0; } - }); + } const outputFrames: FlamegraphAnalysis["frames"] = []; const outputIndexBySource = new Map(); diff --git a/packages/mcp-core/src/tools/support/search-events/replays.ts b/packages/mcp-core/src/tools/support/search-events/replays.ts index 9d3dc817b3..45b9003865 100644 --- a/packages/mcp-core/src/tools/support/search-events/replays.ts +++ b/packages/mcp-core/src/tools/support/search-events/replays.ts @@ -312,7 +312,7 @@ export function formatReplayResults(params: FormatReplayResultsParams): string { output += `Found **${replays.length}** replay${replays.length === 1 ? "" : "s"}:\n\n`; - replays.forEach((replay, index) => { + for (const [index, replay] of replays.entries()) { const replayUrl = apiService.getReplayUrl(organizationSlug, replay.id); const user = formatReplayUser(replay); const clickSummary = [ @@ -343,7 +343,7 @@ export function formatReplayResults(params: FormatReplayResultsParams): string { } output += "\n"; - }); + } output += "## Next Steps\n\n"; const replayDetailsInstruction = formatToolCallInstruction({ diff --git a/packages/mcp-core/src/tools/support/search-events/utils.ts b/packages/mcp-core/src/tools/support/search-events/utils.ts index af4975d8b2..131472ef92 100644 --- a/packages/mcp-core/src/tools/support/search-events/utils.ts +++ b/packages/mcp-core/src/tools/support/search-events/utils.ts @@ -1348,21 +1348,18 @@ export function createDatasetAttributesTool(options: { let commonFields: Record = {}; let datasetFields: Record = {}; if (substringMatch) { - Object.entries(BASE_COMMON_FIELDS).forEach(([key, value]) => { + for (const [key, value] of Object.entries(BASE_COMMON_FIELDS)) { if (key.includes(substringMatch) || value.includes(substringMatch)) { commonFields[key] = value; } - }); - Object.entries(DATASET_FIELDS[normalizedDataset]).forEach( - ([key, value]) => { - if ( - key.includes(substringMatch) || - value.includes(substringMatch) - ) { - datasetFields[key] = value; - } - }, - ); + } + for (const [key, value] of Object.entries( + DATASET_FIELDS[normalizedDataset], + )) { + if (key.includes(substringMatch) || value.includes(substringMatch)) { + datasetFields[key] = value; + } + } } else { commonFields = BASE_COMMON_FIELDS; datasetFields = DATASET_FIELDS[normalizedDataset]; From ac6b75d40aa9bc5a13bab92a14f1612b0d165343 Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Thu, 26 Nov 2026 19:06:39 +0000 Subject: [PATCH 09/17] feat(cli): use positionals and existing CLI flags in sentry wizard `sentry wizard [/] []` replaces the `@sentry/wizard` flags, with the target first like other commands. - The integration is a positional, one at a time. A bare integration id is never read as a target, and a single bare word is always read as an integration, so a project or org spelled like one is written `my-org/nextjs`, `nextjs/` or `/nextjs`. - The target parses with the CLI's org/project grammar and resolves after login with `resolveOrgOptionalTarget`, like other commands. Without one the org and project pickers run, with no detection. - `-f/--force` is the only flag. It sets both `forceInstall` and `ignoreGitChanges`. - The instance comes from `SENTRY_URL` or the stored login, so the SaaS/self-hosted prompt, `--url`, `--saas` and `skipRcUrlCheck` go. - Spotlight mode follows `SENTRY_SPOTLIGHT`, telemetry follows `isTelemetryEnabled()`, and debug output goes through the CLI logger (`--verbose`, `--log-level`). - Every other `@sentry/wizard` flag and `SENTRY_WIZARD_*` variable is gone, hidden ones included, with `disableTelemetryForRun` and `rejectRemovedFlags`. A test pins the wizard's own flags to `force`, and `check:env-coverage` (part of `ci:policy`) fails when any file under `src/` names `SENTRY_WIZARD_`. Co-Authored-By: BYK <126780+BYK@users.noreply.github.com> --- .../cli-docs/src/fragments/commands/wizard.md | 51 ++- .../sentry-cli/skills/sentry-cli/SKILL.md | 2 +- .../skills/sentry-cli/references/wizard.md | 30 +- packages/cli/script/check-env-coverage.ts | 37 +- packages/cli/src/commands/wizard.ts | 346 +++++++++--------- packages/cli/src/lib/env-registry.ts | 25 +- packages/cli/src/lib/telemetry.ts | 13 - packages/cli/src/lib/wizard/run.ts | 47 +-- packages/cli/src/lib/wizard/telemetry.ts | 9 +- .../cli/src/lib/wizard/utils/clack/index.ts | 8 +- packages/cli/src/lib/wizard/utils/debug.ts | 31 +- .../cli/src/lib/wizard/utils/project-data.ts | 120 +----- packages/cli/src/lib/wizard/utils/types.ts | 32 +- packages/cli/test/commands/wizard.test.ts | 253 +++++++++---- .../lib/wizard/utils/project-data.test.ts | 127 +++++-- 15 files changed, 592 insertions(+), 539 deletions(-) diff --git a/apps/cli-docs/src/fragments/commands/wizard.md b/apps/cli-docs/src/fragments/commands/wizard.md index d754b8845b..91218e9918 100644 --- a/apps/cli-docs/src/fragments/commands/wizard.md +++ b/apps/cli-docs/src/fragments/commands/wizard.md @@ -4,13 +4,29 @@ `sentry wizard` sets up the Sentry SDK in the project in the current directory. It asks a few questions, installs the SDK for your framework, -writes its configuration, and sets up source map or debug file uploads. -Pass `-i` with an integration, such as `nextjs`, to skip the integration -picker. +writes its configuration, and sets up source map or debug file uploads. It +takes an optional `/` first, then an optional integration: + +- Pass an integration, such as `nextjs`, to skip the integration picker. +- Pass `/` first to skip the org and project pickers, or + `/` to pick only the project. Without it, the wizard asks; it doesn't + detect a project from your files. +- An integration id is never read as a project or org, and a single bare + word is always read as an integration. Write a project or org with a `/`: + `my-org/my-project`, `my-org/`, or `/my-project`. For a project spelled + like an integration, write `my-org/nextjs`. +- `-f`/`--force` changes a project with uncommitted changes without asking, + and installs the SDK even when the package manager's checks fail. It logs in with your `sentry auth login` account, or starts a login when you -have none, and lets you pick or create the Sentry project to send data to. -Pass `--org` and `--project` to skip those questions. +have none, on the Sentry instance the rest of the CLI uses: `SENTRY_URL`, or +the stored login's. To use a self-hosted instance, log in to it first with +`sentry auth login --url`. + +Set `SENTRY_SPOTLIGHT=1` to set up Spotlight for local development instead, +with no Sentry account or login. Telemetry follows the CLI's settings +(`SENTRY_CLI_NO_TELEMETRY`, `DO_NOT_TRACK`, `sentry cli defaults`), and the +global `--verbose` flag shows the wizard's debug output. `sentry wizard` changes your project's files. To have a coding agent set up Sentry instead, run `sentry init`, which prints the agent's setup guide and @@ -18,12 +34,19 @@ changes nothing. ## Coming from `@sentry/wizard` -`sentry wizard` takes the same integrations and flags as -`npx @sentry/wizard`, so `npx @sentry/wizard -i nextjs` and -`sentry wizard -i nextjs` do the same thing. These were removed: - -- The sign-up flags `--signup`, `--promo-code` and `--coming-from`. Passing one - fails with an explanation. Sign up at https://sentry.io/signup/ (and apply a - promo code there), then run the wizard. -- The Cordova and Electron wizards. Follow their setup guides in the Sentry - docs instead. +`sentry wizard` takes the same integration ids as `npx @sentry/wizard -i`, +but not its flags or `SENTRY_WIZARD_*` environment variables: + +| `@sentry/wizard` | `sentry wizard` | +| -------------------------------------- | ------------------------------------------------ | +| `-i nextjs` | `nextjs` | +| `--org my-org --project my-project` | `my-org/my-project`, before the integration | +| `--url`, `-u`, `--saas` | `sentry auth login --url`, or `SENTRY_URL` | +| `--spotlight` | `SENTRY_SPOTLIGHT=1` | +| `--force-install`, `--ignore-git-changes` | `-f`/`--force` | +| `--disable-telemetry` | `SENTRY_CLI_NO_TELEMETRY=1` or `DO_NOT_TRACK=1` | +| `--debug` | `--verbose` or `--log-level debug` | +| `--signup`, `--promo-code`, `--coming-from` | Sign up at https://sentry.io/signup/ first | + +The Cordova and Electron wizards were retired. Follow their setup guides in +the Sentry docs instead. diff --git a/packages/cli/plugins/sentry-cli/skills/sentry-cli/SKILL.md b/packages/cli/plugins/sentry-cli/skills/sentry-cli/SKILL.md index 963ccb51a1..d5dc5253d3 100644 --- a/packages/cli/plugins/sentry-cli/skills/sentry-cli/SKILL.md +++ b/packages/cli/plugins/sentry-cli/skills/sentry-cli/SKILL.md @@ -818,7 +818,7 @@ Print instructions for a coding agent to set up Sentry Set up the Sentry SDK in your project interactively -- `sentry wizard` — Set up the Sentry SDK in your project interactively +- `sentry wizard [/] []` — Set up the Sentry SDK in your project interactively → Full flags and examples: `references/wizard.md` diff --git a/packages/cli/plugins/sentry-cli/skills/sentry-cli/references/wizard.md b/packages/cli/plugins/sentry-cli/skills/sentry-cli/references/wizard.md index 7e8405f3e0..fe5382422e 100644 --- a/packages/cli/plugins/sentry-cli/skills/sentry-cli/references/wizard.md +++ b/packages/cli/plugins/sentry-cli/skills/sentry-cli/references/wizard.md @@ -11,33 +11,33 @@ requires: Set up the Sentry SDK in your project interactively -### `sentry wizard` +### `sentry wizard [/] []` Set up the Sentry SDK in your project interactively +**Arguments:** + +| Argument | Description | +|----------|-------------| +| `[/] []` | <org>/<project> to set up (skips the project picker), then the integration (skips the integration picker) | + **Flags:** -- `-i, --integration - Integration to set up (skips the picker)` -- `-u, --url - URL of your self-hosted Sentry instance` -- `--org - Slug of the Sentry organization to use` -- `--project - Slug of the Sentry project to use` -- `--saas - Use Sentry SaaS (sentry.io) without asking` -- `--spotlight - Set up Spotlight for local development, without a Sentry account` -- `--force-install - Install the SDK even when the package manager's checks fail` -- `--ignore-git-changes - Don't ask before changing a project with uncommitted changes` -- `--disable-telemetry - Don't send telemetry about this run to Sentry` -- `--debug - Print the wizard's debug output` +- `-f, --force - Change a project with uncommitted changes without asking, and install the SDK even when the package manager's checks fail` **Examples:** ```bash -# Pick an integration and set it up +# Pick an integration and a project, then set it up sentry wizard -# Set up Next.js for a known org and project on sentry.io -sentry wizard -i nextjs --saas --org my-org --project my-project +# Set up Next.js, picking the project +sentry wizard nextjs + +# Set up Next.js for a known org and project +sentry wizard my-org/my-project nextjs # Set up Next.js for Spotlight, without a Sentry account -sentry wizard -i nextjs --spotlight +SENTRY_SPOTLIGHT=1 sentry wizard nextjs ``` All commands also support `--json`, `--fields`, `--help`, `--log-level`, and `--verbose` flags. diff --git a/packages/cli/script/check-env-coverage.ts b/packages/cli/script/check-env-coverage.ts index c07ddd5fc9..92e7d6c431 100644 --- a/packages/cli/script/check-env-coverage.ts +++ b/packages/cli/script/check-env-coverage.ts @@ -15,13 +15,17 @@ * test-only hooks, and vars inherited from the SDK are listed (with a reason) in * INTERNAL_ENV_VARS so their exclusion is explicit and reviewable. * + * It also fails when any file under src/ names a prefix in + * RETIRED_ENV_PREFIXES, such as the `SENTRY_WIZARD_*` vars of `@sentry/wizard`. + * * Usage: * pnpm ts script/check-env-coverage.ts * * Exit codes: * 0 - Every user-facing env var read by the CLI or an installer is documented * or explicitly internal - * 1 - Coverage gap, redundant allowlist entry, or stale allowlist entry + * 1 - Coverage gap, redundant allowlist entry, stale allowlist entry, or a + * retired env var prefix (RETIRED_ENV_PREFIXES) under src/ */ import { readFile } from "node:fs/promises"; @@ -51,10 +55,6 @@ const INTERNAL_ENV_VARS = new Map([ "SENTRY_ENVIRONMENT", "bash-hook traceback template only; inherited SDK convention", ], - [ - "SENTRY_SPOTLIGHT", - "set by `local run` for the child app; the CLI only names it in Worker setup hints", - ], [ "SENTRY_TRACES_SAMPLE_RATE", "inherited from the SDK when spawning subprocesses, not a CLI config knob", @@ -79,6 +79,17 @@ const INTERNAL_ENV_VARS = new Map([ ["SENTRY_RN_SOURCEMAP_REPORT", "internal react-native wrapper plumbing"], ]); +/** + * Env var prefixes the CLI dropped on purpose. No file under src/ may name + * one, read or not, so none comes back as a hidden alias. Each has a reason. + */ +const RETIRED_ENV_PREFIXES = new Map([ + [ + "SENTRY_WIZARD_", + "`sentry wizard` takes `/` and the integration as positionals, and reads only the CLI's own env vars (SENTRY_URL, SENTRY_SPOTLIGHT, SENTRY_LOG_LEVEL)", + ], +]); + const registryNames = new Set(ENV_VAR_REGISTRY.map((entry) => entry.name)); /** @@ -230,6 +241,22 @@ for (const name of INTERNAL_ENV_VARS.keys()) { } } +// Every file type under src/, generated files included, not just the env +// reads above: a retired name in a string or a comment fails too. +for (const file of await glob("src/**/*")) { + const content = await readFile(file, "utf-8"); + for (const [prefix, reason] of RETIRED_ENV_PREFIXES) { + const index = content.indexOf(prefix); + if (index !== -1) { + const line = content.slice(0, index).split("\n").length; + errors.push( + `Retired env var prefix: ${prefix} (at ${file}:${line})\n` + + ` Remove it: ${reason}.`, + ); + } + } +} + if (errors.length > 0) { logger.error( [ diff --git a/packages/cli/src/commands/wizard.ts b/packages/cli/src/commands/wizard.ts index 71f4b7fefd..01311bd7a6 100644 --- a/packages/cli/src/commands/wizard.ts +++ b/packages/cli/src/commands/wizard.ts @@ -3,244 +3,226 @@ * * Run the interactive setup wizard of a framework or platform: it installs * the Sentry SDK, writes its config files, and sets up source map or debug - * file uploads in the current project. Ported from `@sentry/wizard`, whose - * `-i ` invocations keep working. + * file uploads in the current project. Ported from `@sentry/wizard`. * * The wizard logs in with the CLI's own login instead of the old browser - * hand-off, so `auth: false` here: a run in Spotlight mode, or with a - * preselected project, needs no login at all. + * hand-off, so `auth: false` here: a run in Spotlight mode needs no login at + * all. */ import type { SentryContext } from "../context.js"; -import { buildCommand } from "../lib/command.js"; +import { sentry } from "../lib/app-identity.js"; import { - parseOrgSlug, - parseProjectSlug, - parseText, - parseUrl, -} from "../lib/completion-target.js"; + type ParsedOrgProject, + parseOrgProjectInput, +} from "../lib/arg-parsing.js"; +import { buildCommand } from "../lib/command.js"; +import { ORG_PROJECT_TARGET } from "../lib/completion-target.js"; import { getEnv } from "../lib/env.js"; import { ValidationError, WizardExitError } from "../lib/errors.js"; +import { parseBoolValue } from "../lib/parse-bool.js"; import { - disableTelemetryForRun, - isTelemetryEnabled, -} from "../lib/telemetry.js"; -import { INTEGRATION_IDS, runWizard } from "../lib/wizard/run.js"; + type BoundArguments, + boundArguments, +} from "../lib/positional-parse.js"; +import { applySentryUrlContext } from "../lib/sentry-url-parser.js"; +import { isTelemetryEnabled } from "../lib/telemetry.js"; +import { + INTEGRATION_IDS, + runWizard, + type WizardIntegration, +} from "../lib/wizard/run.js"; import { topLevelBrief } from "../top-level-briefs.js"; +const USAGE = "[/] []"; +const usageHint = () => sentry`wizard ${USAGE}`; + type WizardFlags = { - readonly integration?: string; - readonly url?: string; - readonly org?: string; - readonly project?: string; - readonly saas: boolean; - readonly debug: boolean; - readonly spotlight: boolean; - readonly "disable-telemetry": boolean; - readonly "force-install": boolean; - readonly "ignore-git-changes": boolean; - readonly signup: boolean; - readonly "promo-code"?: string; - readonly "coming-from"?: string; - readonly "skip-connect": boolean; - readonly quiet: boolean; - readonly uninstall: boolean; + readonly force: boolean; }; +/** Parsed `sentry wizard` arguments. */ +export type WizardInput = { + /** The org and project to set up; auto-detect means the user picks */ + readonly target: ParsedOrgProject; + /** Server of a pasted Sentry URL, applied when the arguments resolve */ + readonly baseUrl?: string; + /** The integration to set up; the user picks when unset */ + readonly integration?: WizardIntegration; +}; + +/** The arguments of `sentry wizard`. */ +export type WizardArguments = BoundArguments; + +/** Whether `value` is exactly one of {@link INTEGRATION_IDS}. */ +function isIntegrationId(value: string): value is WizardIntegration { + return (INTEGRATION_IDS as readonly string[]).includes(value); +} + /** - * Fail on the `@sentry/wizard` sign-up and partner flags, which `sentry - * wizard` dropped: it logs in with the CLI's login, which has no sign-up or - * partner step. + * The error for an argument in the integration position that names none. * - * @throws {ValidationError} When one of them is passed + * @param hint - Extra line saying how to name a target instead */ -function rejectRemovedFlags(flags: WizardFlags): void { - const removed = [ - flags.signup ? "--signup" : undefined, - flags["promo-code"] === undefined ? undefined : "--promo-code", - flags["coming-from"] === undefined ? undefined : "--coming-from", - ].filter((flag) => flag !== undefined); - if (removed.length === 0) { - return; - } - throw new ValidationError( - `${removed.join(", ")} ${removed.length === 1 ? "is" : "are"} no longer supported. ` + - "Sign up at https://sentry.io/signup/ (and apply any promo code there), " + - "then run the wizard again without " + - `${removed.length === 1 ? "it" : "them"}.`, - removed[0], +function unknownIntegration(value: string, hint = ""): ValidationError { + return new ValidationError( + `Unknown integration '${value}'. Pick one of: ${INTEGRATION_IDS.join(", ")}.\n` + + `${hint} Usage: ${usageHint()}`, + "integration", ); } -/** The trimmed value of the environment variable `name`, unless empty. */ -function envValue(name: string): string | undefined { - return getEnv()[name]?.trim() || undefined; +/** + * Parse the positionals of `sentry wizard`: `[/] []`. + * Has no side effects. + * + * - No arguments: the user picks both. + * - One argument: a bare word is the integration. A target always has a `/` + * (`/`, `/`, `/`) or is a Sentry URL. + * - Two arguments: the target, then the integration. The first may be any + * target form, including a bare project or org slug, except an + * integration id. + * + * A bare integration id is never a target, in either position: an org or + * project spelled like one is written `/nextjs`, `nextjs/` or + * `/nextjs`. + * + * @throws {ValidationError} For more than two arguments, an unknown + * integration, two integrations, or a malformed target + */ +export function parseWizardArguments(args: readonly string[]): WizardInput { + const [first, second, ...extra] = args; + if (extra.length > 0) { + throw new ValidationError( + `Too many arguments: ${extra.join(" ")}. Expected: ${usageHint()}`, + "positional", + ); + } + if (first === undefined) { + return { target: { type: "auto-detect" } }; + } + if (second === undefined) { + if (isIntegrationId(first)) { + return { target: { type: "auto-detect" }, integration: first }; + } + if (!first.includes("/")) { + throw unknownIntegration( + first, + " To name an org or project instead, write it as /, / or /.\n", + ); + } + } else if (isIntegrationId(first)) { + throw new ValidationError( + `'${first}' is an integration, and the wizard sets up one at a time.\n` + + ` To name a project or org called '${first}', write it as /${first}, ${first}/ or /${first}.\n` + + ` Usage: ${usageHint()}`, + "integration", + ); + } else if (!isIntegrationId(second)) { + throw unknownIntegration(second); + } + const { parsed, baseUrl } = parseOrgProjectInput(first); + return { + target: parsed, + ...(baseUrl && { baseUrl }), + ...(second !== undefined && { integration: second }), + }; +} + +/** + * Whether `SENTRY_SPOTLIGHT` turns on Spotlight mode. Like the Sentry SDKs, + * any value but an empty or false-like one (`0`, `false`, `off`, …) counts, + * including a Spotlight URL. + */ +function isSpotlightEnabled(): boolean { + const value = getEnv()["SENTRY_SPOTLIGHT"]?.trim(); + return value ? parseBoolValue(value) !== false : false; } export const wizardCommand = buildCommand({ auth: false, - // The wizard picks the Sentry instance itself (`--url`, `--saas` or a - // prompt) before it logs in, like `sentry init`. - skipRcUrlCheck: true, docs: { brief: topLevelBrief("wizard"), + customUsage: [USAGE], fullDescription: "Set up Sentry in the project in the current directory. The wizard " + "asks you a few questions, installs the Sentry SDK for your framework, " + "writes its configuration, and sets up source map or debug file " + - "uploads. It logs in with your `sentry auth login` account (or starts " + - "a login), and lets you pick or create the Sentry project to send " + - "data to.\n\n" + - "Pass `-i` to skip the integration picker. It takes the same " + - "integrations and flags as `npx @sentry/wizard`, except the sign-up " + - "flags `--signup`, `--promo-code` and `--coming-from`, which fail: " + - "sign up at https://sentry.io/signup/ first.\n\n" + + "uploads.\n\n" + + "It logs in with your `sentry auth login` account (or starts a login) " + + "on the Sentry instance the rest of the CLI uses, and lets you pick or " + + "create the Sentry project to send data to. Pass `/` " + + "first to skip those questions, or `/` to pick only the project. " + + "Pass an integration, such as `nextjs`, to skip the integration " + + `picker. Integrations: ${INTEGRATION_IDS.join(", ")}.\n\n` + + "An integration id is never read as a project or org, and a single " + + "bare word is always read as an integration. To name a project or " + + "org, write it with a `/`: `my-org/my-project`, `my-org/`, or " + + "`/my-project` (for a project spelled like an integration, " + + "`my-org/nextjs`).\n\n" + + "Set `SENTRY_SPOTLIGHT=1` to set up Spotlight for local development " + + "instead, without a Sentry account or login. Use the global " + + "`--verbose` flag for the wizard's debug output.\n\n" + "The wizard changes files in your project. To have a coding agent set " + "up Sentry instead, run `sentry init`, which prints the agent's setup " + "guide and changes nothing.", examples: [ { - description: "Pick an integration and set it up", + description: "Pick an integration and a project, then set it up", run: "wizard", }, { - description: "Set up Next.js for a known org and project on sentry.io", - run: "wizard -i nextjs --saas --org my-org --project my-project", + description: "Set up Next.js, picking the project", + run: "wizard nextjs", + }, + { + description: "Set up Next.js for a known org and project", + run: "wizard my-org/my-project nextjs", }, { description: "Set up Next.js for Spotlight, without a Sentry account", - run: "wizard -i nextjs --spotlight", + run: { prefix: "SENTRY_SPOTLIGHT=1 ", args: "wizard nextjs" }, }, ], }, parameters: { + positional: boundArguments({ + placeholder: "org/project-or-integration", + brief: + "/ to set up (skips the project picker), then the integration (skips the integration picker)", + kind: ORG_PROJECT_TARGET, + parse: parseWizardArguments, + // The org and project resolve after the wizard logs in; only a pasted + // URL's server applies here, before the login picks an instance. + resolve: async (input) => { + if (input.baseUrl) { + applySentryUrlContext(input.baseUrl); + } + return input; + }, + }), flags: { - integration: { - kind: "enum", - values: INTEGRATION_IDS, - brief: "Integration to set up (skips the picker)", - optional: true, - }, - url: { - kind: "parsed", - parse: parseUrl, - brief: "URL of your self-hosted Sentry instance", - placeholder: "url", - optional: true, - }, - org: { - kind: "parsed", - parse: parseOrgSlug, - brief: "Slug of the Sentry organization to use", - placeholder: "org", - optional: true, - }, - project: { - kind: "parsed", - parse: parseProjectSlug, - brief: "Slug of the Sentry project to use", - placeholder: "project", - optional: true, - }, - saas: { - kind: "boolean", - brief: "Use Sentry SaaS (sentry.io) without asking", - default: false, - }, - spotlight: { + force: { kind: "boolean", brief: - "Set up Spotlight for local development, without a Sentry account", - default: false, - }, - "force-install": { - kind: "boolean", - brief: "Install the SDK even when the package manager's checks fail", - default: false, - }, - "ignore-git-changes": { - kind: "boolean", - brief: "Don't ask before changing a project with uncommitted changes", - default: false, - }, - "disable-telemetry": { - kind: "boolean", - brief: "Don't send telemetry about this run to Sentry", - default: false, - }, - debug: { - kind: "boolean", - brief: "Print the wizard's debug output", - default: false, - }, - // `@sentry/wizard`'s sign-up and partner flags. The wizard logs in - // with the CLI's login, which has no sign-up or partner step, so these - // fail with an explanation instead of being dropped silently. - signup: { - kind: "boolean", - brief: "Removed: sign up at https://sentry.io/signup/ first", - default: false, - hidden: true as const, - }, - "promo-code": { - kind: "parsed", - parse: parseText, - brief: "Removed: apply promo codes when you sign up", - placeholder: "code", - optional: true, - hidden: true as const, - }, - "coming-from": { - kind: "parsed", - parse: parseText, - brief: "Removed: partner sign-up is not supported", - placeholder: "partner", - optional: true, - hidden: true as const, - }, - // Flags `@sentry/wizard` accepted that no flow reads any more. Kept so - // copied commands still run. - "skip-connect": { - kind: "boolean", - brief: "Ignored", + "Change a project with uncommitted changes without asking, and install the SDK even when the package manager's checks fail", default: false, - hidden: true as const, - }, - quiet: { - kind: "boolean", - brief: "Ignored", - default: false, - hidden: true as const, - }, - uninstall: { - kind: "boolean", - brief: "Ignored: only the retired Cordova wizard could uninstall", - default: false, - hidden: true as const, }, }, - aliases: { i: "integration", u: "url", s: "signup" }, + aliases: { f: "force" }, }, // oxlint-disable-next-line require-yield -- The wizard prints its own interactive output; the command yields none. - async *func(this: SentryContext, flags: WizardFlags) { - rejectRemovedFlags(flags); - if (flags["disable-telemetry"]) { - disableTelemetryForRun(); - } - + async *func(this: SentryContext, flags: WizardFlags, args: WizardArguments) { + const { target, integration } = await args.resolved; try { await runWizard({ - integration: flags.integration ?? envValue("SENTRY_WIZARD_INTEGRATION"), - debug: flags.debug || envValue("SENTRY_WIZARD_DEBUG") === "true", + integration, wizardOptions: { - telemetryEnabled: !flags["disable-telemetry"] && isTelemetryEnabled(), - url: flags.url ?? envValue("SENTRY_WIZARD_URL"), - orgSlug: flags.org, - projectSlug: flags.project, - saas: flags.saas, - forceInstall: flags["force-install"], - ignoreGitChanges: flags["ignore-git-changes"], - spotlight: flags.spotlight, + telemetryEnabled: isTelemetryEnabled(), + target, + forceInstall: flags.force, + ignoreGitChanges: flags.force, + spotlight: isSpotlightEnabled(), }, }); } catch (error) { diff --git a/packages/cli/src/lib/env-registry.ts b/packages/cli/src/lib/env-registry.ts index b9b5edb556..52d355f748 100644 --- a/packages/cli/src/lib/env-registry.ts +++ b/packages/cli/src/lib/env-registry.ts @@ -139,24 +139,6 @@ export const ENV_VAR_REGISTRY: readonly EnvVarEntry[] = [ selfHosted: true, devGuide: "Sentry OAuth app client ID", }, - { - name: "SENTRY_WIZARD_INTEGRATION", - description: - "Integration for `sentry wizard` to set up when `-i` is not passed, such as `nextjs`. Kept from `@sentry/wizard`.", - example: "nextjs", - }, - { - name: "SENTRY_WIZARD_URL", - description: - "URL of the self-hosted Sentry instance for `sentry wizard` when `--url` is not passed. Kept from `@sentry/wizard`.", - example: "https://sentry.example.com", - }, - { - name: "SENTRY_WIZARD_DEBUG", - description: - "Set to `true` to print the debug output of `sentry wizard`, like `--debug`. Kept from `@sentry/wizard`.", - example: "true", - }, { name: "SENTRY_HANDOFF", description: @@ -220,6 +202,13 @@ export const ENV_VAR_REGISTRY: readonly EnvVarEntry[] = [ example: "1", installOnly: true, }, + // -- Local development -- + { + name: "SENTRY_SPOTLIGHT", + description: + "Turns on Spotlight, the local debugger, in Sentry SDKs. Set it to `1`, `true`, or a Spotlight URL when running `sentry wizard` to set up Spotlight for local development instead of a Sentry project, with no login. Empty, `0`, `false`, and `off` leave it off. `sentry local run` sets it for the app it runs.", + example: "1", + }, // -- Games -- { name: "SENTRY_GAMES_API_URL", diff --git a/packages/cli/src/lib/telemetry.ts b/packages/cli/src/lib/telemetry.ts index b4e32c1640..2467c3f349 100644 --- a/packages/cli/src/lib/telemetry.ts +++ b/packages/cli/src/lib/telemetry.ts @@ -176,19 +176,6 @@ export function isTelemetryEnabled(): boolean { return computeTelemetryEffective().enabled; } -/** - * Stop sending telemetry for the rest of this run, after `withTelemetry` - * already started it: the client drops every envelope from now on, including - * the command's own transaction. For flags such as `sentry wizard - * --disable-telemetry` that opt out of one run. - */ -export function disableTelemetryForRun(): void { - const client = Sentry.getClient(); - if (client) { - client.getOptions().enabled = false; - } -} - /** * Attributes a Snake score metric may carry. Everything else the SDK adds * (user.*, replay ids, ...) is dropped so a score cannot be linked to a user. diff --git a/packages/cli/src/lib/wizard/run.ts b/packages/cli/src/lib/wizard/run.ts index 8bd377980b..ebae262d08 100644 --- a/packages/cli/src/lib/wizard/run.ts +++ b/packages/cli/src/lib/wizard/run.ts @@ -9,12 +9,11 @@ import { ValidationError } from "../errors.js"; import { abortIfCancelled } from "./utils/clack/index.js"; import { clack } from "./utils/clack/prompts.js"; -import { enableDebugLogs } from "./utils/debug.js"; import type { WizardOptions } from "./utils/types.js"; import { CLI_VERSION } from "../constants.js"; /** - * The integrations `sentry wizard -i` accepts, in the order the picker lists + * The integrations `sentry wizard` accepts, in the order the picker lists * them. The ids are the ones `@sentry/wizard -i` took. */ export const WIZARD_INTEGRATIONS = [ @@ -33,12 +32,13 @@ export const WIZARD_INTEGRATIONS = [ { id: "sourcemaps", label: "Configure Source Maps Upload" }, ] as const; -/** An integration id `sentry wizard -i` accepts. */ +/** An integration id `sentry wizard` accepts. */ export type WizardIntegration = (typeof WIZARD_INTEGRATIONS)[number]["id"]; /** - * Every value `-i` accepts. The Cordova and Electron wizards of - * `@sentry/wizard` were retired; their setup guides are in the Sentry docs. + * Every integration id `sentry wizard` accepts. The Cordova and Electron + * wizards of `@sentry/wizard` were retired; their setup guides are in the + * Sentry docs. */ export const INTEGRATION_IDS: readonly WizardIntegration[] = WIZARD_INTEGRATIONS.map((integration) => integration.id); @@ -59,10 +59,8 @@ const WIZARD_RUNNERS: Partial> = { /** What `sentry wizard` passes to {@link runWizard}. */ export type RunWizardArgs = { - /** `-i`: the integration to set up; prompts for one when unset. */ - integration?: string | undefined; - /** `--debug`: print the wizard's debug output. */ - debug: boolean; + /** The integration to set up; prompts for one when unset. */ + integration?: WizardIntegration | undefined; /** The options every wizard flow takes. */ wizardOptions: WizardOptions; }; @@ -71,17 +69,11 @@ export type RunWizardArgs = { * Run the wizard of `args.integration`, after asking for one when it is * unset. * - * @throws {ValidationError} For an unknown integration, or one that has no - * flow in this version yet + * @throws {ValidationError} For an integration that has no flow in this + * version yet */ export async function runWizard(args: RunWizardArgs): Promise { - if (args.debug) { - enableDebugLogs(); - } - - const integration = args.integration - ? toWizardIntegration(args.integration) - : await askForIntegration(); + const integration = args.integration ?? (await askForIntegration()); const runner = WIZARD_RUNNERS[integration]; if (!runner) { @@ -93,25 +85,6 @@ export async function runWizard(args: RunWizardArgs): Promise { await runner(args.wizardOptions); } -/** - * `id` as one of {@link WIZARD_INTEGRATIONS}. `-i` already checks its - * value; `SENTRY_WIZARD_INTEGRATION` is checked here. - * - * @throws {ValidationError} When `id` names no integration - */ -function toWizardIntegration(id: string): WizardIntegration { - const match = WIZARD_INTEGRATIONS.find( - (integration) => integration.id === id, - ); - if (!match) { - throw new ValidationError( - `Unknown integration "${id}". Pick one of: ${INTEGRATION_IDS.join(", ")}.`, - "integration", - ); - } - return match.id; -} - /** Ask which integration to set up, out of the ones that have a flow. */ async function askForIntegration(): Promise { clack.intro(`Sentry Wizard ${CLI_VERSION}`); diff --git a/packages/cli/src/lib/wizard/telemetry.ts b/packages/cli/src/lib/wizard/telemetry.ts index 09a39e330d..e19324fcca 100644 --- a/packages/cli/src/lib/wizard/telemetry.ts +++ b/packages/cli/src/lib/wizard/telemetry.ts @@ -6,8 +6,7 @@ * wizard flow is a `wizard.flow` span under it and each step a `wizard.step` * span under that. Tags go on the same scope as the CLI's. Telemetry is off * when the CLI's is (`SENTRY_CLI_NO_TELEMETRY`, `DO_NOT_TRACK`, or - * `sentry cli defaults telemetry off`), and `--disable-telemetry` turns it - * off for the run. + * `sentry cli defaults telemetry off`). * * The old wizard sent its telemetry to a project of its own; the tag names * stay the same so its dashboards can move over. @@ -26,7 +25,7 @@ export const Sentry = { setTag, setUser }; /** * Run a wizard flow in a `wizard.flow` span, tagged with the integration and - * which of `--org`, `--project`, and `--saas` were passed. + * the kind of `/` target passed (`auto-detect` for none). */ export async function withTelemetry( options: { @@ -38,9 +37,7 @@ export async function withTelemetry( callback: () => F | Promise, ): Promise { setTag("integration", options.integration); - setTag("args.project", Boolean(options.wizardOptions.projectSlug)); - setTag("args.org", Boolean(options.wizardOptions.orgSlug)); - setTag("args.saas", Boolean(options.wizardOptions.saas)); + setTag("args.target", options.wizardOptions.target?.type ?? "auto-detect"); return await startSpan( { diff --git a/packages/cli/src/lib/wizard/utils/clack/index.ts b/packages/cli/src/lib/wizard/utils/clack/index.ts index a076b5049b..35282ec08e 100644 --- a/packages/cli/src/lib/wizard/utils/clack/index.ts +++ b/packages/cli/src/lib/wizard/utils/clack/index.ts @@ -169,8 +169,8 @@ export function printWelcome(options: { This wizard sends telemetry data and crash reports to Sentry. This helps us improve the Wizard. You can turn this off at any time by running ${chalk.cyanBright( - sentry`wizard --disable-telemetry`, - )}.`; + sentry`cli defaults telemetry off`, + )}, or by setting SENTRY_CLI_NO_TELEMETRY=1.`; } clack.note(welcomeText); @@ -200,7 +200,7 @@ export async function confirmContinueIfNoOrDirtyGitRepo({ ) { if (nonInteractive) { clack.log.error( - "Project is not inside a git repository in non-interactive mode. Run from a git repository or pass --ignore-git-changes to skip this safety check.", + "Project is not inside a git repository in non-interactive mode. Run from a git repository or pass --force to skip this safety check.", ); Sentry.setTag("continue-without-git", false); await abort(); @@ -237,7 +237,7 @@ The wizard will create and update files.`, if (nonInteractive) { clack.log.error( - "Project has uncommitted or untracked files in non-interactive mode. Commit or stash your changes, or pass --ignore-git-changes to skip this safety check.", + "Project has uncommitted or untracked files in non-interactive mode. Commit or stash your changes, or pass --force to skip this safety check.", ); Sentry.setTag("continue-with-dirty-repo", false); await abort(); diff --git a/packages/cli/src/lib/wizard/utils/debug.ts b/packages/cli/src/lib/wizard/utils/debug.ts index c8668c78ce..a8fb70f99a 100644 --- a/packages/cli/src/lib/wizard/utils/debug.ts +++ b/packages/cli/src/lib/wizard/utils/debug.ts @@ -1,32 +1,13 @@ /** - * Debug output of the setup wizards, shown with `sentry wizard --debug`. + * Debug output of the setup wizards, shown with the CLI's global `--verbose` + * or `--log-level debug`. */ -import chalk from "chalk"; -import { clack } from "./clack/prompts.js"; +import { logger } from "../../logger.js"; -let debugEnabled = false; +const log = logger.withTag("wizard"); -/** Render one debug argument: strings as-is, errors with their stack. */ -function prepareMessage(msg: unknown): string { - if (typeof msg === "string") { - return msg; - } - if (msg instanceof Error) { - return msg.stack ?? msg.message; - } - return JSON.stringify(msg, null, "\t"); -} - -/** Log `args` in the wizard's output when `--debug` is on. */ +/** Log `args` at the CLI logger's debug level. */ export function debug(...args: unknown[]): void { - if (!debugEnabled) { - return; - } - clack.log.info(chalk.dim(args.map((a) => prepareMessage(a)).join(" "))); -} - -/** Turn on {@link debug} output for the rest of the run. */ -export function enableDebugLogs(): void { - debugEnabled = true; + log.debug(...args); } diff --git a/packages/cli/src/lib/wizard/utils/project-data.ts b/packages/cli/src/lib/wizard/utils/project-data.ts index 0e4b856c32..c44faa30a0 100644 --- a/packages/cli/src/lib/wizard/utils/project-data.ts +++ b/packages/cli/src/lib/wizard/utils/project-data.ts @@ -9,8 +9,11 @@ * agent handoff from `SENTRY_HANDOFF`) when there is none. A new login asks * for `org:tokens` and `org:ci` too, so the auth token below needs no second * approval. - * - The org from `--org`, the handoff, or a prompt; then the project from - * `--project` or a prompt that can also create one for the wizard's + * - The Sentry instance the rest of the CLI uses: `SENTRY_URL`, or the + * stored login's. + * - The org and project of the `/` target, resolved like other + * commands' targets; else the org from the handoff or a prompt, then the + * project from a prompt that can also create one for the wizard's * platform, like the old browser page could. * - The project's DSN from its client keys. * - A new org auth token for the build plugins and `sentry` commands that @@ -33,21 +36,18 @@ import { MEMBER_PROJECT_CREATION_DISABLED_DETAIL, } from "../../api/projects.js"; import { assertAutoLoginHostTrusted } from "../../auto-auth.js"; -import { DEFAULT_SENTRY_URL } from "../../constants.js"; import { getAuthConfig } from "../../db/auth.js"; import { getEnv } from "../../env.js"; import { ApiError } from "../../errors.js"; import { runInteractiveLogin } from "../../interactive-login.js"; import { logger } from "../../logger.js"; import { OAUTH_SCOPES, resolveOAuthScopeString } from "../../oauth.js"; +import { resolveOrgOptionalTarget } from "../../resolve-target.js"; import { resolveOrCreateTeam } from "../../resolve-team.js"; import { ensureScopesForAction } from "../../scope-recovery.js"; import { isSentrySaasUrl } from "../../sentry-urls.js"; import { getApiBaseUrl } from "../../sentry-client.js"; -import { - isRequestOriginTrusted, - registerLoginTrustAnchor, -} from "../../token-host.js"; +import { isRequestOriginTrusted } from "../../token-host.js"; import { slugify } from "../../utils.js"; import { sentry } from "../../app-identity.js"; import type { @@ -104,7 +104,7 @@ export type WizardProjectData = * `options.preSelectedProject`, or one the user picks (or creates) after * logging in. * - * @param options - Wizard options (`--url`, `--saas`, `--org`, `--project`, …) + * @param options - Wizard options (the `/` target, Spotlight, …) * @param platform - Platform for a project the user creates */ export async function getOrAskForProjectData( @@ -122,29 +122,33 @@ export async function getOrAskForProjectData( if (options.preSelectedProject) { return { selfHosted: options.preSelectedProject.selfHosted, - sentryUrl: withTrailingSlash(options.url ?? DEFAULT_SENTRY_URL), + sentryUrl: withTrailingSlash(getApiBaseUrl()), authToken: options.preSelectedProject.authToken, selectedProject: options.preSelectedProject.project, spotlight: false, }; } - await traceStep("ask-self-hosted", () => - selectSentryUrl(options.url, options.saas), - ); const handoffOrg = await traceStep("login", ensureLoggedIn); - // The chosen instance, or the stored login's when none was chosen. + // `SENTRY_URL`, or the stored login's instance. const sentryUrl = withTrailingSlash(getApiBaseUrl()); const selfHosted = !isSentrySaasUrl(sentryUrl); Sentry.setTag("url", sentryUrl); Sentry.setTag("self-hosted", selfHosted); + const parsedTarget = options.target; + const target = + parsedTarget && parsedTarget.type !== "auto-detect" + ? await traceStep("resolve-target", () => + resolveOrgOptionalTarget(parsedTarget, process.cwd(), "wizard"), + ) + : undefined; const org = await traceStep("select-org", () => - selectOrganization(options.orgSlug ?? handoffOrg), + selectOrganization(target?.org ?? handoffOrg), ); const project = await traceStep("select-project", () => - selectProject(org, options.projectSlug, platform), + selectProject(org, target?.project, platform), ); Sentry.setTag("project", project.slug); Sentry.setUser({ id: org.slug }); @@ -168,90 +172,6 @@ export async function getOrAskForProjectData( }; } -/** - * Point this run at the Sentry instance the user chose: SaaS for `--saas`, - * the `--url` instance, or the answer to a SaaS/self-hosted prompt. Without - * any of them and with a stored login, the login's instance is used. - * - * An instance the user names here (flag or prompt) is trusted for login, the - * same as `sentry auth login --url`. - */ -async function selectSentryUrl( - urlFromArgs: string | undefined, - saas: boolean | undefined, -): Promise { - if (saas) { - useSentryUrl(DEFAULT_SENTRY_URL); - return; - } - if (!urlFromArgs && getAuthConfig()) { - return; - } - - if (!urlFromArgs) { - const choice = await abortIfCancelled( - clack.select({ - message: "Are you using Sentry SaaS or self-hosted Sentry?", - options: [ - { value: "saas", label: "Sentry SaaS (sentry.io)" }, - { - value: "self-hosted", - label: "Self-hosted/on-premise/single-tenant", - }, - ], - }), - ); - if (choice === "saas") { - useSentryUrl(DEFAULT_SENTRY_URL); - return; - } - } - - let pending = urlFromArgs; - for (;;) { - const url = - pending || - (await abortIfCancelled( - clack.text({ - message: `Please enter the URL of your ${ - urlFromArgs ? "" : "self-hosted " - }Sentry instance.`, - placeholder: "https://sentry.io/", - }), - )); - pending = undefined; - const origin = parseOrigin(url); - if (origin) { - useSentryUrl(origin); - return; - } - clack.log.error( - `Please enter a valid URL. (It should look something like "https://sentry.mydomain.com/", got ${url})`, - ); - } -} - -/** The origin of `url`, or `undefined` when it isn't an HTTP(S) URL. */ -function parseOrigin(url: string): string | undefined { - try { - const parsed = new URL(url); - return parsed.protocol === "https:" || parsed.protocol === "http:" - ? parsed.origin - : undefined; - } catch (error) { - log.debug(`Invalid Sentry URL ${url}`, error); - return; - } -} - -/** Send this run's API requests and login to `url`, trusted as user input. */ -function useSentryUrl(url: string): void { - const env = getEnv(); - env["SENTRY_HOST"] = url; - env["SENTRY_URL"] = url; - registerLoginTrustAnchor(url); -} - /** * Make sure the CLI has a login for the selected instance: claim the agent * handoff in `SENTRY_HANDOFF`, keep a stored login, or run the device flow. @@ -405,7 +325,7 @@ async function createProject( spinner.start("Creating your Sentry project"); try { const team = await resolveOrCreateTeam(orgSlug, { - usageHint: sentry`wizard --org `, + usageHint: sentry`wizard /`, autoCreateSlug: slugify(body.name), }); const { project } = await createProjectWithDsn(orgSlug, team.slug, body); diff --git a/packages/cli/src/lib/wizard/utils/types.ts b/packages/cli/src/lib/wizard/utils/types.ts index d349678578..1f53c0e364 100644 --- a/packages/cli/src/lib/wizard/utils/types.ts +++ b/packages/cli/src/lib/wizard/utils/types.ts @@ -3,6 +3,8 @@ * flow, the Sentry project a flow sets up, and feature prompts. */ +import type { ParsedOrgProject } from "../../arg-parsing.js"; + export interface SentryProjectData { id: string; slug: string; @@ -27,30 +29,11 @@ export type WizardOptions = { telemetryEnabled: boolean; /** - * The url of the Sentry instance to use. - * This can be passed via the `-u` or `--url` arg. - */ - url?: string | undefined; - - /** - * The org to pre-select in the wizard. - * This can be passed via the `--org` arg. - * Example: `--org my-org` - */ - orgSlug?: string | undefined; - - /** - * Project slug to pre-select in the wizard. - * This can be passed via the `--project` arg. - * Example: `--project my-project` - */ - projectSlug?: string | undefined; - - /** - * If this option is set, the wizard will skip the self-hosted or SaaS - * selection step and directly assume that the wizard is used for Sentry SaaS. + * The org and project from `sentry wizard /`, resolved after + * the login: an org and project skip both pickers, an org (`/`) skips + * the org picker. Unset or auto-detect: the user picks both. */ - saas?: boolean | undefined; + target?: ParsedOrgProject | undefined; /** * If this is set, the wizard will skip the login and project selection step. @@ -69,6 +52,7 @@ export type WizardOptions = { /** * If this is set, the wizard will ignore any git changes in the project and not prompt for confirmation. + * `sentry wizard --force` sets it, together with {@link forceInstall}. */ ignoreGitChanges?: boolean | undefined; @@ -78,7 +62,7 @@ export type WizardOptions = { * - Skips login and project selection * - Uses empty DSN * - Skips auth token file creation - * This can be passed via the `--spotlight` arg. + * `sentry wizard` turns it on when `SENTRY_SPOTLIGHT` is set. */ spotlight?: boolean | undefined; }; diff --git a/packages/cli/test/commands/wizard.test.ts b/packages/cli/test/commands/wizard.test.ts index 46be02ce14..3705740bb9 100644 --- a/packages/cli/test/commands/wizard.test.ts +++ b/packages/cli/test/commands/wizard.test.ts @@ -1,40 +1,38 @@ /** - * Tests for `sentry wizard`: integration selection, the flags it passes to a - * wizard flow, and how a stopped wizard sets the exit code. + * Tests for `sentry wizard`: its command line (`[/] + * []` and `--force`, nothing else), what it passes to a wizard + * flow, and how a stopped wizard sets the exit code. */ import { afterEach, beforeEach, describe, expect, test, vi } from "vitest"; -const { runNextjsWizard } = vi.hoisted(() => ({ +const { runNextjsWizard, isTelemetryEnabled } = vi.hoisted(() => ({ runNextjsWizard: vi.fn<(options: unknown) => Promise>(), + isTelemetryEnabled: vi.fn<() => boolean>(), })); vi.mock("../../src/lib/wizard/nextjs/nextjs-wizard.js", () => ({ runNextjsWizard, })); +vi.mock("../../src/lib/telemetry.js", async (importOriginal) => ({ + ...(await importOriginal()), + isTelemetryEnabled, +})); -import { wizardCommand } from "../../src/commands/wizard.js"; +import { + parseWizardArguments, + wizardCommand, +} from "../../src/commands/wizard.js"; import type { SentryContext } from "../../src/context.js"; +import { buildCommand } from "../../src/lib/command.js"; import { ValidationError, WizardExitError } from "../../src/lib/errors.js"; import type { Writer } from "../../src/types/index.js"; import { loadCommand, useTestConfigDir } from "../helpers.js"; useTestConfigDir("wizard-test-"); -const DEFAULT_FLAGS = { - saas: false, - debug: false, - spotlight: false, - "disable-telemetry": false, - "force-install": false, - "ignore-git-changes": false, - signup: false, - "skip-connect": false, - quiet: false, - uninstall: false, -}; - async function runWizardCommand( flags: Record = {}, + ...args: string[] ): Promise { const context = { process, @@ -47,12 +45,21 @@ async function runWizardCommand( configDir: "/tmp", } as unknown as SentryContext; const func = await loadCommand(wizardCommand); - await func.call(context, { ...DEFAULT_FLAGS, ...flags }); + await func.call(context, { force: false, ...flags }, ...args); +} + +/** The options the Next.js flow was called with. */ +function nextjsOptions(): Record { + expect(runNextjsWizard).toHaveBeenCalledTimes(1); + return runNextjsWizard.mock.calls[0]?.[0] as Record; } beforeEach(() => { runNextjsWizard.mockReset(); runNextjsWizard.mockResolvedValue(undefined); + isTelemetryEnabled.mockReset(); + isTelemetryEnabled.mockReturnValue(true); + vi.stubEnv("SENTRY_SPOTLIGHT", ""); process.exitCode = undefined; }); @@ -61,72 +68,182 @@ afterEach(() => { process.exitCode = undefined; }); -describe("sentry wizard", () => { - test("runs the -i integration with the @sentry/wizard flags", async () => { - await runWizardCommand({ +describe("sentry wizard flags", () => { + /** Flags and aliases `buildCommand` adds to every command. */ + const injected = buildCommand({ + auth: false, + docs: { brief: "probe" }, + parameters: {}, + // oxlint-disable-next-line require-yield -- A probe; it never runs. + async *func() { + await Promise.resolve(); + }, + }).parameters; + + test("--force (-f) is the wizard's only flag, and it is not hidden", () => { + const { flags = {}, aliases = {} } = wizardCommand.parameters as { + flags?: Record; + aliases?: Record; + }; + const ownFlags = Object.keys(flags).filter( + (name) => !(name in (injected.flags ?? {})), + ); + const ownAliases = Object.entries(aliases).filter( + ([alias]) => !(alias in (injected.aliases ?? {})), + ); + + expect(ownFlags).toEqual(["force"]); + expect(flags["force"]?.hidden).toBeUndefined(); + expect(Object.fromEntries(ownAliases)).toEqual({ f: "force" }); + }); +}); + +describe("parseWizardArguments", () => { + test("no arguments: the user picks the integration and the project", () => { + expect(parseWizardArguments([])).toEqual({ + target: { type: "auto-detect" }, + }); + }); + + test("an integration alone", () => { + expect(parseWizardArguments(["nextjs"])).toEqual({ + target: { type: "auto-detect" }, integration: "nextjs", - org: "acme", - project: "web", - url: "https://sentry.example.com", - spotlight: true, - "force-install": true, - "ignore-git-changes": true, - "disable-telemetry": true, }); + }); - expect(runNextjsWizard).toHaveBeenCalledWith({ - telemetryEnabled: false, - url: "https://sentry.example.com", - orgSlug: "acme", - projectSlug: "web", - saas: false, - forceInstall: true, - ignoreGitChanges: true, - spotlight: true, + test("a target alone", () => { + expect(parseWizardArguments(["my-org/my-project"])).toEqual({ + target: { type: "explicit", org: "my-org", project: "my-project" }, + }); + expect(parseWizardArguments(["my-org/"])).toEqual({ + target: { type: "org-all", org: "my-org" }, + }); + expect(parseWizardArguments(["/my-project"])).toEqual({ + target: { type: "project-search", projectSlug: "my-project" }, }); }); - test.each([ - [{ signup: true }, "--signup is no longer supported."], - [{ "promo-code": "PROMO" }, "--promo-code is no longer supported."], - [{ "coming-from": "vercel" }, "--coming-from is no longer supported."], - [ - { signup: true, "promo-code": "PROMO" }, - "--signup, --promo-code are no longer supported.", - ], - ])("rejects the removed sign-up flags %o", async (flags, message) => { - const error = await runWizardCommand({ integration: "nextjs", ...flags }) - .then(() => undefined) - .catch((caught: unknown) => caught); - - expect(error).toBeInstanceOf(ValidationError); - expect((error as ValidationError).message).toContain(message); - expect((error as ValidationError).message).toContain( - "https://sentry.io/signup/", + test("a target, then an integration", () => { + expect(parseWizardArguments(["my-org/my-project", "nextjs"])).toEqual({ + target: { type: "explicit", org: "my-org", project: "my-project" }, + integration: "nextjs", + }); + }); + + test("a bare project or org slug before an integration is the target", () => { + expect(parseWizardArguments(["my-project", "nextjs"])).toEqual({ + target: { type: "project-search", projectSlug: "my-project" }, + integration: "nextjs", + }); + }); + + test("a bare slug alone is read as an integration, so it must be one", () => { + expect(() => parseWizardArguments(["my-project"])).toThrow( + new ValidationError( + "Unknown integration 'my-project'. Pick one of: reactNative, flutter, ios, appleSnapshots, angular, android, nextjs, nuxt, remix, reactRouter, sveltekit, cloudflare, sourcemaps.\n" + + " To name an org or project instead, write it as /, / or /.\n" + + " Usage: sentry wizard [/] []", + "integration", + ), + ); + }); + + test("a project named like an integration is written with its org", () => { + expect(parseWizardArguments(["my-org/nextjs"])).toEqual({ + target: { type: "explicit", org: "my-org", project: "nextjs" }, + }); + expect(parseWizardArguments(["my-org/nextjs", "nextjs"])).toEqual({ + target: { type: "explicit", org: "my-org", project: "nextjs" }, + integration: "nextjs", + }); + expect(parseWizardArguments(["/nextjs"])).toEqual({ + target: { type: "project-search", projectSlug: "nextjs" }, + }); + }); + + test("an unknown integration after a target", () => { + expect(() => parseWizardArguments(["my-org/my-project", "cobol"])).toThrow( + "Unknown integration 'cobol'.", ); - expect(runNextjsWizard).not.toHaveBeenCalled(); }); - test("reads the integration and URL from SENTRY_WIZARD_* variables", async () => { - vi.stubEnv("SENTRY_WIZARD_INTEGRATION", "nextjs"); - vi.stubEnv("SENTRY_WIZARD_URL", "https://self-hosted.example.com"); + test("integration ids are matched exactly", () => { + expect(() => parseWizardArguments(["NextJS"])).toThrow( + "Unknown integration 'NextJS'.", + ); + expect(() => parseWizardArguments(["nextjs,remix"])).toThrow( + "Unknown integration 'nextjs,remix'.", + ); + }); - await runWizardCommand(); + test("exactly one integration", () => { + expect(() => parseWizardArguments(["nextjs", "remix"])).toThrow( + "'nextjs' is an integration, and the wizard sets up one at a time.\n" + + " To name a project or org called 'nextjs', write it as /nextjs, nextjs/ or /nextjs.", + ); + }); - expect(runNextjsWizard).toHaveBeenCalledWith( - expect.objectContaining({ url: "https://self-hosted.example.com" }), + test("too many arguments", () => { + expect(() => + parseWizardArguments(["my-org/my-project", "nextjs", "remix"]), + ).toThrow( + "Too many arguments: remix. Expected: sentry wizard [/] []", ); }); +}); + +describe("sentry wizard", () => { + test("runs the integration for the target", async () => { + await runWizardCommand({}, "my-org/my-project", "nextjs"); + + expect(nextjsOptions()).toEqual({ + telemetryEnabled: true, + target: { type: "explicit", org: "my-org", project: "my-project" }, + forceInstall: false, + ignoreGitChanges: false, + spotlight: false, + }); + }); - test("rejects an unknown SENTRY_WIZARD_INTEGRATION", async () => { - vi.stubEnv("SENTRY_WIZARD_INTEGRATION", "cobol"); + test("--force both force-installs and skips the uncommitted changes prompt", async () => { + await runWizardCommand({ force: true }, "nextjs"); - await expect(runWizardCommand()).rejects.toThrow(ValidationError); - expect(runNextjsWizard).not.toHaveBeenCalled(); + expect(nextjsOptions()).toMatchObject({ + forceInstall: true, + ignoreGitChanges: true, + }); }); + test.each([ + ["1", true], + ["true", true], + ["http://localhost:8969/stream", true], + ["0", false], + ["false", false], + ["off", false], + ["", false], + ])("SENTRY_SPOTLIGHT=%j sets Spotlight mode to %s", async (value, on) => { + vi.stubEnv("SENTRY_SPOTLIGHT", value); + + await runWizardCommand({}, "nextjs"); + + expect(nextjsOptions()).toMatchObject({ spotlight: on }); + }); + + test.each([true, false])( + "telemetry follows isTelemetryEnabled() (%s)", + async (enabled) => { + isTelemetryEnabled.mockReturnValue(enabled); + + await runWizardCommand({}, "nextjs"); + + expect(nextjsOptions()).toMatchObject({ telemetryEnabled: enabled }); + }, + ); + test("reports an integration this version can't set up yet", async () => { - await expect(runWizardCommand({ integration: "remix" })).rejects.toThrow( + await expect(runWizardCommand({}, "remix")).rejects.toThrow( "The remix wizard is not available in this version yet.", ); }); @@ -134,7 +251,7 @@ describe("sentry wizard", () => { test("exits with the wizard's code when it stops", async () => { runNextjsWizard.mockRejectedValue(new WizardExitError(0)); - await runWizardCommand({ integration: "nextjs" }); + await runWizardCommand({}, "nextjs"); expect(process.exitCode).toBe(0); }); @@ -142,7 +259,7 @@ describe("sentry wizard", () => { test("exits with code 1 when the wizard can't continue", async () => { runNextjsWizard.mockRejectedValue(new WizardExitError(1)); - await runWizardCommand({ integration: "nextjs" }); + await runWizardCommand({}, "nextjs"); expect(process.exitCode).toBe(1); }); diff --git a/packages/cli/test/lib/wizard/utils/project-data.test.ts b/packages/cli/test/lib/wizard/utils/project-data.test.ts index 152d7adb29..b2baab05be 100644 --- a/packages/cli/test/lib/wizard/utils/project-data.test.ts +++ b/packages/cli/test/lib/wizard/utils/project-data.test.ts @@ -21,6 +21,7 @@ const mocks = vi.hoisted(() => ({ text: vi.fn(), isRequestOriginTrusted: vi.fn(), getApiBaseUrl: vi.fn(), + resolveOrgOptionalTarget: vi.fn(), warn: vi.fn(), })); @@ -73,6 +74,11 @@ vi.mock("../../../../src/lib/api/organizations.js", () => ({ vi.mock("../../../../src/lib/api/org-auth-tokens.js", () => ({ createOrgAuthToken: mocks.createOrgAuthToken, })); +// Target resolution has its own tests; these check what the wizard does +// with the resolved org and project. +vi.mock("../../../../src/lib/resolve-target.js", () => ({ + resolveOrgOptionalTarget: mocks.resolveOrgOptionalTarget, +})); vi.mock("../../../../src/lib/resolve-team.js", () => ({ resolveOrCreateTeam: mocks.resolveOrCreateTeam, })); @@ -87,6 +93,7 @@ vi.mock("../../../../src/lib/api/projects.js", async (importOriginal) => ({ createProjectWithAutoTeam: mocks.createProjectWithAutoTeam, })); +import type { ParsedOrgProject } from "../../../../src/lib/arg-parsing.js"; import { ApiError, WizardExitError } from "../../../../src/lib/errors.js"; import { DUMMY_AUTH_TOKEN, @@ -96,6 +103,11 @@ import type { SentryProjectData } from "../../../../src/lib/wizard/utils/types.j const ORG = { id: "1", slug: "acme", name: "Acme" }; const PROJECT = { id: "42", slug: "web", name: "web", platform: "javascript" }; +const ACME_WEB: ParsedOrgProject = { + type: "explicit", + org: "acme", + project: "web", +}; const KEY = { id: "k1", name: "Default", @@ -117,6 +129,20 @@ beforeEach(async () => { mocks.getProjectKeys.mockResolvedValue([KEY]); mocks.ensureScopesForAction.mockResolvedValue("ready"); mocks.createOrgAuthToken.mockResolvedValue({ token: "sntrys_new" }); + mocks.resolveOrgOptionalTarget.mockImplementation( + (parsed: ParsedOrgProject) => { + switch (parsed.type) { + case "explicit": + return Promise.resolve({ org: parsed.org, project: parsed.project }); + case "org-all": + return Promise.resolve({ org: parsed.org }); + case "project-search": + return Promise.resolve({ org: "acme", project: parsed.projectSlug }); + default: + return Promise.reject(new Error("auto-detect is not resolved")); + } + }, + ); }); describe("getOrAskForProjectData", () => { @@ -153,16 +179,19 @@ describe("getOrAskForProjectData", () => { expect(mocks.listOrganizations).not.toHaveBeenCalled(); }); - it("uses the stored login and the --org and --project slugs", async () => { + it("uses the stored login and the / target", async () => { const result = await getOrAskForProjectData({ telemetryEnabled: false, - saas: true, - orgSlug: "acme", - projectSlug: "web", + target: ACME_WEB, }); expect(mocks.runInteractiveLogin).not.toHaveBeenCalled(); expect(mocks.select).not.toHaveBeenCalled(); + expect(mocks.resolveOrgOptionalTarget).toHaveBeenCalledWith( + ACME_WEB, + process.cwd(), + "wizard", + ); expect(mocks.getProject).toHaveBeenCalledWith("acme", "web"); expect(result).toEqual({ spotlight: false, @@ -178,16 +207,14 @@ describe("getOrAskForProjectData", () => { }); }); - it("asks for the project when the --project slug is not found", async () => { + it("asks for the project when the target's project is not found", async () => { mocks.getProject.mockRejectedValue(new ApiError("Not found", 404)); mocks.listProjects.mockResolvedValue([PROJECT]); mocks.select.mockResolvedValueOnce(PROJECT); const result = await getOrAskForProjectData({ telemetryEnabled: false, - saas: true, - orgSlug: "acme", - projectSlug: "missing", + target: { type: "explicit", org: "acme", project: "missing" }, }); expect(mocks.listProjects).toHaveBeenCalledWith("acme"); @@ -207,7 +234,7 @@ describe("getOrAskForProjectData", () => { }); const result = await getOrAskForProjectData( - { telemetryEnabled: false, saas: true, orgSlug: "acme" }, + { telemetryEnabled: false, target: { type: "org-all", org: "acme" } }, "javascript-nextjs", ); @@ -223,9 +250,7 @@ describe("getOrAskForProjectData", () => { const result = await getOrAskForProjectData({ telemetryEnabled: false, - saas: true, - orgSlug: "acme", - projectSlug: "web", + target: ACME_WEB, }); expect(mocks.createOrgAuthToken).not.toHaveBeenCalled(); @@ -238,9 +263,7 @@ describe("getOrAskForProjectData", () => { await getOrAskForProjectData({ telemetryEnabled: false, - saas: true, - orgSlug: "acme", - projectSlug: "web", + target: ACME_WEB, }); expect(mocks.runInteractiveLogin).toHaveBeenCalledWith({ @@ -253,7 +276,7 @@ describe("getOrAskForProjectData", () => { mocks.runInteractiveLogin.mockResolvedValue(null); await expect( - getOrAskForProjectData({ telemetryEnabled: false, saas: true }), + getOrAskForProjectData({ telemetryEnabled: false }), ).rejects.toThrow(WizardExitError); }); @@ -263,9 +286,7 @@ describe("getOrAskForProjectData", () => { await getOrAskForProjectData({ telemetryEnabled: false, - url: "https://sentry.example.com", - orgSlug: "acme", - projectSlug: "web", + target: ACME_WEB, }); expect(mocks.runInteractiveLogin).toHaveBeenCalled(); @@ -276,8 +297,7 @@ describe("getOrAskForProjectData", () => { const result = await getOrAskForProjectData({ telemetryEnabled: false, - orgSlug: "acme", - projectSlug: "web", + target: ACME_WEB, }); expect(mocks.runInteractiveLogin).not.toHaveBeenCalled(); @@ -293,8 +313,7 @@ describe("getOrAskForProjectData", () => { await getOrAskForProjectData({ telemetryEnabled: false, - orgSlug: "acme", - projectSlug: "web", + target: ACME_WEB, }); expect(mocks.warn).toHaveBeenCalledWith( @@ -307,14 +326,68 @@ describe("getOrAskForProjectData", () => { it("claims an agent handoff and uses its org", async () => { vi.stubEnv("SENTRY_HANDOFF", "handoff-code"); mocks.completeAgentHandoff.mockResolvedValue({ organizationSlug: "acme" }); + mocks.listOrganizations.mockResolvedValue([ + ORG, + { id: "2", slug: "other", name: "Other" }, + ]); + mocks.listProjects.mockResolvedValue([PROJECT]); + mocks.select.mockResolvedValueOnce(PROJECT); - await getOrAskForProjectData({ + await getOrAskForProjectData({ telemetryEnabled: false }); + + expect(mocks.completeAgentHandoff).toHaveBeenCalledWith("handoff-code"); + expect(mocks.select).toHaveBeenCalledTimes(1); + expect(mocks.listProjects).toHaveBeenCalledWith("acme"); + }); + + it("asks for the org and project when no target is given", async () => { + const other = { id: "2", slug: "other", name: "Other" }; + mocks.listOrganizations.mockResolvedValue([ORG, other]); + mocks.listProjects.mockResolvedValue([PROJECT]); + mocks.select.mockResolvedValueOnce(ORG).mockResolvedValueOnce(PROJECT); + + const result = await getOrAskForProjectData({ telemetryEnabled: false, - saas: true, - projectSlug: "web", + target: { type: "auto-detect" }, }); - expect(mocks.completeAgentHandoff).toHaveBeenCalledWith("handoff-code"); + // Nothing is detected from the project's files or the CLI defaults. + expect(mocks.resolveOrgOptionalTarget).not.toHaveBeenCalled(); + expect(mocks.select).toHaveBeenCalledTimes(2); + expect(result).toMatchObject({ selectedProject: { slug: "web" } }); + }); + + it("resolves a bare project slug like other commands' targets", async () => { + const target: ParsedOrgProject = { + type: "project-search", + projectSlug: "web", + }; + + await getOrAskForProjectData({ telemetryEnabled: false, target }); + + expect(mocks.resolveOrgOptionalTarget).toHaveBeenCalledWith( + target, + process.cwd(), + "wizard", + ); + expect(mocks.select).not.toHaveBeenCalled(); expect(mocks.getProject).toHaveBeenCalledWith("acme", "web"); }); + + it("uses the CLI's instance for a preselected project", async () => { + mocks.getApiBaseUrl.mockReturnValue("https://sentry.example.com"); + const project: SentryProjectData = { + id: "7", + slug: "app", + organization: { id: "1", name: "Acme", slug: "acme" }, + keys: [{ dsn: { public: "https://k@sentry.example.com/7" } }], + }; + + const result = await getOrAskForProjectData({ + telemetryEnabled: false, + preSelectedProject: { project, authToken: "tok", selfHosted: true }, + }); + + expect(result).toMatchObject({ sentryUrl: "https://sentry.example.com/" }); + }); }); From 4c93aa845158ef8dff95134aa339c58c31b1af02 Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Thu, 26 Nov 2026 19:23:37 +0000 Subject: [PATCH 10/17] fix(cli): use the credential host for the project issues URL Re-export buildProjectIssuesUrl from lib/sentry-web-urls.ts through withSentryBaseUrl(getApiBaseUrl()), like the other user-facing link builders, so self-hosted and regional logins get links on the host they are authenticated against. Co-Authored-By: BYK <126780+BYK@users.noreply.github.com> --- packages/cli/src/lib/sentry-web-urls.ts | 8 ++++++++ packages/cli/test/lib/sentry-urls.credential.test.ts | 4 ++++ 2 files changed, 12 insertions(+) diff --git a/packages/cli/src/lib/sentry-web-urls.ts b/packages/cli/src/lib/sentry-web-urls.ts index 2207e6a9d1..f4805167f0 100644 --- a/packages/cli/src/lib/sentry-web-urls.ts +++ b/packages/cli/src/lib/sentry-web-urls.ts @@ -11,6 +11,7 @@ import { buildMetricAlertsUrl as buildMetricAlertsUrlPure, buildOrgSettingsUrl as buildOrgSettingsUrlPure, buildOrgUrl as buildOrgUrlPure, + buildProjectIssuesUrl as buildProjectIssuesUrlPure, buildProjectUrl as buildProjectUrlPure, buildReleaseUrl as buildReleaseUrlPure, buildReplayUrl as buildReplayUrlPure, @@ -56,6 +57,13 @@ export function buildEventSearchUrl(orgSlug: string, eventId: string): string { return render(() => buildEventSearchUrlPure(orgSlug, eventId)); } +export function buildProjectIssuesUrl( + orgSlug: string, + projectId: string, +): string { + return render(() => buildProjectIssuesUrlPure(orgSlug, projectId)); +} + export function buildOrgSettingsUrl(orgSlug: string, hash?: string): string { return render(() => buildOrgSettingsUrlPure(orgSlug, hash)); } diff --git a/packages/cli/test/lib/sentry-urls.credential.test.ts b/packages/cli/test/lib/sentry-urls.credential.test.ts index 38e9d87bed..e5000fe361 100644 --- a/packages/cli/test/lib/sentry-urls.credential.test.ts +++ b/packages/cli/test/lib/sentry-urls.credential.test.ts @@ -3,6 +3,7 @@ import { setAuthToken } from "../../src/lib/db/auth.js"; import { resetEnvTokenHostForTesting } from "../../src/lib/env-token-host.js"; import { buildOrgUrl, + buildProjectIssuesUrl, buildProjectUrl, getSentryBaseUrl, isSaaS, @@ -40,6 +41,9 @@ describe("web URLs for active credential hosts", () => { expect(buildProjectUrl("acme", "site")).toBe( "https://sentry.example.com/settings/acme/projects/site/", ); + expect(buildProjectIssuesUrl("acme", "42")).toBe( + "https://sentry.example.com/organizations/acme/issues/?project=42", + ); }); test("stored OAuth host wins over an inactive environment token", () => { From 2f2f91a2303211c1c149d250b86a1f076cfbdeba 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:40:46 +0000 Subject: [PATCH 11/17] =?UTF-8?q?fix(mcp):=20regenerate=20the=20chart=20ap?= =?UTF-8?q?p=20after=20the=20for=E2=80=A6of=20conversion?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: BYK <126780+BYK@users.noreply.github.com> --- packages/mcp-core/src/server.ui-resources.test.ts | 2 +- packages/mcp-core/src/ui-resources.ts | 4 ++-- packages/mcp-core/src/ui/chart-app.generated.ts | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/packages/mcp-core/src/server.ui-resources.test.ts b/packages/mcp-core/src/server.ui-resources.test.ts index bd31394ab0..b17369868f 100644 --- a/packages/mcp-core/src/server.ui-resources.test.ts +++ b/packages/mcp-core/src/server.ui-resources.test.ts @@ -15,7 +15,7 @@ vi.mock("@sentry/core/server", () => ({ wrapMcpServerWithSentry: vi.fn((server) => server), })); -const CHART_URI = "ui://sentry/chart/v5.html"; +const CHART_URI = "ui://sentry/chart/v6.html"; const MCP_APP_MIME_TYPE = "text/html;profile=mcp-app"; async function connect(skills: Skill[]) { diff --git a/packages/mcp-core/src/ui-resources.ts b/packages/mcp-core/src/ui-resources.ts index 4c19d2787a..590c9101ec 100644 --- a/packages/mcp-core/src/ui-resources.ts +++ b/packages/mcp-core/src/ui-resources.ts @@ -57,13 +57,13 @@ export interface UiResource { * chart-app/ by generate-chart-app. */ export const CHART_UI_RESOURCE: UiResource = { - uri: "ui://sentry/chart/v5.html", + uri: "ui://sentry/chart/v6.html", name: "sentry_chart", title: "Sentry Chart", description: "Interactive time series chart for render_sentry_chart and render_issue_chart results, with a range picker, fullscreen, and a link to Sentry.", htmlSha256: - "7957519bcbf3a3855250904467784362573af55eb36cc11bac53d0625c2d2d22", + "079fa3cb185c5fdf7ad4e5983657af34093d2a477963d10be7c6da909aeaeaf5", // About 1.5x the current view, so a new dependency cannot slip in. budgetBytes: 24 * 1024, loadHtml: async () => diff --git a/packages/mcp-core/src/ui/chart-app.generated.ts b/packages/mcp-core/src/ui/chart-app.generated.ts index ed6b4b9e2b..f1a79316dd 100644 --- a/packages/mcp-core/src/ui/chart-app.generated.ts +++ b/packages/mcp-core/src/ui/chart-app.generated.ts @@ -1,2 +1,2 @@ // Generated by scripts/generate-chart-app.ts from chart-app/. Do not edit. -export const CHART_APP_HTML = "Sentry chart"; +export const CHART_APP_HTML = "Sentry chart"; From f0ece5cac79c8b2ae21961f89c2c1af8445330f8 Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Fri, 27 Nov 2026 17:08:11 +0000 Subject: [PATCH 12/17] fix(cli): fix review findings in the SvelteKit, Remix and React Router wizards Fixes carried over from sentry-wizard that keep its intended behaviour: - React Router: Ctrl+C at the `react-router reveal` prompt stops the wizard instead of running reveal. - React Router: `--force` reaches both SDK installs. - React Router: an existing react-router.config with the other extension is updated instead of shadowed by a new file. - React Router: `export default [...] as RouteConfig` gets the example routes, and an unsupported routes export now shows the manual steps. - React Router: the example routes are registered in `app/routes.js` too. - React Router: the package.json fallback snippet shows the real `react-router-serve` start script as the line to replace. - Remix: an unknown installed SDK version falls back to the `^11` the wizard installs, so the data collection prompt is offered. - SvelteKit: a failed vite.config edit no longer reports success. - SvelteKit: `kit.experimental.(tracing|instrumentation)` objects with `server: false` or no `server` key are rewritten instead of skipped, and the fallback snippet keeps server tracing off when it was declined. --- .../codemods/react-router-config.ts | 8 +- .../react-router/codemods/routes-config.ts | 30 ++-- .../react-router/react-router-wizard.ts | 20 +-- .../lib/wizard/react-router/sdk-example.ts | 10 +- .../src/lib/wizard/react-router/sdk-setup.ts | 16 +- .../src/lib/wizard/react-router/templates.ts | 18 +++ .../cli/src/lib/wizard/remix/remix-wizard.ts | 2 +- .../sveltekit/sdk-setup/svelte-config.ts | 29 ++-- .../lib/wizard/sveltekit/sdk-setup/vite.ts | 1 + .../codemods/react-router-config.test.ts | 23 +++ .../react-router/react-router-wizard.test.ts | 69 +++++++++ .../wizard/react-router/routes-config.test.ts | 32 ++++ .../wizard/react-router/sdk-example.test.ts | 59 ++++++++ .../lib/wizard/react-router/sdk-setup.test.ts | 25 +++ .../lib/wizard/react-router/templates.test.ts | 16 ++ .../lib/wizard/remix/remix-wizard.test.ts | 77 ++++++++++ .../sdk-setup/enable-tracing.test.ts | 142 ++++++++++++++++++ .../wizard/sveltekit/sdk-setup/vite.test.ts | 18 +++ 18 files changed, 540 insertions(+), 55 deletions(-) create mode 100644 packages/cli/test/lib/wizard/react-router/react-router-wizard.test.ts create mode 100644 packages/cli/test/lib/wizard/react-router/sdk-example.test.ts create mode 100644 packages/cli/test/lib/wizard/remix/remix-wizard.test.ts create mode 100644 packages/cli/test/lib/wizard/sveltekit/sdk-setup/enable-tracing.test.ts diff --git a/packages/cli/src/lib/wizard/react-router/codemods/react-router-config.ts b/packages/cli/src/lib/wizard/react-router/codemods/react-router-config.ts index 93726591f1..ae127572a3 100644 --- a/packages/cli/src/lib/wizard/react-router/codemods/react-router-config.ts +++ b/packages/cli/src/lib/wizard/react-router/codemods/react-router-config.ts @@ -165,7 +165,13 @@ export async function instrumentReactRouterConfig( undefined, ), ): Promise<{ ssrWasChanged: boolean }> { - const configFilename = `react-router.config.${isTS ? "ts" : "js"}`; + // Prefer an existing config with either extension, so a `.js` config in a + // TypeScript project is updated instead of shadowed by a new `.ts` file. + const preferredFilename = `react-router.config.${isTS ? "ts" : "js"}`; + const configFilename = + [preferredFilename, `react-router.config.${isTS ? "js" : "ts"}`].find( + (candidate) => existsSync(path.join(process.cwd(), candidate)), + ) ?? preferredFilename; const configPath = path.join(process.cwd(), configFilename); if (!existsSync(configPath)) { diff --git a/packages/cli/src/lib/wizard/react-router/codemods/routes-config.ts b/packages/cli/src/lib/wizard/react-router/codemods/routes-config.ts index 316ed0e95c..b0deee5a66 100644 --- a/packages/cli/src/lib/wizard/react-router/codemods/routes-config.ts +++ b/packages/cli/src/lib/wizard/react-router/codemods/routes-config.ts @@ -70,23 +70,31 @@ export async function addRoutesToConfig( if (declaration.type === "ArrayExpression") { arrayExpression = declaration; - } else if (declaration.type === "TSSatisfiesExpression") { - // Handle TypeScript satisfies expression like: [...] satisfies RouteConfig + } else if ( + declaration.type === "TSSatisfiesExpression" || + declaration.type === "TSAsExpression" + ) { + // Handle `[...] satisfies RouteConfig` and `[...] as RouteConfig` if (declaration.expression.type === "ArrayExpression") { arrayExpression = declaration.expression; } } - if (arrayExpression) { - // Parse and add the new route calls directly to the elements array - const pageRouteCall = - recast.parse(pageRouteCode).program.body[0].expression; - const apiRouteCall = - recast.parse(apiRouteCode).program.body[0].expression; - - arrayExpression.elements.push(pageRouteCall); - arrayExpression.elements.push(apiRouteCall); + if (!arrayExpression) { + // The caller turns this into manual instructions for the user. + throw new Error( + "The default export of the routes config is not an array literal", + ); } + + // Parse and add the new route calls directly to the elements array + const pageRouteCall = + recast.parse(pageRouteCode).program.body[0].expression; + const apiRouteCall = + recast.parse(apiRouteCode).program.body[0].expression; + + arrayExpression.elements.push(pageRouteCall); + arrayExpression.elements.push(apiRouteCall); break; } } diff --git a/packages/cli/src/lib/wizard/react-router/react-router-wizard.ts b/packages/cli/src/lib/wizard/react-router/react-router-wizard.ts index e699611e6f..01c50d920c 100644 --- a/packages/cli/src/lib/wizard/react-router/react-router-wizard.ts +++ b/packages/cli/src/lib/wizard/react-router/react-router-wizard.ts @@ -22,7 +22,6 @@ import { printSdkV11MigrationGuideIfOutdated, addDotEnvSentryBuildPluginFile, showCopyPasteInstructions, - makeCodeSnippet, runPrettierIfInstalled, } from "../utils/clack/index.js"; import { offerProjectScopedMcpConfig } from "../utils/clack/mcp-config.js"; @@ -56,6 +55,7 @@ import { getManualServerInstrumentContent, getManualReactRouterConfigContent, getManualViteConfigContent, + getManualPackageJsonScriptsContent, } from "./templates.js"; import { abortIfSpotlightNotSupported } from "../utils/abort-if-sportlight-not-supported.js"; import { @@ -124,6 +124,7 @@ async function runReactRouterWizardWithTelemetry( packageName: `@sentry/react-router@${SENTRY_REACT_ROUTER_SDK_RANGE}`, packageNameDisplayLabel: "@sentry/react-router", alreadyInstalled: sentryAlreadyInstalled, + forceInstall: options.forceInstall, }); // The install may have been skipped (user declined the update prompt), so @@ -203,6 +204,7 @@ The wizard will continue, but you may need to upgrade React Router before moving packageName: `@sentry/profiling-node@${SENTRY_REACT_ROUTER_SDK_RANGE}`, packageNameDisplayLabel: "@sentry/profiling-node", alreadyInstalled: profilingAlreadyInstalled, + forceInstall: options.forceInstall, }); } @@ -371,21 +373,7 @@ Please create your entry files manually using React Router v7 commands.`); await showCopyPasteInstructions({ filename: "package.json", - codeSnippet: makeCodeSnippet(true, (unchanged, plus, minus) => { - return unchanged(`{ - scripts: { - ${minus('"start": "react-router dev"')} - ${plus( - '"start": "NODE_ENV=production NODE_OPTIONS=\'--import ./instrument.server.mjs\' react-router-serve ./build/server/index.js"', - )} - ${minus('"dev": "react-router dev"')} - ${plus( - '"dev": "NODE_OPTIONS=\'--import ./instrument.server.mjs\' react-router dev"', - )} - }, - // ... rest of your package.json - }`); - }), + codeSnippet: getManualPackageJsonScriptsContent(), }); debug(e); diff --git a/packages/cli/src/lib/wizard/react-router/sdk-example.ts b/packages/cli/src/lib/wizard/react-router/sdk-example.ts index b06c3b3a4b..3a0275425a 100644 --- a/packages/cli/src/lib/wizard/react-router/sdk-example.ts +++ b/packages/cli/src/lib/wizard/react-router/sdk-example.ts @@ -70,14 +70,16 @@ export async function createExamplePage(options: { clack.log.info(`Created ${chalk.cyan(apiRouteRelative)}.`); } - // Check if there's a routes.ts configuration file and add the route using codemod - const routesConfigPath = path.join(options.projectDir, "app", "routes.ts"); - if (existsSync(routesConfigPath)) { + // Check if there's a routes.(ts|js) configuration file and add the route using codemod + const routesConfigPath = ["routes.ts", "routes.js"] + .map((filename) => path.join(options.projectDir, "app", filename)) + .find((candidate) => existsSync(candidate)); + if (routesConfigPath) { try { await addRoutesToConfig(routesConfigPath, options.isTS); } catch (e) { clack.log.warn( - `Could not update routes.ts configuration: ${ + `Could not update ${path.basename(routesConfigPath)} configuration: ${ e instanceof Error ? e.message : String(e) }`, ); diff --git a/packages/cli/src/lib/wizard/react-router/sdk-setup.ts b/packages/cli/src/lib/wizard/react-router/sdk-setup.ts index 75bb3c7380..722ac8de9c 100644 --- a/packages/cli/src/lib/wizard/react-router/sdk-setup.ts +++ b/packages/cli/src/lib/wizard/react-router/sdk-setup.ts @@ -17,7 +17,7 @@ import { getPackageVersion } from "../utils/package-json.js"; import { debug } from "../utils/debug.js"; import { getSentryInstrumentationServerContent } from "./templates.js"; import { instrumentServerEntry } from "./codemods/server-entry.js"; -import { getPackageDotJson } from "../utils/clack/index.js"; +import { abortIfCancelled, getPackageDotJson } from "../utils/clack/index.js"; import { instrumentClientEntry } from "./codemods/client.entry.js"; import { instrumentViteConfig } from "./codemods/vite.js"; import { instrumentReactRouterConfig } from "./codemods/react-router-config.js"; @@ -62,12 +62,14 @@ export async function tryRevealAndGetManualInstructions( missingFilename: string, filePath: string, ): Promise { - const shouldTryReveal = await clack.confirm({ - message: `Would you like to try running ${chalk.cyan( - REACT_ROUTER_REVEAL_COMMAND, - )} to generate entry files?`, - initialValue: true, - }); + const shouldTryReveal = await abortIfCancelled( + clack.confirm({ + message: `Would you like to try running ${chalk.cyan( + REACT_ROUTER_REVEAL_COMMAND, + )} to generate entry files?`, + initialValue: true, + }), + ); if (shouldTryReveal) { try { diff --git a/packages/cli/src/lib/wizard/react-router/templates.ts b/packages/cli/src/lib/wizard/react-router/templates.ts index 2f7b87481b..19e146da34 100644 --- a/packages/cli/src/lib/wizard/react-router/templates.ts +++ b/packages/cli/src/lib/wizard/react-router/templates.ts @@ -378,3 +378,21 @@ export default defineConfig(config => { });`), ); }; + +/** The `package.json` scripts change, shown when the automatic edit fails. */ +export const getManualPackageJsonScriptsContent = () => + makeCodeSnippet(true, (unchanged, plus, minus) => + unchanged(`{ + scripts: { + ${minus('"start": "react-router-serve ./build/server/index.js"')} + ${plus( + '"start": "NODE_ENV=production NODE_OPTIONS=\'--import ./instrument.server.mjs\' react-router-serve ./build/server/index.js"', + )} + ${minus('"dev": "react-router dev"')} + ${plus( + '"dev": "NODE_OPTIONS=\'--import ./instrument.server.mjs\' react-router dev"', + )} + }, + // ... rest of your package.json +}`), + ); diff --git a/packages/cli/src/lib/wizard/remix/remix-wizard.ts b/packages/cli/src/lib/wizard/remix/remix-wizard.ts index 364b344ed7..b64b7e5e9d 100644 --- a/packages/cli/src/lib/wizard/remix/remix-wizard.ts +++ b/packages/cli/src/lib/wizard/remix/remix-wizard.ts @@ -120,7 +120,7 @@ async function runRemixWizardWithTelemetry( // From v11 on, the SDK collects rich context by default, so offer to // reduce collection of data that can identify users. const reduceDataCollection = - sdkSupportsDataCollection(installedSdkVersion, "^10") && + sdkSupportsDataCollection(installedSdkVersion, "^11") && (await askShouldReduceDataCollection()); const dsn = selectedProject.keys[0].dsn.public; diff --git a/packages/cli/src/lib/wizard/sveltekit/sdk-setup/svelte-config.ts b/packages/cli/src/lib/wizard/sveltekit/sdk-setup/svelte-config.ts index 46437b7319..c0069d37b3 100644 --- a/packages/cli/src/lib/wizard/sveltekit/sdk-setup/svelte-config.ts +++ b/packages/cli/src/lib/wizard/sveltekit/sdk-setup/svelte-config.ts @@ -71,29 +71,26 @@ export async function enableTracingAndInstrumentation( originalSvelteConfig: PartialBackwardsForwardsCompatibleSvelteConfig, enableTracing: boolean, ) { - const hasTracingEnabled = originalSvelteConfig.kit?.experimental?.tracing; + const experimental = originalSvelteConfig.kit?.experimental; + const hasTracingEnabled = experimental?.tracing?.server === true; const hasInstrumentationEnabled = - originalSvelteConfig.kit?.experimental?.instrumentation; + experimental?.instrumentation?.server === true; - if (hasTracingEnabled && hasInstrumentationEnabled) { + if (hasInstrumentationEnabled && (hasTracingEnabled || !enableTracing)) { clack.log.info("Tracing and instrumentation are already enabled."); return; } - if (hasTracingEnabled || hasInstrumentationEnabled) { - clack.log.info( - "Tracing and instrumentation are partially enabled. Make sure both options are enabled.", - ); - await showFallbackConfigSnippet(); - return; - } + // Never turn off server tracing that the project already enabled. + const tracingServer = enableTracing || hasTracingEnabled; + try { const configPath = path.join(process.cwd(), SVELTE_CONFIG_FILE); const svelteConfigContent = await promises.readFile(configPath, "utf-8"); const { error, result } = _enableTracingAndInstrumentationInConfig( svelteConfigContent, - enableTracing, + tracingServer, ); if (error) { @@ -102,7 +99,7 @@ export async function enableTracingAndInstrumentation( ); debug(error); reportCliError(error); - await showFallbackConfigSnippet(); + await showFallbackConfigSnippet(tracingServer); return; } @@ -127,7 +124,7 @@ export async function enableTracingAndInstrumentation( `Failed to enable tracing and instrumentation in ${SVELTE_CONFIG_FILE}`, ), ); - await showFallbackConfigSnippet(); + await showFallbackConfigSnippet(tracingServer); return; } } @@ -370,7 +367,9 @@ function _isValidConfigObject( return !!o; } -async function showFallbackConfigSnippet(): Promise { +async function showFallbackConfigSnippet( + tracingServer: boolean, +): Promise { const codeSnippet = makeCodeSnippet(true, (unchanged, plus) => unchanged(`const config = { preprocess: vitePreprocess(), @@ -382,7 +381,7 @@ kit: { server: true, }, tracing: { - server: true, + server: ${tracingServer}, }, },`)} }, diff --git a/packages/cli/src/lib/wizard/sveltekit/sdk-setup/vite.ts b/packages/cli/src/lib/wizard/sveltekit/sdk-setup/vite.ts index 9fd5924f11..d3625f3aee 100644 --- a/packages/cli/src/lib/wizard/sveltekit/sdk-setup/vite.ts +++ b/packages/cli/src/lib/wizard/sveltekit/sdk-setup/vite.ts @@ -89,6 +89,7 @@ Skipping adding Sentry functionality to.`, ), ); reportCliError(new Error("Sveltekit Vite Config Modification Fail")); + return; } clack.log.success(`Added Sentry code to ${prettyViteConfigFilename}`); diff --git a/packages/cli/test/lib/wizard/react-router/codemods/react-router-config.test.ts b/packages/cli/test/lib/wizard/react-router/codemods/react-router-config.test.ts index 7f1356a72a..073bfec3ed 100644 --- a/packages/cli/test/lib/wizard/react-router/codemods/react-router-config.test.ts +++ b/packages/cli/test/lib/wizard/react-router/codemods/react-router-config.test.ts @@ -134,6 +134,29 @@ export default { expect(result.ssrWasChanged).toBe(false); }); + it("updates an existing react-router.config.js in a TypeScript project", async () => { + const writtenFiles: Record = {}; + vi.mocked(existsSync).mockImplementation( + (filePath) => filePath === path.join(mockCwd, "react-router.config.js"), + ); + vi.mocked(promises.readFile).mockResolvedValue( + "export default {\n ssr: true,\n};\n", + ); + vi.mocked(promises.writeFile).mockImplementation((filePath, content) => { + writtenFiles[filePath as string] = content as string; + return Promise.resolve(); + }); + + await instrumentReactRouterConfig(true); + + expect(Object.keys(writtenFiles)).toEqual([ + path.join(mockCwd, "react-router.config.js"), + ]); + expect( + writtenFiles[path.join(mockCwd, "react-router.config.js")], + ).toContain("sentryOnBuildEnd"); + }); + it("should add buildEnd hook to existing config", async () => { const existingConfig = `export default { ssr: true, diff --git a/packages/cli/test/lib/wizard/react-router/react-router-wizard.test.ts b/packages/cli/test/lib/wizard/react-router/react-router-wizard.test.ts new file mode 100644 index 0000000000..914147a250 --- /dev/null +++ b/packages/cli/test/lib/wizard/react-router/react-router-wizard.test.ts @@ -0,0 +1,69 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; + +const { installPackageMock } = vi.hoisted(() => ({ + installPackageMock: vi.fn(), +})); + +vi.mock("../../../../src/lib/wizard/telemetry.js", () => ({ + Sentry: { setTag: vi.fn() }, + withTelemetry: (_options: unknown, callback: () => unknown) => callback(), + traceStep: (_name: string, callback: () => unknown) => callback(), +})); + +vi.mock("../../../../src/lib/wizard/utils/clack/index.js", () => ({ + printWelcome: vi.fn(), + getPackageDotJson: vi.fn(() => + Promise.resolve({ devDependencies: { "@react-router/dev": "^7.0.0" } }), + ), + isUsingTypeScript: vi.fn(() => true), + confirmContinueIfNoOrDirtyGitRepo: vi.fn(() => Promise.resolve()), + getOrAskForProjectData: vi.fn(() => + Promise.resolve({ + spotlight: false, + selfHosted: false, + sentryUrl: "https://sentry.io/", + authToken: "token", + selectedProject: { + id: "1", + slug: "project", + organization: { id: "1", slug: "org", name: "Org" }, + keys: [{ dsn: { public: "https://key@sentry.io/1" } }], + }, + }), + ), + printSdkV11MigrationGuideIfOutdated: vi.fn(), + installPackage: installPackageMock, +})); + +vi.mock("../../../../src/lib/wizard/utils/node-version.js", () => ({ + warnIfNodeVersionUnsupportedBySdkV11: vi.fn(), +})); + +import { runReactRouterWizard } from "../../../../src/lib/wizard/react-router/react-router-wizard.js"; + +describe("runReactRouterWizard", () => { + beforeEach(() => { + vi.clearAllMocks(); + // Stop the wizard right after the SDK install; only its options matter. + installPackageMock.mockRejectedValue(new Error("stop after install")); + }); + + it.each([true, false])( + "passes forceInstall=%s to the SDK install", + async (forceInstall) => { + await expect( + runReactRouterWizard({ + telemetryEnabled: false, + forceInstall, + }), + ).rejects.toThrow("stop after install"); + + expect(installPackageMock).toHaveBeenCalledWith( + expect.objectContaining({ + packageNameDisplayLabel: "@sentry/react-router", + forceInstall, + }), + ); + }, + ); +}); diff --git a/packages/cli/test/lib/wizard/react-router/routes-config.test.ts b/packages/cli/test/lib/wizard/react-router/routes-config.test.ts index 1b9c0839f3..57781f6b5a 100644 --- a/packages/cli/test/lib/wizard/react-router/routes-config.test.ts +++ b/packages/cli/test/lib/wizard/react-router/routes-config.test.ts @@ -74,6 +74,38 @@ export default [ ); }); + it("should add routes when the default export uses `as RouteConfig`", async () => { + writeFileSync( + routesConfigPath, + `import type { RouteConfig } from "@react-router/dev/routes"; +import { index, route } from "@react-router/dev/routes"; + +export default [index("routes/home.tsx")] as RouteConfig;`, + ); + + await addRoutesToConfig(routesConfigPath, true); + + const updatedContent = readFileSync(routesConfigPath, "utf-8"); + expect(updatedContent).toContain( + 'route("/sentry-example-page", "routes/sentry-example-page.tsx")', + ); + expect(updatedContent).toContain( + 'route("/api/sentry-example-api", "routes/api.sentry-example-api.ts")', + ); + }); + + it("should throw when the default export is not an array literal", async () => { + const routesContent = `import { flatRoutes } from "@react-router/fs-routes"; + +export default flatRoutes();`; + writeFileSync(routesConfigPath, routesContent); + + await expect(addRoutesToConfig(routesConfigPath, true)).rejects.toThrow( + "not an array literal", + ); + expect(readFileSync(routesConfigPath, "utf-8")).toBe(routesContent); + }); + it("should handle JavaScript projects correctly", async () => { // Create a routes.ts file const routesContent = `import type { RouteConfig } from "@react-router/dev/routes"; diff --git a/packages/cli/test/lib/wizard/react-router/sdk-example.test.ts b/packages/cli/test/lib/wizard/react-router/sdk-example.test.ts new file mode 100644 index 0000000000..9fced90fcb --- /dev/null +++ b/packages/cli/test/lib/wizard/react-router/sdk-example.test.ts @@ -0,0 +1,59 @@ +import { + mkdirSync, + mkdtempSync, + readFileSync, + rmSync, + writeFileSync, +} from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; + +vi.mock("@clack/prompts", () => ({ + log: { info: vi.fn(), warn: vi.fn(), success: vi.fn() }, +})); + +import { createExamplePage } from "../../../../src/lib/wizard/react-router/sdk-example.js"; + +describe("createExamplePage", () => { + let tmpDir: string; + + beforeEach(() => { + tmpDir = mkdtempSync(path.join(tmpdir(), "react-router-example-test-")); + mkdirSync(path.join(tmpDir, "app"), { recursive: true }); + vi.spyOn(process, "cwd").mockReturnValue(tmpDir); + }); + + afterEach(() => { + vi.restoreAllMocks(); + rmSync(tmpDir, { recursive: true, force: true }); + }); + + it("registers the example routes in a JavaScript app/routes.js", async () => { + const routesConfigPath = path.join(tmpDir, "app", "routes.js"); + writeFileSync( + routesConfigPath, + `import { index } from "@react-router/dev/routes"; + +export default [index("routes/home.jsx")]; +`, + ); + + await createExamplePage({ + selfHosted: false, + orgSlug: "org", + projectId: "1", + url: "https://sentry.io/", + isTS: false, + projectDir: tmpDir, + }); + + const updated = readFileSync(routesConfigPath, "utf-8"); + expect(updated).toContain( + 'route("/sentry-example-page", "routes/sentry-example-page.jsx")', + ); + expect(updated).toContain( + 'route("/api/sentry-example-api", "routes/api.sentry-example-api.js")', + ); + }); +}); diff --git a/packages/cli/test/lib/wizard/react-router/sdk-setup.test.ts b/packages/cli/test/lib/wizard/react-router/sdk-setup.test.ts index fca0dffc39..742b6368e6 100644 --- a/packages/cli/test/lib/wizard/react-router/sdk-setup.test.ts +++ b/packages/cli/test/lib/wizard/react-router/sdk-setup.test.ts @@ -94,6 +94,16 @@ vi.mock("../../../../src/lib/wizard/utils/clack/index.js", () => { }, ), getPackageDotJson: getPackageDotJsonMock, + // Same contract as the real helper: a cancelled prompt stops the wizard. + abortIfCancelled: vi.fn(async (input: unknown) => { + const value = await input; + if (typeof value === "symbol") { + const { WizardExitError } = + await import("../../../../src/lib/errors.js"); + throw new WizardExitError(0); + } + return value; + }), }; }); @@ -109,6 +119,7 @@ import { } from "../../../../src/lib/wizard/react-router/sdk-setup.js"; import { execSync } from "node:child_process"; import type { Mock } from "vitest"; +import { WizardExitError } from "../../../../src/lib/errors.js"; import { getSentryInstrumentationServerContent } from "../../../../src/lib/wizard/react-router/templates.js"; describe("React Router SDK Setup", () => { @@ -452,6 +463,20 @@ describe("tryRevealAndGetManualInstructions", () => { ); }); + it("stops the wizard without running reveal when the prompt is cancelled", async () => { + clackMocks.confirm.mockResolvedValueOnce( + Symbol("clack:cancel") as unknown as boolean, + ); + + await expect( + tryRevealAndGetManualInstructions( + "entry.client.tsx", + "/app/entry.client.tsx", + ), + ).rejects.toThrow(WizardExitError); + expect(execSync).not.toHaveBeenCalled(); + }); + it("should return false when user declines reveal operation", async () => { const missingFilename = "entry.server.tsx"; const filePath = "/app/entry.server.tsx"; diff --git a/packages/cli/test/lib/wizard/react-router/templates.test.ts b/packages/cli/test/lib/wizard/react-router/templates.test.ts index 7faab3977e..36a525ef97 100644 --- a/packages/cli/test/lib/wizard/react-router/templates.test.ts +++ b/packages/cli/test/lib/wizard/react-router/templates.test.ts @@ -31,6 +31,7 @@ import { getManualServerInstrumentContent, getManualReactRouterConfigContent, getManualViteConfigContent, + getManualPackageJsonScriptsContent, } from "../../../../src/lib/wizard/react-router/templates.js"; describe("React Router Templates", () => { @@ -470,4 +471,19 @@ describe("React Router Templates", () => { expect(result).toContain("exclude: ['@sentry/react-router']"); }); }); + + describe("getManualPackageJsonScriptsContent", () => { + it("replaces the serve start script and the dev script", () => { + const result = getManualPackageJsonScriptsContent(); + + expect(result).toContain( + '- "start": "react-router-serve ./build/server/index.js"', + ); + expect(result).not.toContain('"start": "react-router dev"'); + expect(result).toContain('- "dev": "react-router dev"'); + expect(result).toContain( + '+ "dev": "NODE_OPTIONS=\'--import ./instrument.server.mjs\' react-router dev"', + ); + }); + }); }); diff --git a/packages/cli/test/lib/wizard/remix/remix-wizard.test.ts b/packages/cli/test/lib/wizard/remix/remix-wizard.test.ts new file mode 100644 index 0000000000..7c9f9619a1 --- /dev/null +++ b/packages/cli/test/lib/wizard/remix/remix-wizard.test.ts @@ -0,0 +1,77 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; + +const { askShouldReduceDataCollectionMock, getPackageDotJsonMock } = vi.hoisted( + () => ({ + askShouldReduceDataCollectionMock: vi.fn(), + getPackageDotJsonMock: vi.fn(), + }), +); + +vi.mock("../../../../src/lib/wizard/telemetry.js", () => ({ + Sentry: { setTag: vi.fn() }, + withTelemetry: (_options: unknown, callback: () => unknown) => callback(), + traceStep: (_name: string, callback: () => unknown) => callback(), +})); + +vi.mock("../../../../src/lib/wizard/utils/clack/index.js", () => ({ + printWelcome: vi.fn(), + getPackageDotJson: getPackageDotJsonMock, + confirmContinueIfNoOrDirtyGitRepo: vi.fn(() => Promise.resolve()), + ensurePackageIsInstalled: vi.fn(() => Promise.resolve()), + getOrAskForProjectData: vi.fn(() => + Promise.resolve({ + spotlight: false, + selfHosted: false, + sentryUrl: "https://sentry.io/", + authToken: "token", + selectedProject: { + id: "1", + slug: "project", + organization: { id: "1", slug: "org", name: "Org" }, + keys: [{ dsn: { public: "https://key@sentry.io/1" } }], + }, + }), + ), + printSdkV11MigrationGuideIfOutdated: vi.fn(), + installPackage: vi.fn(() => Promise.resolve()), +})); + +vi.mock("../../../../src/lib/wizard/utils/data-collection.js", async () => ({ + ...(await vi.importActual< + typeof import("../../../../src/lib/wizard/utils/data-collection.js") + >("../../../../src/lib/wizard/utils/data-collection.js")), + askShouldReduceDataCollection: askShouldReduceDataCollectionMock, +})); + +vi.mock("../../../../src/lib/wizard/utils/node-version.js", () => ({ + warnIfNodeVersionUnsupportedBySdkV11: vi.fn(), +})); + +import { runRemixWizard } from "../../../../src/lib/wizard/remix/remix-wizard.js"; + +describe("runRemixWizard", () => { + beforeEach(() => { + vi.clearAllMocks(); + // Stop the wizard at the data collection prompt; only reaching it matters. + askShouldReduceDataCollectionMock.mockRejectedValue( + new Error("stop at data collection"), + ); + }); + + it.each([undefined, "workspace:*"])( + "offers to reduce data collection when the installed SDK version is %s", + async (installedVersion) => { + getPackageDotJsonMock.mockResolvedValue({ + dependencies: { + "@remix-run/react": "^2.0.0", + ...(installedVersion && { "@sentry/remix": installedVersion }), + }, + }); + + await expect(runRemixWizard({ telemetryEnabled: false })).rejects.toThrow( + "stop at data collection", + ); + expect(askShouldReduceDataCollectionMock).toHaveBeenCalledTimes(1); + }, + ); +}); diff --git a/packages/cli/test/lib/wizard/sveltekit/sdk-setup/enable-tracing.test.ts b/packages/cli/test/lib/wizard/sveltekit/sdk-setup/enable-tracing.test.ts new file mode 100644 index 0000000000..72b7533f5a --- /dev/null +++ b/packages/cli/test/lib/wizard/sveltekit/sdk-setup/enable-tracing.test.ts @@ -0,0 +1,142 @@ +import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; + +const { showCopyPasteInstructionsMock } = vi.hoisted(() => ({ + showCopyPasteInstructionsMock: vi.fn( + (_options: { filename: string; codeSnippet: string }) => Promise.resolve(), + ), +})); + +vi.mock("@clack/prompts", () => ({ + log: { + info: vi.fn(), + warning: vi.fn(), + warn: vi.fn(), + error: vi.fn(), + success: vi.fn(), + }, +})); + +vi.mock("../../../../../src/lib/error-reporting.js", () => ({ + reportCliError: vi.fn(), +})); + +vi.mock("../../../../../src/lib/wizard/utils/clack/index.js", () => ({ + showCopyPasteInstructions: showCopyPasteInstructionsMock, + makeCodeSnippet: ( + _colors: boolean, + callback: ( + unchanged: (str: string) => string, + plus: (str: string) => string, + ) => string, + ) => + callback( + (str) => str, + (str) => str, + ), +})); + +import { enableTracingAndInstrumentation } from "../../../../../src/lib/wizard/sveltekit/sdk-setup/svelte-config.js"; + +const configWith = (experimental: string) => `const config = { + kit: { + experimental: ${experimental}, + }, +}; + +export default config; +`; + +describe("enableTracingAndInstrumentation", () => { + let tmpDir: string; + let configPath: string; + + beforeEach(() => { + vi.clearAllMocks(); + tmpDir = mkdtempSync(path.join(tmpdir(), "sveltekit-config-test-")); + configPath = path.join(tmpDir, "svelte.config.js"); + vi.spyOn(process, "cwd").mockReturnValue(tmpDir); + }); + + afterEach(() => { + vi.restoreAllMocks(); + rmSync(tmpDir, { recursive: true, force: true }); + }); + + it("turns on server options that are present but disabled", async () => { + writeFileSync( + configPath, + configWith( + "{ tracing: { server: false }, instrumentation: { server: true } }", + ), + ); + + await enableTracingAndInstrumentation( + { + kit: { + experimental: { + tracing: { server: false }, + instrumentation: { server: true }, + }, + }, + }, + true, + ); + + const result = readFileSync(configPath, "utf-8"); + expect(result).toMatch(/tracing: \{\s*server: true/); + expect(result).toMatch(/instrumentation: \{\s*server: true/); + expect(showCopyPasteInstructionsMock).not.toHaveBeenCalled(); + }); + + it("fills empty experimental objects", async () => { + writeFileSync( + configPath, + configWith("{ tracing: {}, instrumentation: {} }"), + ); + + await enableTracingAndInstrumentation( + { kit: { experimental: { tracing: {}, instrumentation: {} } } }, + true, + ); + + const result = readFileSync(configPath, "utf-8"); + expect(result).toMatch(/tracing: \{\s*server: true/); + expect(result).toMatch(/instrumentation: \{\s*server: true/); + }); + + it("leaves a fully enabled config untouched", async () => { + const content = configWith( + "{ tracing: { server: true }, instrumentation: { server: true } }", + ); + writeFileSync(configPath, content); + + await enableTracingAndInstrumentation( + { + kit: { + experimental: { + tracing: { server: true }, + instrumentation: { server: true }, + }, + }, + }, + true, + ); + + expect(readFileSync(configPath, "utf-8")).toBe(content); + }); + + it("keeps server tracing off in the fallback snippet when tracing was declined", async () => { + writeFileSync(configPath, "export default {{{ not js"); + + await enableTracingAndInstrumentation({}, false); + + expect(showCopyPasteInstructionsMock).toHaveBeenCalledTimes(1); + const codeSnippet = + showCopyPasteInstructionsMock.mock.calls[0]?.[0]?.codeSnippet ?? ""; + expect(codeSnippet).toMatch(/tracing: \{\s*server: false/); + expect(codeSnippet).toMatch(/instrumentation: \{\s*server: true/); + }); +}); diff --git a/packages/cli/test/lib/wizard/sveltekit/sdk-setup/vite.test.ts b/packages/cli/test/lib/wizard/sveltekit/sdk-setup/vite.test.ts index 3201e15d51..72098b6f7d 100644 --- a/packages/cli/test/lib/wizard/sveltekit/sdk-setup/vite.test.ts +++ b/packages/cli/test/lib/wizard/sveltekit/sdk-setup/vite.test.ts @@ -14,10 +14,15 @@ vi.mock("@clack/prompts", () => ({ select: vi.fn(() => Promise.resolve(true)), })); +vi.mock("../../../../../src/lib/error-reporting.js", () => ({ + reportCliError: vi.fn(), +})); + vi.mock("../../../../../src/lib/wizard/utils/clack/index.js", () => ({ abortIfCancelled: vi.fn((v: unknown) => v), })); +import { log } from "@clack/prompts"; import { modifyViteConfig } from "../../../../../src/lib/wizard/sveltekit/sdk-setup/vite.js"; import type { ProjectInfo } from "../../../../../src/lib/wizard/sveltekit/sdk-setup/types.js"; @@ -108,4 +113,17 @@ export default defineConfig({ expect(readFileSync(viteConfigPath, "utf-8")).toBe(existing); }); + + it("does not report success when the automatic edit fails", async () => { + vi.clearAllMocks(); + // A config that magicast can parse but `addVitePlugin` cannot handle. + writeFileSync(viteConfigPath, "export default 42;\n"); + + await modifyViteConfig(viteConfigPath, projectInfo({})); + + expect(log.warning).toHaveBeenCalledWith( + expect.stringContaining("Couldn't automatically modify"), + ); + expect(log.success).not.toHaveBeenCalled(); + }); }); From 9ddade5dccbdc9947688768370868ed4320ae574 Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Fri, 27 Nov 2026 22:04:58 +0000 Subject: [PATCH 13/17] fix(cli): follow-up review fixes for the React Router and SvelteKit wizards - React Router config: logs and the copy-paste fallback name the config file the wizard actually edits (.js or .ts). - React Router config: a method-style `buildEnd() {}` counts as an existing hook instead of being overwritten. - React Router example routes: the manual fallback names routes.js and .jsx/.js modules in JavaScript apps. - SvelteKit: declining tracing never turns off tracing.server that the config file already enables. Co-Authored-By: BYK <126780+BYK@users.noreply.github.com> --- .../codemods/react-router-config.ts | 33 +++++++--- .../react-router/react-router-wizard.ts | 6 +- .../lib/wizard/react-router/sdk-example.ts | 8 ++- .../src/lib/wizard/react-router/sdk-setup.ts | 7 ++- .../sveltekit/sdk-setup/svelte-config.ts | 6 +- .../codemods/react-router-config.test.ts | 60 ++++++++++++++++++- .../wizard/react-router/sdk-example.test.ts | 21 +++++++ .../sveltekit/sdk-setup/svelte-config.test.ts | 18 ++++++ 8 files changed, 143 insertions(+), 16 deletions(-) diff --git a/packages/cli/src/lib/wizard/react-router/codemods/react-router-config.ts b/packages/cli/src/lib/wizard/react-router/codemods/react-router-config.ts index ae127572a3..1d9a941f0d 100644 --- a/packages/cli/src/lib/wizard/react-router/codemods/react-router-config.ts +++ b/packages/cli/src/lib/wizard/react-router/codemods/react-router-config.ts @@ -72,9 +72,15 @@ export function addSentryBuildEndToReactRouterConfig(program: t.Program): { return { success: false, ssrWasChanged: false }; } - const buildEndProp = findProperty(configObj, "buildEnd"); + // `buildEnd: async () => {}` is a property, `async buildEnd() {}` a method. + const hasBuildEnd = configObj.properties.some( + (p) => + (p.type === "ObjectProperty" || p.type === "ObjectMethod") && + ((p.key.type === "Identifier" && p.key.name === "buildEnd") || + (p.key.type === "StringLiteral" && p.key.value === "buildEnd")), + ); - if (buildEndProp) { + if (hasBuildEnd) { throw new Error( "A buildEnd hook already exists in your React Router config.", ); @@ -159,19 +165,28 @@ export function hasReactRouterSentryContent(program: t.Program): boolean { return hasSentry; } +/** + * The project's React Router config filename. Prefers an existing config with + * either extension, so a `.js` config in a TypeScript project is updated + * instead of shadowed by a new `.ts` file. + */ +export function getReactRouterConfigFilename(isTS: boolean): string { + const preferred = `react-router.config.${isTS ? "ts" : "js"}`; + const other = `react-router.config.${isTS ? "js" : "ts"}`; + return ( + [preferred, other].find((candidate) => + existsSync(path.join(process.cwd(), candidate)), + ) ?? preferred + ); +} + export async function instrumentReactRouterConfig( isTS: boolean, vitePluginImportPath: string = getSentryReactRouterVitePluginImportPath( undefined, ), ): Promise<{ ssrWasChanged: boolean }> { - // Prefer an existing config with either extension, so a `.js` config in a - // TypeScript project is updated instead of shadowed by a new `.ts` file. - const preferredFilename = `react-router.config.${isTS ? "ts" : "js"}`; - const configFilename = - [preferredFilename, `react-router.config.${isTS ? "js" : "ts"}`].find( - (candidate) => existsSync(path.join(process.cwd(), candidate)), - ) ?? preferredFilename; + const configFilename = getReactRouterConfigFilename(isTS); const configPath = path.join(process.cwd(), configFilename); if (!existsSync(configPath)) { diff --git a/packages/cli/src/lib/wizard/react-router/react-router-wizard.ts b/packages/cli/src/lib/wizard/react-router/react-router-wizard.ts index 01c50d920c..9d8fdfbea1 100644 --- a/packages/cli/src/lib/wizard/react-router/react-router-wizard.ts +++ b/packages/cli/src/lib/wizard/react-router/react-router-wizard.ts @@ -35,6 +35,7 @@ import { getSentryReactRouterVitePluginImportPath, } from "./sdk-version.js"; import { debug } from "../utils/debug.js"; +import { getReactRouterConfigFilename } from "./codemods/react-router-config.js"; import { createExamplePage } from "./sdk-example.js"; import { isReactRouterV7, @@ -444,10 +445,11 @@ Please create your entry files manually using React Router v7 commands.`); `Could not configure React Router build hook automatically.`, ); + const configFilename = getReactRouterConfigFilename(typeScriptDetected); await showCopyPasteInstructions({ - filename: `react-router.config.${typeScriptDetected ? "ts" : "js"}`, + filename: configFilename, codeSnippet: getManualReactRouterConfigContent( - typeScriptDetected, + configFilename.endsWith(".ts"), vitePluginImportPath, ), hint: "This enables automatic sourcemap uploads at the end of the build process", diff --git a/packages/cli/src/lib/wizard/react-router/sdk-example.ts b/packages/cli/src/lib/wizard/react-router/sdk-example.ts index 3a0275425a..7a342febf7 100644 --- a/packages/cli/src/lib/wizard/react-router/sdk-example.ts +++ b/packages/cli/src/lib/wizard/react-router/sdk-example.ts @@ -84,7 +84,13 @@ export async function createExamplePage(options: { }`, ); clack.log.info( - 'Please manually add these routes to your routes.ts file: route("/sentry-example-page", "routes/sentry-example-page.tsx") and route("/api/sentry-example-api", "routes/api.sentry-example-api.ts")', + `Please manually add these routes to your ${path.basename( + routesConfigPath, + )} file: route("/sentry-example-page", "routes/sentry-example-page.${ + options.isTS ? "tsx" : "jsx" + }") and route("/api/sentry-example-api", "routes/api.sentry-example-api.${ + options.isTS ? "ts" : "js" + }")`, ); } } diff --git a/packages/cli/src/lib/wizard/react-router/sdk-setup.ts b/packages/cli/src/lib/wizard/react-router/sdk-setup.ts index 722ac8de9c..9d56be1923 100644 --- a/packages/cli/src/lib/wizard/react-router/sdk-setup.ts +++ b/packages/cli/src/lib/wizard/react-router/sdk-setup.ts @@ -20,7 +20,10 @@ import { instrumentServerEntry } from "./codemods/server-entry.js"; import { abortIfCancelled, getPackageDotJson } from "../utils/clack/index.js"; import { instrumentClientEntry } from "./codemods/client.entry.js"; import { instrumentViteConfig } from "./codemods/vite.js"; -import { instrumentReactRouterConfig } from "./codemods/react-router-config.js"; +import { + getReactRouterConfigFilename, + instrumentReactRouterConfig, +} from "./codemods/react-router-config.js"; const REACT_ROUTER_REVEAL_COMMAND = "npx react-router reveal"; const INSTRUMENTATION_FILE = "instrument.server.mjs"; @@ -403,7 +406,7 @@ export async function configureReactRouterConfig( isTS: boolean, vitePluginImportPath: string, ): Promise { - const configFilename = `react-router.config.${isTS ? "ts" : "js"}`; + const configFilename = getReactRouterConfigFilename(isTS); const configPath = path.join(process.cwd(), configFilename); const filename = chalk.cyan(configFilename); diff --git a/packages/cli/src/lib/wizard/sveltekit/sdk-setup/svelte-config.ts b/packages/cli/src/lib/wizard/sveltekit/sdk-setup/svelte-config.ts index c0069d37b3..3fe77554ca 100644 --- a/packages/cli/src/lib/wizard/sveltekit/sdk-setup/svelte-config.ts +++ b/packages/cli/src/lib/wizard/sveltekit/sdk-setup/svelte-config.ts @@ -327,7 +327,11 @@ export function _enableTracingAndInstrumentationInConfig( }; } - kitExperimentalTracingSeverProp.value = b.booleanLiteral(enableTracing); + // Never turn off server tracing that the file already enables, even when + // the loaded config didn't show it. + kitExperimentalTracingSeverProp.value = b.booleanLiteral( + enableTracing || kitExperimentalTracingSeverProp.value.value, + ); } else { experimentalTracingObject.properties.push( b.objectProperty(b.identifier("server"), b.booleanLiteral(enableTracing)), diff --git a/packages/cli/test/lib/wizard/react-router/codemods/react-router-config.test.ts b/packages/cli/test/lib/wizard/react-router/codemods/react-router-config.test.ts index 073bfec3ed..554c9841e8 100644 --- a/packages/cli/test/lib/wizard/react-router/codemods/react-router-config.test.ts +++ b/packages/cli/test/lib/wizard/react-router/codemods/react-router-config.test.ts @@ -1,7 +1,12 @@ import { existsSync, promises } from "node:fs"; import path from "node:path"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -import { instrumentReactRouterConfig } from "../../../../../src/lib/wizard/react-router/codemods/react-router-config.js"; +import { log } from "@clack/prompts"; +import { + getReactRouterConfigFilename, + instrumentReactRouterConfig, +} from "../../../../../src/lib/wizard/react-router/codemods/react-router-config.js"; +import { configureReactRouterConfig } from "../../../../../src/lib/wizard/react-router/sdk-setup.js"; vi.mock("@clack/prompts", () => ({ log: { @@ -134,6 +139,46 @@ export default { expect(result.ssrWasChanged).toBe(false); }); + it.each([ + [true, [], "react-router.config.ts"], + [false, [], "react-router.config.js"], + [true, ["react-router.config.js"], "react-router.config.js"], + [false, ["react-router.config.ts"], "react-router.config.ts"], + [ + true, + ["react-router.config.ts", "react-router.config.js"], + "react-router.config.ts", + ], + ])( + "getReactRouterConfigFilename(isTS: %s) with %j picks %s", + (isTS, existing, expected) => { + vi.mocked(existsSync).mockImplementation((filePath) => + existing.some((name) => filePath === path.join(mockCwd, name)), + ); + + expect(getReactRouterConfigFilename(isTS)).toBe(expected); + }, + ); + + it("names the existing .js config when configuring a TypeScript project", async () => { + vi.mocked(existsSync).mockImplementation( + (filePath) => filePath === path.join(mockCwd, "react-router.config.js"), + ); + vi.mocked(promises.readFile).mockResolvedValue( + "export default {\n ssr: true,\n};\n", + ); + vi.mocked(promises.writeFile).mockResolvedValue(); + + await configureReactRouterConfig(true, "@sentry/react-router"); + + expect(log.success).toHaveBeenCalledWith( + expect.stringContaining("react-router.config.js"), + ); + expect(log.success).not.toHaveBeenCalledWith( + expect.stringContaining("react-router.config.ts"), + ); + }); + it("updates an existing react-router.config.js in a TypeScript project", async () => { const writtenFiles: Record = {}; vi.mocked(existsSync).mockImplementation( @@ -225,6 +270,19 @@ export default { expect(writtenConfig).toContain("ssr: true"); }); + it("throws when buildEnd already exists as a method", async () => { + vi.mocked(existsSync).mockReturnValue(true); + vi.mocked(promises.readFile).mockResolvedValue( + "export default {\n ssr: true,\n async buildEnd() {\n await upload();\n },\n};\n", + ); + vi.mocked(promises.writeFile).mockResolvedValue(); + + await expect(instrumentReactRouterConfig(true)).rejects.toThrow( + "A buildEnd hook already exists", + ); + expect(promises.writeFile).not.toHaveBeenCalled(); + }); + it("should throw error if buildEnd already exists", async () => { const existingConfig = `export default { ssr: true, diff --git a/packages/cli/test/lib/wizard/react-router/sdk-example.test.ts b/packages/cli/test/lib/wizard/react-router/sdk-example.test.ts index 9fced90fcb..36e6c9f393 100644 --- a/packages/cli/test/lib/wizard/react-router/sdk-example.test.ts +++ b/packages/cli/test/lib/wizard/react-router/sdk-example.test.ts @@ -13,6 +13,7 @@ vi.mock("@clack/prompts", () => ({ log: { info: vi.fn(), warn: vi.fn(), success: vi.fn() }, })); +import { log } from "@clack/prompts"; import { createExamplePage } from "../../../../src/lib/wizard/react-router/sdk-example.js"; describe("createExamplePage", () => { @@ -56,4 +57,24 @@ export default [index("routes/home.jsx")]; 'route("/api/sentry-example-api", "routes/api.sentry-example-api.js")', ); }); + + it("gives JavaScript paths in the manual routes fallback", async () => { + writeFileSync( + path.join(tmpDir, "app", "routes.js"), + "export default routes;\n", + ); + + await createExamplePage({ + selfHosted: false, + orgSlug: "org", + projectId: "1", + url: "https://sentry.io/", + isTS: false, + projectDir: tmpDir, + }); + + expect(log.info).toHaveBeenCalledWith( + 'Please manually add these routes to your routes.js file: route("/sentry-example-page", "routes/sentry-example-page.jsx") and route("/api/sentry-example-api", "routes/api.sentry-example-api.js")', + ); + }); }); diff --git a/packages/cli/test/lib/wizard/sveltekit/sdk-setup/svelte-config.test.ts b/packages/cli/test/lib/wizard/sveltekit/sdk-setup/svelte-config.test.ts index 0a21edf567..c59ea90f08 100644 --- a/packages/cli/test/lib/wizard/sveltekit/sdk-setup/svelte-config.test.ts +++ b/packages/cli/test/lib/wizard/sveltekit/sdk-setup/svelte-config.test.ts @@ -661,4 +661,22 @@ export default { expect(modifiedConfig.error).toBe("Failed to parse Svelte config"); }); }); + + it("keeps tracing.server true in the file when tracing is declined", () => { + const { result, error } = _enableTracingAndInstrumentationInConfig( + `export default { + kit: { + experimental: { + tracing: { server: true }, + }, + }, +}; +`, + false, + ); + + expect(error).toBeUndefined(); + expect(result).toMatch(/tracing:\s*\{\s*server:\s*true/); + expect(result).not.toMatch(/tracing:\s*\{\s*server:\s*false/); + }); }); From 1afdba23fbec95fdc1caea97b5f7c5897447c894 Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Fri, 27 Nov 2026 22:19:39 +0000 Subject: [PATCH 14/17] fix(cli): React Router wizard telemetry notice, quoted ssr key, vite fallback filename - Pass telemetryEnabled to printWelcome so the disclosure shows, as in the other wizards. - Match quoted "ssr" keys so an existing "ssr": false is flipped, not shadowed. - Name the existing vite.config file in the copy-paste fallback. --- .../codemods/react-router-config.ts | 38 +++++++++++-------- .../lib/wizard/react-router/codemods/vite.ts | 15 ++++++-- .../react-router/react-router-wizard.ts | 4 +- .../src/lib/wizard/react-router/sdk-setup.ts | 10 ++--- .../codemods/react-router-config.test.ts | 22 +++++++++++ .../wizard/react-router/codemods/vite.test.ts | 29 ++++++++++++++ .../react-router/react-router-wizard.test.ts | 14 +++++++ 7 files changed, 107 insertions(+), 25 deletions(-) diff --git a/packages/cli/src/lib/wizard/react-router/codemods/react-router-config.ts b/packages/cli/src/lib/wizard/react-router/codemods/react-router-config.ts index 1d9a941f0d..7a923b180c 100644 --- a/packages/cli/src/lib/wizard/react-router/codemods/react-router-config.ts +++ b/packages/cli/src/lib/wizard/react-router/codemods/react-router-config.ts @@ -13,10 +13,7 @@ import { parseModule, generateCode } from "magicast"; import { clack } from "../../utils/clack/prompts.js"; import chalk from "chalk"; -import { - findProperty, - preserveTrailingNewline, -} from "../../utils/ast-utils.js"; +import { preserveTrailingNewline } from "../../utils/ast-utils.js"; import { getSentryReactRouterVitePluginImportPath } from "../sdk-version.js"; /** @@ -72,21 +69,13 @@ export function addSentryBuildEndToReactRouterConfig(program: t.Program): { return { success: false, ssrWasChanged: false }; } - // `buildEnd: async () => {}` is a property, `async buildEnd() {}` a method. - const hasBuildEnd = configObj.properties.some( - (p) => - (p.type === "ObjectProperty" || p.type === "ObjectMethod") && - ((p.key.type === "Identifier" && p.key.name === "buildEnd") || - (p.key.type === "StringLiteral" && p.key.value === "buildEnd")), - ); - - if (hasBuildEnd) { + if (findConfigProperty(configObj, "buildEnd")) { throw new Error( "A buildEnd hook already exists in your React Router config.", ); } - const ssrProp = findProperty(configObj, "ssr"); + const ssrProp = findConfigProperty(configObj, "ssr"); if (!ssrProp) { const ssrProperty = b.objectProperty( @@ -103,8 +92,9 @@ export function addSentryBuildEndToReactRouterConfig(program: t.Program): { configObj.properties.unshift(ssrProperty); ssrWasChanged = true; } else if ( - ssrProp.value.type === "BooleanLiteral" || - ssrProp.value.type === "Literal" + ssrProp.type === "ObjectProperty" && + (ssrProp.value.type === "BooleanLiteral" || + ssrProp.value.type === "Literal") ) { const wasExplicitlyFalse = ssrProp.value.value === false; @@ -246,3 +236,19 @@ export default { return { ssrWasChanged }; } + +/** + * A config key, whether written `key`, `"key"` or as a method (`key() {}`), so + * an existing entry is updated or detected instead of shadowed by a new one. + */ +function findConfigProperty( + configObj: t.ObjectExpression, + name: string, +): t.ObjectProperty | t.ObjectMethod | undefined { + return configObj.properties.find( + (p): p is t.ObjectProperty | t.ObjectMethod => + (p.type === "ObjectProperty" || p.type === "ObjectMethod") && + ((p.key.type === "Identifier" && p.key.name === name) || + (p.key.type === "StringLiteral" && p.key.value === name)), + ); +} diff --git a/packages/cli/src/lib/wizard/react-router/codemods/vite.ts b/packages/cli/src/lib/wizard/react-router/codemods/vite.ts index e2e39a1002..3c15541483 100644 --- a/packages/cli/src/lib/wizard/react-router/codemods/vite.ts +++ b/packages/cli/src/lib/wizard/react-router/codemods/vite.ts @@ -219,6 +219,17 @@ export function addReactRouterPluginToViteConfig( return { success: true, wasConverted }; } +/** + * The project's Vite config filename: an existing `vite.config.ts`, else an + * existing `vite.config.js`, else the one matching the project's language. + */ +export function getViteConfigFilename(isTS: boolean): string { + const existing = ["vite.config.ts", "vite.config.js"].find((name) => + existsSync(path.join(process.cwd(), name)), + ); + return existing ?? `vite.config.${isTS ? "ts" : "js"}`; +} + export async function instrumentViteConfig( orgSlug: string, projectSlug: string, @@ -226,9 +237,7 @@ export async function instrumentViteConfig( undefined, ), ): Promise<{ wasConverted: boolean }> { - const configPath = existsSync(path.join(process.cwd(), "vite.config.ts")) - ? path.join(process.cwd(), "vite.config.ts") - : path.join(process.cwd(), "vite.config.js"); + const configPath = path.join(process.cwd(), getViteConfigFilename(true)); if (!existsSync(configPath)) { throw new Error("Could not find vite.config.ts or vite.config.js"); diff --git a/packages/cli/src/lib/wizard/react-router/react-router-wizard.ts b/packages/cli/src/lib/wizard/react-router/react-router-wizard.ts index 9d8fdfbea1..33454cb30f 100644 --- a/packages/cli/src/lib/wizard/react-router/react-router-wizard.ts +++ b/packages/cli/src/lib/wizard/react-router/react-router-wizard.ts @@ -36,6 +36,7 @@ import { } from "./sdk-version.js"; import { debug } from "../utils/debug.js"; import { getReactRouterConfigFilename } from "./codemods/react-router-config.js"; +import { getViteConfigFilename } from "./codemods/vite.js"; import { createExamplePage } from "./sdk-example.js"; import { isReactRouterV7, @@ -83,6 +84,7 @@ async function runReactRouterWizardWithTelemetry( ): Promise { printWelcome({ wizardName: "Sentry React Router Wizard", + telemetryEnabled: options.telemetryEnabled, }); const packageJson = await getPackageDotJson(); @@ -420,7 +422,7 @@ Please create your entry files manually using React Router v7 commands.`); ); await showCopyPasteInstructions({ - filename: `vite.config.${typeScriptDetected ? "ts" : "js"}`, + filename: getViteConfigFilename(typeScriptDetected), codeSnippet: getManualViteConfigContent( selectedProject.organization.slug, selectedProject.slug, diff --git a/packages/cli/src/lib/wizard/react-router/sdk-setup.ts b/packages/cli/src/lib/wizard/react-router/sdk-setup.ts index 9d56be1923..85f6720c73 100644 --- a/packages/cli/src/lib/wizard/react-router/sdk-setup.ts +++ b/packages/cli/src/lib/wizard/react-router/sdk-setup.ts @@ -19,11 +19,14 @@ import { getSentryInstrumentationServerContent } from "./templates.js"; import { instrumentServerEntry } from "./codemods/server-entry.js"; import { abortIfCancelled, getPackageDotJson } from "../utils/clack/index.js"; import { instrumentClientEntry } from "./codemods/client.entry.js"; -import { instrumentViteConfig } from "./codemods/vite.js"; import { getReactRouterConfigFilename, instrumentReactRouterConfig, } from "./codemods/react-router-config.js"; +import { + getViteConfigFilename, + instrumentViteConfig, +} from "./codemods/vite.js"; const REACT_ROUTER_REVEAL_COMMAND = "npx react-router reveal"; const INSTRUMENTATION_FILE = "instrument.server.mjs"; @@ -368,10 +371,7 @@ export async function configureReactRouterVitePlugin( projectSlug: string, vitePluginImportPath: string, ): Promise { - const configPath = existsSync(path.join(process.cwd(), "vite.config.ts")) - ? path.join(process.cwd(), "vite.config.ts") - : path.join(process.cwd(), "vite.config.js"); - const filename = chalk.cyan(path.basename(configPath)); + const filename = chalk.cyan(getViteConfigFilename(true)); try { const { wasConverted } = await instrumentViteConfig( diff --git a/packages/cli/test/lib/wizard/react-router/codemods/react-router-config.test.ts b/packages/cli/test/lib/wizard/react-router/codemods/react-router-config.test.ts index 554c9841e8..e17b9adc6a 100644 --- a/packages/cli/test/lib/wizard/react-router/codemods/react-router-config.test.ts +++ b/packages/cli/test/lib/wizard/react-router/codemods/react-router-config.test.ts @@ -248,6 +248,28 @@ export default { expect(writtenConfig).toContain("ssr: true"); }); + it('flips a quoted "ssr": false instead of adding a second key', async () => { + const existingConfig = `export default { + "ssr": false +};`; + + const writtenFiles: Record = {}; + + vi.mocked(existsSync).mockReturnValue(true); + vi.mocked(promises.readFile).mockResolvedValue(existingConfig); + vi.mocked(promises.writeFile).mockImplementation((filePath, content) => { + writtenFiles[filePath as string] = content as string; + return Promise.resolve(); + }); + + const result = await instrumentReactRouterConfig(true); + + expect(result.ssrWasChanged).toBe(true); + const writtenConfig = Object.values(writtenFiles)[0]; + expect(writtenConfig).not.toContain("false"); + expect(writtenConfig?.match(/ssr/g)).toHaveLength(1); + }); + it("should report ssrWasChanged when changing ssr from false to true", async () => { const existingConfig = `export default { ssr: false diff --git a/packages/cli/test/lib/wizard/react-router/codemods/vite.test.ts b/packages/cli/test/lib/wizard/react-router/codemods/vite.test.ts index 321e8ac579..12232b8914 100644 --- a/packages/cli/test/lib/wizard/react-router/codemods/vite.test.ts +++ b/packages/cli/test/lib/wizard/react-router/codemods/vite.test.ts @@ -3,6 +3,7 @@ import type { namedTypes as t } from "ast-types"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { addReactRouterPluginToViteConfig, + getViteConfigFilename, instrumentViteConfig, } from "../../../../../src/lib/wizard/react-router/codemods/vite.js"; @@ -312,3 +313,31 @@ export default defineConfig(function(config) { }); }); }); + +describe("getViteConfigFilename", () => { + beforeEach(() => { + vi.spyOn(process, "cwd").mockReturnValue("/mock/project"); + }); + + afterEach(() => { + vi.restoreAllMocks(); + }); + + it("names an existing vite.config.js in a TypeScript project", () => { + vi.mocked(existsSync).mockImplementation( + (p) => p === "/mock/project/vite.config.js", + ); + expect(getViteConfigFilename(true)).toBe("vite.config.js"); + }); + + it("prefers an existing vite.config.ts, as the codemod does", () => { + vi.mocked(existsSync).mockReturnValue(true); + expect(getViteConfigFilename(false)).toBe("vite.config.ts"); + }); + + it("falls back to the project language when neither exists", () => { + vi.mocked(existsSync).mockReturnValue(false); + expect(getViteConfigFilename(true)).toBe("vite.config.ts"); + expect(getViteConfigFilename(false)).toBe("vite.config.js"); + }); +}); diff --git a/packages/cli/test/lib/wizard/react-router/react-router-wizard.test.ts b/packages/cli/test/lib/wizard/react-router/react-router-wizard.test.ts index 914147a250..8063c6edea 100644 --- a/packages/cli/test/lib/wizard/react-router/react-router-wizard.test.ts +++ b/packages/cli/test/lib/wizard/react-router/react-router-wizard.test.ts @@ -40,6 +40,7 @@ vi.mock("../../../../src/lib/wizard/utils/node-version.js", () => ({ })); import { runReactRouterWizard } from "../../../../src/lib/wizard/react-router/react-router-wizard.js"; +import { printWelcome } from "../../../../src/lib/wizard/utils/clack/index.js"; describe("runReactRouterWizard", () => { beforeEach(() => { @@ -66,4 +67,17 @@ describe("runReactRouterWizard", () => { ); }, ); + + it.each([true, false])( + "shows the telemetry disclosure when telemetryEnabled=%s", + async (telemetryEnabled) => { + await expect( + runReactRouterWizard({ telemetryEnabled, forceInstall: false }), + ).rejects.toThrow("stop after install"); + + expect(printWelcome).toHaveBeenCalledWith( + expect.objectContaining({ telemetryEnabled }), + ); + }, + ); }); From 19849a491bceaaa159f99f5a40a1832fe1553475 Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Fri, 27 Nov 2026 22:47:48 +0000 Subject: [PATCH 15/17] fix(cli): don't instrument an already instrumented Remix build script again --- .../cli/src/lib/wizard/remix/sdk-setup.ts | 10 ++++++ .../lib/wizard/remix/build-script.test.ts | 33 +++++++++++++++---- 2 files changed, 37 insertions(+), 6 deletions(-) diff --git a/packages/cli/src/lib/wizard/remix/sdk-setup.ts b/packages/cli/src/lib/wizard/remix/sdk-setup.ts index ef128c2625..b17bda52e8 100644 --- a/packages/cli/src/lib/wizard/remix/sdk-setup.ts +++ b/packages/cli/src/lib/wizard/remix/sdk-setup.ts @@ -352,6 +352,16 @@ export async function updateBuildScript(args: { (args.url ? ` --url ${args.url}` : "") + (args.isHydrogen ? " --buildPath ./dist" : ""); + if ( + packageJson.scripts["build"]?.includes("@sentry/remix --upload-sourcemaps") + ) { + // Already set up by an earlier run; replacing again would duplicate it. + clack.log.info( + `${chalk.cyan("build")} script already uploads sourcemaps, skipping.`, + ); + return; + } + if (!packageJson.scripts["build"]) { packageJson.scripts["build"] = instrumentedBuildCommand; } else if (packageJson.scripts["build"].includes(buildCommand)) { diff --git a/packages/cli/test/lib/wizard/remix/build-script.test.ts b/packages/cli/test/lib/wizard/remix/build-script.test.ts index 1ad6c3283e..efd2e0e915 100644 --- a/packages/cli/test/lib/wizard/remix/build-script.test.ts +++ b/packages/cli/test/lib/wizard/remix/build-script.test.ts @@ -24,12 +24,15 @@ vi.mock("@clack/prompts", () => { vi.mock("../../../../src/lib/wizard/utils/clack/index.js", async () => ({ ...(await vi.importActual("../../../../src/lib/wizard/utils/clack/index.js")), - getPackageDotJson: vi.fn().mockResolvedValue({ - scripts: { - build: "remix build", - }, - version: "1.0.0", - }), + // A fresh object per call: updateBuildScript mutates the one it gets. + getPackageDotJson: vi.fn(() => + Promise.resolve({ + scripts: { + build: "remix build", + }, + version: "1.0.0", + }), + ), })); describe("updateBuildScript", () => { @@ -139,4 +142,22 @@ describe("updateBuildScript", () => { }), ).rejects.toThrow("build` script doesn't contain a known build command"); }); + + it("leaves an already instrumented build script alone on a re-run", async () => { + vi.mocked(getPackageDotJson).mockResolvedValueOnce({ + scripts: { + build: + "remix build --sourcemap && npx @sentry/remix --upload-sourcemaps --org my-org --project my-project", + }, + version: "1.0.0", + }); + + await updateBuildScript({ + org: "my-org", + project: "my-project", + isHydrogen: false, + }); + + expect(writeFileSpy).not.toHaveBeenCalled(); + }); }); From cc081c970e5d52b140c8a06a453290b5ecc4def7 Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Fri, 27 Nov 2026 23:03:49 +0000 Subject: [PATCH 16/17] fix(cli): find React Router entries whose extension differs from tsconfig --- .../react-router/react-router-wizard.ts | 15 ++++++---- .../src/lib/wizard/react-router/sdk-setup.ts | 25 ++++++++++++----- .../lib/wizard/react-router/sdk-setup.test.ts | 28 +++++++++++++++++++ 3 files changed, 55 insertions(+), 13 deletions(-) diff --git a/packages/cli/src/lib/wizard/react-router/react-router-wizard.ts b/packages/cli/src/lib/wizard/react-router/react-router-wizard.ts index 33454cb30f..7ebfaa2201 100644 --- a/packages/cli/src/lib/wizard/react-router/react-router-wizard.ts +++ b/packages/cli/src/lib/wizard/react-router/react-router-wizard.ts @@ -50,6 +50,7 @@ import { instrumentSentryOnEntryServer, configureReactRouterConfig, configureReactRouterVitePlugin, + getEntryFilename, } from "./sdk-setup.js"; import { getManualClientEntryContent, @@ -284,9 +285,10 @@ Please create your entry files manually using React Router v7 commands.`); `Could not initialize Sentry on client entry automatically.`, ); - const clientEntryFilename = `entry.client.${ - typeScriptDetected ? "tsx" : "jsx" - }`; + const clientEntryFilename = getEntryFilename( + "entry.client", + typeScriptDetected, + ); const manualClientContent = getManualClientEntryContent( selectedProject.keys[0].dsn.public, @@ -318,9 +320,10 @@ Please create your entry files manually using React Router v7 commands.`); `Could not initialize Sentry on server entry automatically.`, ); - const serverEntryFilename = `entry.server.${ - typeScriptDetected ? "tsx" : "jsx" - }`; + const serverEntryFilename = getEntryFilename( + "entry.server", + typeScriptDetected, + ); const manualServerContent = getManualServerEntryContent( useInstrumentationAPI, ); diff --git a/packages/cli/src/lib/wizard/react-router/sdk-setup.ts b/packages/cli/src/lib/wizard/react-router/sdk-setup.ts index 85f6720c73..9ef3c991e9 100644 --- a/packages/cli/src/lib/wizard/react-router/sdk-setup.ts +++ b/packages/cli/src/lib/wizard/react-router/sdk-setup.ts @@ -45,13 +45,24 @@ function _formatConfigErrorMessage( ); } -function getAppFilePath( - filename: string, - isTS: boolean, - isPage = true, -): string { - const ext = isPage ? (isTS ? "tsx" : "jsx") : isTS ? "ts" : "js"; - return path.join(process.cwd(), APP_DIRECTORY, `${filename}.${ext}`); +/** + * The filename of an `app/` entry such as `entry.client`: the `.tsx` or + * `.jsx` file that exists, else the one matching the project's language. + */ +export function getEntryFilename(name: string, isTS: boolean): string { + const preferred = `${name}.${isTS ? "tsx" : "jsx"}`; + const alternate = `${name}.${isTS ? "jsx" : "tsx"}`; + const exists = (file: string) => + existsSync(path.join(process.cwd(), APP_DIRECTORY, file)); + return !exists(preferred) && exists(alternate) ? alternate : preferred; +} + +function getAppFilePath(filename: string, isTS: boolean): string { + return path.join( + process.cwd(), + APP_DIRECTORY, + getEntryFilename(filename, isTS), + ); } export function getRouteFilePath(filename: string, isTS: boolean): string { diff --git a/packages/cli/test/lib/wizard/react-router/sdk-setup.test.ts b/packages/cli/test/lib/wizard/react-router/sdk-setup.test.ts index 742b6368e6..80b4be7ab8 100644 --- a/packages/cli/test/lib/wizard/react-router/sdk-setup.test.ts +++ b/packages/cli/test/lib/wizard/react-router/sdk-setup.test.ts @@ -116,6 +116,7 @@ import { createServerInstrumentationFile, tryRevealAndGetManualInstructions, updatePackageJsonScripts, + getEntryFilename, } from "../../../../src/lib/wizard/react-router/sdk-setup.js"; import { execSync } from "node:child_process"; import type { Mock } from "vitest"; @@ -764,3 +765,30 @@ describe("updatePackageJsonScripts", () => { ); }); }); + +describe("getEntryFilename", () => { + beforeEach(() => { + vi.clearAllMocks(); + }); + + it("finds a .jsx entry in a TypeScript project", () => { + existsSyncMock.mockImplementation((p: string) => + p.endsWith("entry.client.jsx"), + ); + expect(getEntryFilename("entry.client", true)).toBe("entry.client.jsx"); + }); + + it("finds a .tsx entry in a JavaScript project", () => { + existsSyncMock.mockImplementation((p: string) => + p.endsWith("entry.server.tsx"), + ); + expect(getEntryFilename("entry.server", false)).toBe("entry.server.tsx"); + }); + + it("uses the project language when both or neither exist", () => { + existsSyncMock.mockReturnValue(true); + expect(getEntryFilename("entry.client", true)).toBe("entry.client.tsx"); + existsSyncMock.mockReturnValue(false); + expect(getEntryFilename("entry.client", false)).toBe("entry.client.jsx"); + }); +}); From 89d2d643150f9887715434edc2f7315186a4755a Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Fri, 27 Nov 2026 23:24:32 +0000 Subject: [PATCH 17/17] fix(cli): match @sentry/profiling-node to the installed React Router SDK major --- .../lib/wizard/react-router/react-router-wizard.ts | 5 ++++- .../cli/src/lib/wizard/react-router/sdk-version.ts | 13 +++++++++++++ .../lib/wizard/react-router/sdk-version.test.ts | 13 +++++++++++++ 3 files changed, 30 insertions(+), 1 deletion(-) diff --git a/packages/cli/src/lib/wizard/react-router/react-router-wizard.ts b/packages/cli/src/lib/wizard/react-router/react-router-wizard.ts index 7ebfaa2201..9a11de511c 100644 --- a/packages/cli/src/lib/wizard/react-router/react-router-wizard.ts +++ b/packages/cli/src/lib/wizard/react-router/react-router-wizard.ts @@ -32,6 +32,7 @@ import { import { MIN_REACT_ROUTER_VERSION_FOR_SDK_V11, SENTRY_REACT_ROUTER_SDK_RANGE, + getProfilingNodeRange, getSentryReactRouterVitePluginImportPath, } from "./sdk-version.js"; import { debug } from "../utils/debug.js"; @@ -205,7 +206,9 @@ The wizard will continue, but you may need to upgrade React Router before moving ); await installPackage({ - packageName: `@sentry/profiling-node@${SENTRY_REACT_ROUTER_SDK_RANGE}`, + packageName: `@sentry/profiling-node@${getProfilingNodeRange( + installedSdkVersion, + )}`, packageNameDisplayLabel: "@sentry/profiling-node", alreadyInstalled: profilingAlreadyInstalled, forceInstall: options.forceInstall, diff --git a/packages/cli/src/lib/wizard/react-router/sdk-version.ts b/packages/cli/src/lib/wizard/react-router/sdk-version.ts index a08793f961..afb7977109 100644 --- a/packages/cli/src/lib/wizard/react-router/sdk-version.ts +++ b/packages/cli/src/lib/wizard/react-router/sdk-version.ts @@ -35,3 +35,16 @@ export function getSentryReactRouterVitePluginImportPath( ? SENTRY_REACT_ROUTER_VITE_IMPORT_PATH : SENTRY_REACT_ROUTER_ROOT_IMPORT_PATH; } + +/** + * The `@sentry/profiling-node` range matching the installed SDK's major, so a + * kept v10 SDK doesn't get a v11 profiler. Falls back to the install range. + */ +export function getProfilingNodeRange( + installedSdkVersion: string | undefined, +): string { + const sdkMajor = getMajorVersion(installedSdkVersion); + return sdkMajor === undefined + ? SENTRY_REACT_ROUTER_SDK_RANGE + : `^${sdkMajor}`; +} diff --git a/packages/cli/test/lib/wizard/react-router/sdk-version.test.ts b/packages/cli/test/lib/wizard/react-router/sdk-version.test.ts index 3ec4bcefc3..6d0b6fab77 100644 --- a/packages/cli/test/lib/wizard/react-router/sdk-version.test.ts +++ b/packages/cli/test/lib/wizard/react-router/sdk-version.test.ts @@ -2,6 +2,7 @@ import { describe, expect, it } from "vitest"; import { getSentryReactRouterVitePluginImportPath, SENTRY_REACT_ROUTER_SDK_RANGE, + getProfilingNodeRange, } from "../../../../src/lib/wizard/react-router/sdk-version.js"; describe("getSentryReactRouterVitePluginImportPath", () => { @@ -32,3 +33,15 @@ describe("getSentryReactRouterVitePluginImportPath", () => { }, ); }); + +describe("getProfilingNodeRange", () => { + it.each([ + ["^10.20.0", "^10"], + ["10.5.1", "^10"], + ["^11.0.0", "^11"], + [undefined, "^11"], + ["workspace:*", "^11"], + ])("matches the installed SDK %s with %s", (installed, expected) => { + expect(getProfilingNodeRange(installed)).toBe(expected); + }); +});