diff --git a/packages/cli/src/lib/wizard/cloudflare/cloudflare-wizard.ts b/packages/cli/src/lib/wizard/cloudflare/cloudflare-wizard.ts index afef021f4..136565461 100644 --- a/packages/cli/src/lib/wizard/cloudflare/cloudflare-wizard.ts +++ b/packages/cli/src/lib/wizard/cloudflare/cloudflare-wizard.ts @@ -154,7 +154,10 @@ async function runCloudflareWizardWithTelemetry( binding: "CF_VERSION_METADATA", }, }, - { removeCompatibilityFlags: ["nodejs_als"] }, + { + removeCompatibilityFlags: ["nodejs_als"], + keepCompatibilityDate: true, + }, ), ); diff --git a/packages/cli/src/lib/wizard/cloudflare/sdk-setup.ts b/packages/cli/src/lib/wizard/cloudflare/sdk-setup.ts index f1dc97c1c..82a714f30 100644 --- a/packages/cli/src/lib/wizard/cloudflare/sdk-setup.ts +++ b/packages/cli/src/lib/wizard/cloudflare/sdk-setup.ts @@ -1,7 +1,6 @@ /** - * Write the Sentry initialization into the worker entry point: wrap an - * existing handler, or create an entry point when the Wrangler config names - * none. + * Write the Sentry initialization into the worker entry point: wrap the + * existing handler, or create a starter worker and wrap that. */ import chalk from "chalk"; @@ -21,8 +20,10 @@ import { import { wrapWorkerWithSentry } from "./wrap-worker.js"; /** - * Creates or updates the main worker file with Sentry initialization. - * Currently focused on Cloudflare Workers + * Wraps the worker entry point with Sentry initialization. When the entry + * point the Wrangler config names, or the default one, doesn't exist yet, it + * creates a starter worker there first, so every path ends with a wrapped + * worker. */ export async function createSentryInitFile( dsn: string, @@ -31,65 +32,49 @@ export async function createSentryInitFile( }, reduceDataCollection: boolean, ): Promise { - const entryPointFromConfig = getEntryPointFromWranglerConfig(); + const entryPoint = getEntryPointFromWranglerConfig() ?? defaultEntryPoint; + const entryPointPath = path.join(process.cwd(), entryPoint); - if (!entryPointFromConfig) { + if (existsSync(entryPointPath)) { + clack.log.info(`Found existing entry point: ${chalk.cyan(entryPoint)}`); + } else { clack.log.info( - "No entry point found in wrangler config, creating a new one.", + `No worker found at ${chalk.cyan(entryPoint)}, creating a new one.`, ); - const cloudflareWorkerTemplate = getCloudflareWorkerTemplateWithHandler(); - - await promises.mkdir( - path.join(process.cwd(), path.dirname(defaultEntryPoint)), - { - recursive: true, - }, - ); + await promises.mkdir(path.dirname(entryPointPath), { recursive: true }); await promises.writeFile( - path.join(process.cwd(), defaultEntryPoint), - cloudflareWorkerTemplate, + entryPointPath, + getCloudflareWorkerTemplateWithHandler(/\.[cm]?tsx?$/.test(entryPoint)), { encoding: "utf-8", flag: "w" }, ); - clack.log.success(`Created ${chalk.cyan(defaultEntryPoint)}.`); - - return; + clack.log.success(`Created ${chalk.cyan(entryPoint)}.`); } - const entryPointPath = path.join(process.cwd(), entryPointFromConfig); - - if (existsSync(entryPointPath)) { - clack.log.info( - `Found existing entry point: ${chalk.cyan(entryPointFromConfig)}`, + try { + await wrapWorkerWithSentry( + entryPointPath, + dsn, + selectedFeatures, + reduceDataCollection, ); + clack.log.success( + `Wrapped ${chalk.cyan(entryPoint)} with Sentry initialization.`, + ); + } catch (error) { + debug(error); + clack.log.warn("Failed to wrap worker automatically."); + clack.log.step("Please wrap your handler with Sentry initialization:"); - try { - await wrapWorkerWithSentry( - entryPointPath, - dsn, - selectedFeatures, - reduceDataCollection, - ); - clack.log.success( - `Wrapped ${chalk.cyan( - entryPointFromConfig, - )} with Sentry initialization.`, - ); - } catch (error) { - debug(error); - clack.log.warn("Failed to wrap worker automatically."); - clack.log.step("Please wrap your handler with Sentry initialization:"); - - clack.note( - chalk.cyan( - getCloudflareWorkerTemplate( - dsn, - selectedFeatures, - reduceDataCollection, - ), + clack.note( + chalk.cyan( + getCloudflareWorkerTemplate( + dsn, + selectedFeatures, + reduceDataCollection, ), - ); - } + ), + ); } } diff --git a/packages/cli/src/lib/wizard/cloudflare/templates.ts b/packages/cli/src/lib/wizard/cloudflare/templates.ts index 9c3655747..68445a110 100644 --- a/packages/cli/src/lib/wizard/cloudflare/templates.ts +++ b/packages/cli/src/lib/wizard/cloudflare/templates.ts @@ -39,9 +39,15 @@ export default Sentry.withSentry( `; } -export function getCloudflareWorkerTemplateWithHandler(): string { +/** + * A starter worker. With `typescript` unset, it leaves out the type + * annotations, for a `.js` or `.mjs` entry point. + */ +export function getCloudflareWorkerTemplateWithHandler( + typescript: boolean, +): string { return `export default { - async fetch(request, env, ctx): Promise { + async fetch(request, env, ctx)${typescript ? ": Promise" : ""} { const url = new URL(request.url); switch (url.pathname) { case '/message': @@ -52,6 +58,6 @@ export function getCloudflareWorkerTemplateWithHandler(): string { return new Response('Not Found', { status: 404 }); } }, -} satisfies ExportedHandler; +}${typescript ? " satisfies ExportedHandler" : ""}; `; } diff --git a/packages/cli/src/lib/wizard/cloudflare/wrangler/get-entry-point-from-wrangler-config.ts b/packages/cli/src/lib/wizard/cloudflare/wrangler/get-entry-point-from-wrangler-config.ts index e244f72a1..81e7bf0d7 100644 --- a/packages/cli/src/lib/wizard/cloudflare/wrangler/get-entry-point-from-wrangler-config.ts +++ b/packages/cli/src/lib/wizard/cloudflare/wrangler/get-entry-point-from-wrangler-config.ts @@ -49,7 +49,8 @@ export function getEntryPointFromWranglerConfig(): string | undefined { mainProperty?.value.type === "Literal") && typeof mainProperty.value.value === "string" ) { - return mainProperty.value.value; + // An empty `main` names no file, as in the TOML branch. + return mainProperty.value.value || undefined; } return undefined; diff --git a/packages/cli/src/lib/wizard/cloudflare/wrangler/update-wrangler-config.ts b/packages/cli/src/lib/wizard/cloudflare/wrangler/update-wrangler-config.ts index 785cb9375..0b95350b4 100644 --- a/packages/cli/src/lib/wizard/cloudflare/wrangler/update-wrangler-config.ts +++ b/packages/cli/src/lib/wizard/cloudflare/wrangler/update-wrangler-config.ts @@ -25,6 +25,7 @@ import { findWranglerConfig } from "./find-wrangler-config.js"; const b = recast.types.builders; type WranglerConfigUpdates = { + main?: string; compatibility_date?: string; compatibility_flags?: string[]; version_metadata?: { @@ -39,10 +40,19 @@ type WranglerConfigUpdateOptions = { * e.g. flags superseded by one of the flags being added. */ removeCompatibilityFlags?: string[] | undefined; + /** + * Set `compatibility_date` only when the config doesn't have one yet: the + * date pins the Worker's runtime behaviour. + */ + keepCompatibilityDate?: boolean | undefined; }; -const getTomlConfigSnippet = (options: WranglerConfigUpdateOptions) => { +const getTomlConfigSnippet = ( + updates: WranglerConfigUpdates, + options: WranglerConfigUpdateOptions, +) => { const superseded = options.removeCompatibilityFlags ?? []; + const { main } = updates; return makeCodeSnippet(true, (_unchanged, plus) => plus( @@ -52,8 +62,10 @@ const getTomlConfigSnippet = (options: WranglerConfigUpdateOptions) => { .map((flag) => `"${flag}"`) .join(", ")} from compatibility_flags if present\n` : "" - }compatibility_flags = ["nodejs_compat"] -compatibility_date = "${new Date().toISOString().slice(0, 10)}" + }${main ? `main = "${main}"\n` : ""}compatibility_flags = ["nodejs_compat"] +compatibility_date = "${new Date().toISOString().slice(0, 10)}"${ + options.keepCompatibilityDate ? " # only if not set yet" : "" + } [version_metadata] binding = "CF_VERSION_METADATA"`, @@ -98,7 +110,7 @@ export async function updateWranglerConfig( case ".toml": await showCopyPasteInstructions({ filename: configFile, - codeSnippet: getTomlConfigSnippet(options), + codeSnippet: getTomlConfigSnippet(updates, options), }); break; } @@ -208,7 +220,13 @@ function updateJsoncObject( options: WranglerConfigUpdateOptions = {}, ): void { for (const [key, value] of Object.entries(updates)) { - if (value === null || value === undefined) { + if ( + value === null || + value === undefined || + (key === "compatibility_date" && + options.keepCompatibilityDate && + getObjectProperty(jsonObject, key)) + ) { continue; } diff --git a/packages/cli/src/lib/wizard/sourcemaps/ci.ts b/packages/cli/src/lib/wizard/sourcemaps/ci.ts index 136492b31..9ca085584 100644 --- a/packages/cli/src/lib/wizard/sourcemaps/ci.ts +++ b/packages/cli/src/lib/wizard/sourcemaps/ci.ts @@ -96,7 +96,7 @@ async function configureCI( return; } - // Wrangler's `post` script already runs `sentry:sourcemaps` + // The Wrangler deploy script already runs `sentry:sourcemaps` afterwards if (isCliBasedFlowTool && selectedTool !== "wrangler") { await traceStep("ci-npm-script-setup", setupNpmScriptInCI); } diff --git a/packages/cli/src/lib/wizard/sourcemaps/tools/webpack.ts b/packages/cli/src/lib/wizard/sourcemaps/tools/webpack.ts index 2d8706e88..5a652df36 100644 --- a/packages/cli/src/lib/wizard/sourcemaps/tools/webpack.ts +++ b/packages/cli/src/lib/wizard/sourcemaps/tools/webpack.ts @@ -4,6 +4,7 @@ */ import type { namedTypes as t } from "ast-types"; +import type { ExpressionKind } from "ast-types/lib/gen/kinds.js"; import chalk from "chalk"; import { promises } from "node:fs"; import path from "node:path"; @@ -255,10 +256,18 @@ function addSentryWebpackPlugin( ); if (pluginsProp) { - if (pluginsProp.value.type === "ArrayExpression") { - pluginsProp.value.elements.push(sentryPluginCall); - } else { + const plugins = pluginsProp.value; + if (plugins.type === "ArrayExpression") { + plugins.elements.push(sentryPluginCall); + } else if (isNullish(plugins)) { pluginsProp.value = b.arrayExpression([sentryPluginCall]); + } else { + // A variable or call such as `getPlugins()`: keep its plugins and add + // Sentry after them. + pluginsProp.value = b.arrayExpression([ + b.spreadElement(plugins as ExpressionKind), + sentryPluginCall, + ]); } return true; } @@ -273,6 +282,15 @@ function addSentryWebpackPlugin( return true; } +/** `undefined` or `null`, which leaves no plugins to keep. */ +function isNullish(node: t.Property["value"]): boolean { + return ( + (node.type === "Identifier" && node.name === "undefined") || + node.type === "NullLiteral" || + (node.type === "Literal" && node.value === null) + ); +} + function addSentryWebpackPluginImport(program: t.Program, importPath: string) { const b = recast.types.builders; diff --git a/packages/cli/src/lib/wizard/sourcemaps/tools/wrangler.ts b/packages/cli/src/lib/wizard/sourcemaps/tools/wrangler.ts index b4a10efb9..461ef2dbb 100644 --- a/packages/cli/src/lib/wizard/sourcemaps/tools/wrangler.ts +++ b/packages/cli/src/lib/wizard/sourcemaps/tools/wrangler.ts @@ -24,7 +24,7 @@ import { } from "../../utils/clack/index.js"; import { clack } from "../../utils/clack/prompts.js"; import { hasPackageInstalled } from "../../utils/package-json.js"; -import { NPM } from "../../utils/package-manager.js"; +import { NPM, YARN_V2 } from "../../utils/package-manager.js"; import { addUploadTargetToSentryCliRc } from "./sentry-cli.js"; import type { SourceMapUploadToolConfigurationOptions } from "./types.js"; @@ -35,6 +35,12 @@ const SENTRY_NPM_SCRIPT_NAME = "sentry:sourcemaps"; */ export const DIST_DIR = path.join(".", "dist"); +/** + * A `--var` that sets SENTRY_RELEASE, with `=` or `:` and optional quotes, + * like `SHELL_SPOTLIGHT_VAR_RE` in `lib/wrangler.ts`. + */ +const RELEASE_VAR_RE = /--var(?:=|\s+)["']?SENTRY_RELEASE(?::|=)/; + export async function configureWrangler( options: SourceMapUploadToolConfigurationOptions, ) { @@ -86,17 +92,24 @@ Otherwise, let's proceed with the Wrangler setup.`, } const deployCommand = await getDeployCommand(); - if (!deployCommand) { - return; - } - - const outDir = await getWranglerOutDir(deployCommand); + const outDir = deployCommand + ? await getWranglerOutDir(deployCommand) + : DIST_DIR; await createAndAddSentrySourcemapsScript(outDir); - await writePostDeployCommand(deployCommand); - - await modifyDeployCommand(deployCommand, outDir); + if (deployCommand) { + await modifyDeployCommand(deployCommand, outDir); + await addUploadAfterDeploy(deployCommand); + } else { + const packageManager = await getPackageManager(NPM); + await showCopyPasteInstructions({ + codeSnippet: `${getManualDeployCommand(outDir)} && ${ + packageManager.runScriptCommand + } ${SENTRY_NPM_SCRIPT_NAME}`, + filename: "package.json", + }); + } await addUploadTargetToSentryCliRc(options); await addSentryCliConfig({ authToken: options.authToken }); @@ -238,7 +251,7 @@ async function getDeployCommand(): Promise { `We can only add the ${chalk.cyan( SENTRY_NPM_SCRIPT_NAME, )} script to another \`script\` in your ${chalk.cyan("package.json")}. -Please add it manually to your prod build command.`, +Please add it manually to your deploy command:`, ); return undefined; } @@ -246,12 +259,28 @@ Please add it manually to your prod build command.`, return deployCommand; } -async function writePostDeployCommand(deployCommand: string): Promise { +/** + * Run `sentry:sourcemaps` after `deployCommand`: from its `post` + * script, as the Sentry docs do, or chained onto the deploy script for Yarn + * 2+, which doesn't run `post` scripts. An existing `post` script is + * kept, with the upload added after it. + */ +async function addUploadAfterDeploy(deployCommand: string): Promise { const pkgJson = await getPackageDotJson(); const packageManager = await getPackageManager(NPM); pkgJson.scripts = pkgJson.scripts ?? {}; - pkgJson.scripts[`post${deployCommand}`] = - `${packageManager.runScriptCommand} ${SENTRY_NPM_SCRIPT_NAME}`; + + const scriptName = + packageManager === YARN_V2 ? deployCommand : `post${deployCommand}`; + const existingScript = pkgJson.scripts[scriptName]; + if (existingScript?.includes(SENTRY_NPM_SCRIPT_NAME)) { + return; + } + + const runUpload = `${packageManager.runScriptCommand} ${SENTRY_NPM_SCRIPT_NAME}`; + pkgJson.scripts[scriptName] = existingScript + ? `${existingScript} && ${runUpload}` + : runUpload; await promises.writeFile( path.join(process.cwd(), "package.json"), @@ -259,12 +288,19 @@ async function writePostDeployCommand(deployCommand: string): Promise { ); clack.log.success( - `Added a ${chalk.cyan(`post${deployCommand}`)} script to your ${chalk.cyan( - "package.json", - )}.`, + `${existingScript ? "Updated" : "Added"} the ${chalk.cyan( + scriptName, + )} script in your ${chalk.cyan("package.json")} to upload source maps after each deploy.`, ); } +/** The `wrangler deploy` command to show when the wizard can't edit it. */ +function getManualDeployCommand(outDir: string): string { + return `wrangler deploy --outdir ${quoteShellArg( + outDir, + )} --var SENTRY_RELEASE:${PROPOSE_VERSION} --upload-source-maps`; +} + async function modifyDeployCommand( deployCommand: string, outDir: string, @@ -281,9 +317,7 @@ async function modifyDeployCommand( ); await showCopyPasteInstructions({ - codeSnippet: `wrangler deploy --outdir ${quoteShellArg( - outDir, - )} --var SENTRY_RELEASE:${PROPOSE_VERSION} --upload-source-maps`, + codeSnippet: getManualDeployCommand(outDir), filename: "package.json", }); @@ -305,7 +339,7 @@ async function modifyDeployCommand( ); await showCopyPasteInstructions({ - codeSnippet: oldDeployCommand, + codeSnippet: getManualDeployCommand(outDir), filename: "package.json", }); @@ -338,11 +372,12 @@ export function safeInsertArgsToWranglerDeployCommand( outDir: string, ): string | undefined { // split deployCommand into individual bash commands (potentially separated by &&, ||, >> etc.) - const originalWranglerDeployCommand = getWranglerDeployCommand(deployCommand); + const wranglerDeployCommand = findWranglerDeployCommand(deployCommand); - if (!originalWranglerDeployCommand) { + if (!wranglerDeployCommand) { return undefined; } + const originalWranglerDeployCommand = wranglerDeployCommand.text; const existingArgs = originalWranglerDeployCommand .split(" ") @@ -365,15 +400,22 @@ export function safeInsertArgsToWranglerDeployCommand( // This is how we inject the SENTRY_RELEASE variable, // which is picked up by the CloudFlare SDK. - // multiple --var arguments are allowed, so no need to check for existing --var arguments. - newArgs.push("--var", `SENTRY_RELEASE:${PROPOSE_VERSION}`); - - return deployCommand - .replace( - originalWranglerDeployCommand, - `${originalWranglerDeployCommand} ${newArgs.join(" ")} `, - ) - .trim(); + // Skip it when the script already sets SENTRY_RELEASE, e.g. on a rerun. + if (!RELEASE_VAR_RE.test(originalWranglerDeployCommand)) { + newArgs.push("--var", `SENTRY_RELEASE:${PROPOSE_VERSION}`); + } + + if (newArgs.length === 0) { + return deployCommand; + } + + // Insert at the deploy command's own position: the same text can appear + // earlier in the script, such as in `echo wrangler deploy`. + const end = + wranglerDeployCommand.start + originalWranglerDeployCommand.length; + return `${deployCommand.slice(0, end)} ${newArgs.join(" ")} ${deployCommand.slice( + end, + )}`.trim(); } /** @@ -436,10 +478,11 @@ const COMMAND_SEPARATORS = ["&&", "||", ">>", ">", "<", "|", ";"]; * Split a package script into its individual commands at the operators in * {@link COMMAND_SEPARATORS}. Operators inside quotes or a `$(…)` command * substitution (such as the `| head -n 1` of the release version this - * wizard adds) don't split. The commands are substrings of `script`. + * wizard adds) don't split. Each command is a substring of `script` that + * starts at `start`. */ -function splitShellCommands(script: string): string[] { - const commands: string[] = []; +function splitShellCommands(script: string): { start: number; text: string }[] { + const commands: { start: number; text: string }[] = []; let start = 0; let depth = 0; let quote: string | undefined; @@ -473,29 +516,74 @@ function splitShellCommands(script: string): string[] { ? COMMAND_SEPARATORS.find((op) => script.startsWith(op, i)) : undefined; if (separator) { - commands.push(script.slice(start, i)); + commands.push({ start, text: script.slice(start, i) }); i += separator.length; start = i; continue; } i += 1; } - commands.push(script.slice(start)); + commands.push({ start, text: script.slice(start) }); return commands; } /** + * Package-manager runners that the wizard edits when they come straight + * before `wrangler`, as in `npx wrangler deploy`. Anything else, such as + * runner flags, `cross-env` or `FOO=1`, gets the manual instructions. + */ +const WRANGLER_RUNNERS = new Set(["npx", "pnpm", "yarn", "bunx"]); + +/** + * Where `argv` runs `wrangler`: bare, or right after a runner from + * {@link WRANGLER_RUNNERS}. -1 when it doesn't. + */ +function findWranglerIndex(argv: string[]): number { + if (argv[0] === "wrangler") { + return 0; + } + return WRANGLER_RUNNERS.has(argv[0] ?? "") && argv[1] === "wrangler" ? 1 : -1; +} + +/** + * Wrangler commands with their own `deploy` subcommand, which doesn't take + * the Workers flags this wizard adds. + */ +const NON_WORKER_DEPLOY_COMMANDS = new Set(["pages", "versions"]); + +/** + * The command of `deployCommand` that runs `wrangler deploy`, bare or + * through `npx`, `pnpm`, `yarn` or `bunx` (see {@link findWranglerIndex}). + * `wrangler pages deploy` and `wrangler versions deploy` don't count. + * * Exported for testing */ export function getWranglerDeployCommand( deployCommand: string, ): string | undefined { - return splitShellCommands(deployCommand).find((cmd) => { - const argv = cmd + return findWranglerDeployCommand(deployCommand)?.text; +} + +/** {@link getWranglerDeployCommand}, with where it starts in `deployCommand`. */ +function findWranglerDeployCommand( + deployCommand: string, +): { start: number; text: string } | undefined { + return splitShellCommands(deployCommand).find(({ text }) => { + const argv = text .split(" ") .map((arg) => arg.trim()) .filter(Boolean); - return argv[0] === "wrangler" && argv.includes("deploy"); + const wranglerIndex = findWranglerIndex(argv); + if (wranglerIndex === -1) { + return false; + } + const deployIndex = argv.indexOf("deploy", wranglerIndex + 1); + return ( + deployIndex !== -1 && + !argv + .slice(wranglerIndex + 1, deployIndex) + .some((arg) => NON_WORKER_DEPLOY_COMMANDS.has(arg)) + ); }); } diff --git a/packages/cli/src/lib/wizard/sourcemaps/utils/other-wizards.ts b/packages/cli/src/lib/wizard/sourcemaps/utils/other-wizards.ts index 9cc77bcc9..272a25961 100644 --- a/packages/cli/src/lib/wizard/sourcemaps/utils/other-wizards.ts +++ b/packages/cli/src/lib/wizard/sourcemaps/utils/other-wizards.ts @@ -1,6 +1,7 @@ /** * Point users of a framework that has its own wizard (SvelteKit, React - * Native) to that wizard instead of the generic source maps one. + * Native) to that wizard instead of the generic source maps one, or to its + * guides while this version doesn't have that wizard yet. */ import chalk from "chalk"; @@ -25,22 +26,9 @@ type FrameworkInfo = { frameworkPackage: string; troubleshootingDocsLink: string; sourcemapsDocsLink: string; - wizard: WizardFunction; + integration: "sveltekit" | "reactNative"; }; -/** - * The `sentry wizard -i ` flow. `run.ts` is imported on demand - * because it imports this flow. - */ -function runOtherWizard( - integration: "sveltekit" | "reactNative", -): WizardFunction { - return async (options) => { - const { runWizard } = await import("../../run.js"); - await runWizard({ integration, wizardOptions: options }); - }; -} - const sdkMap: Record = { "@sentry/sveltekit": { frameworkName: "SvelteKit", @@ -49,7 +37,7 @@ const sdkMap: Record = { "https://docs.sentry.io/platforms/javascript/guides/sveltekit/manual-setup/#configure-source-maps-upload", troubleshootingDocsLink: "https://docs.sentry.io/platforms/javascript/guides/sveltekit/sourcemaps/troubleshooting_js/", - wizard: runOtherWizard("sveltekit"), + integration: "sveltekit", }, "@sentry/react-native": { frameworkName: "React Native", @@ -58,7 +46,7 @@ const sdkMap: Record = { "https://docs.sentry.io/platforms/react-native/sourcemaps/", troubleshootingDocsLink: "https://docs.sentry.io/platforms/react-native/troubleshooting/#source-maps", - wizard: runOtherWizard("reactNative"), + integration: "reactNative", }, }; @@ -75,7 +63,14 @@ export async function checkIfMoreSuitableWizardExistsAndAskForRedirect(): Promis return undefined; } - return await askForRedirect(framework.sdkName, framework.info); + // `run.ts` is imported on demand because it imports this flow. + const { hasWizardRunner, runWizard } = await import("../../run.js"); + const { integration } = framework.info; + const wizard: WizardFunction | undefined = hasWizardRunner(integration) + ? (options) => runWizard({ integration, wizardOptions: options }) + : undefined; + + return await askForRedirect(framework.sdkName, framework.info, wizard); } async function checkIfMoreSuitableWizardExists(): Promise< @@ -107,24 +102,29 @@ async function checkIfMoreSuitableWizardExists(): Promise< return { sdkName: installedSdkPackage.name, info }; } +/** + * Recommend the framework's wizard, or its guides when `wizard` is unset + * because this version doesn't have that wizard yet. + */ async function askForRedirect( sdkName: string, - { - frameworkName, - sourcemapsDocsLink, - troubleshootingDocsLink, - wizard, - }: FrameworkInfo, + { frameworkName, sourcemapsDocsLink, troubleshootingDocsLink }: FrameworkInfo, + wizard: WizardFunction | undefined, ): Promise { + const recommendation = wizard + ? `We recommend using our dedicated ${frameworkName} wizard instead of this wizard. +The ${frameworkName} wizard will set up our ${sdkName} SDK and also configure uploading source maps for you. + +If you already tried the ${frameworkName} wizard and it didn't work for you, check out the following guides:` + : `This version of the Sentry CLI doesn't have the ${frameworkName} wizard yet. +We recommend setting up source maps for ${frameworkName} with the following guides instead of this wizard:`; + clack.log.warn( `${chalk.yellow( `It seems like you're using this wizard in a ${frameworkName} project.`, )} -We recommend using our dedicated ${frameworkName} wizard instead of this wizard. -The ${frameworkName} wizard will set up our ${sdkName} SDK and also configure uploading source maps for you. - -If you already tried the ${frameworkName} wizard and it didn't work for you, check out the following guides: +${recommendation} Manual source maps configuration for ${frameworkName}: ${sourcemapsDocsLink} @@ -136,19 +136,29 @@ ${troubleshootingDocsLink} const nextStep = await abortIfCancelled( clack.select<"redirect" | "continue" | "stop">({ - message: `Do you want to run the ${frameworkName} wizard now?`, + message: wizard + ? `Do you want to run the ${frameworkName} wizard now?` + : "How do you want to continue?", options: [ + ...(wizard + ? [ + { + label: "Yes", + value: "redirect" as const, + hint: chalk.green("Recommended"), + }, + ] + : []), { - label: "Yes", - value: "redirect", - hint: chalk.green("Recommended"), - }, - { - label: "No, continue with this wizard", + label: wizard + ? "No, continue with this wizard" + : "Continue with this wizard", value: "continue", }, { - label: "No, I'll check out the guides ", + label: wizard + ? "No, I'll check out the guides " + : "Exit and check out the guides", value: "stop", hint: "Exit this wizard", }, diff --git a/packages/cli/test/lib/wizard/cloudflare/cloudflare-wizard.test.ts b/packages/cli/test/lib/wizard/cloudflare/cloudflare-wizard.test.ts index 755595f07..6cd03eda2 100644 --- a/packages/cli/test/lib/wizard/cloudflare/cloudflare-wizard.test.ts +++ b/packages/cli/test/lib/wizard/cloudflare/cloudflare-wizard.test.ts @@ -1,6 +1,7 @@ import { beforeEach, describe, expect, it, vi } from "vitest"; import { runCloudflareWizard } from "../../../../src/lib/wizard/cloudflare/cloudflare-wizard.js"; +import { updateWranglerConfig } from "../../../../src/lib/wizard/cloudflare/wrangler/update-wrangler-config.js"; import { askShouldReduceDataCollection } from "../../../../src/lib/wizard/utils/data-collection.js"; import { getPackageVersion } from "../../../../src/lib/wizard/utils/package-json.js"; import type { WizardOptions } from "../../../../src/lib/wizard/utils/types.js"; @@ -95,4 +96,13 @@ describe("runCloudflareWizard", () => { expect(askShouldReduceDataCollection).not.toHaveBeenCalled(); }); + + it("keeps the Worker's existing compatibility_date", async () => { + await runCloudflareWizard(options); + + expect(updateWranglerConfig).toHaveBeenCalledWith( + expect.objectContaining({ compatibility_date: expect.any(String) }), + expect.objectContaining({ keepCompatibilityDate: true }), + ); + }); }); diff --git a/packages/cli/test/lib/wizard/cloudflare/get-entry-point-from-wrangler-config.test.ts b/packages/cli/test/lib/wizard/cloudflare/get-entry-point-from-wrangler-config.test.ts index b5fdbac47..84f8ef72d 100644 --- a/packages/cli/test/lib/wizard/cloudflare/get-entry-point-from-wrangler-config.test.ts +++ b/packages/cli/test/lib/wizard/cloudflare/get-entry-point-from-wrangler-config.test.ts @@ -93,6 +93,12 @@ compatibility_date = "2024-01-01"`, expect(result).toBeUndefined(); }); + it("returns undefined if main is empty in wrangler.json", () => { + fs.writeFileSync(path.join(tmpDir, "wrangler.json"), `{ "main": "" }`); + + expect(getEntryPointFromWranglerConfig()).toBeUndefined(); + }); + it("returns undefined if JSON parsing fails", () => { fs.writeFileSync(path.join(tmpDir, "wrangler.json"), "{ invalid json }"); diff --git a/packages/cli/test/lib/wizard/cloudflare/sdk-setup.test.ts b/packages/cli/test/lib/wizard/cloudflare/sdk-setup.test.ts index 4417368ce..cc57c882b 100644 --- a/packages/cli/test/lib/wizard/cloudflare/sdk-setup.test.ts +++ b/packages/cli/test/lib/wizard/cloudflare/sdk-setup.test.ts @@ -73,31 +73,56 @@ describe("createSentryInitFile", () => { vi.restoreAllMocks(); }); - it("creates a new default entry point file", async () => { + it("creates a default entry point and wraps it with Sentry", async () => { const template = 'export default { async fetch() { return new Response("ᕕ(⌐■_■)ᕗ ♪♬"); } }'; - const getCloudflareWorkerTemplateWithHandlerSpy = vi - .spyOn(templates, "getCloudflareWorkerTemplateWithHandler") - .mockReturnValue(template); + vi.spyOn( + templates, + "getCloudflareWorkerTemplateWithHandler", + ).mockReturnValue(template); await createSentryInitFile(testDsn, testFeatures, false); const expectedPath = path.join(tmpDir, "src/index.ts"); const content = fs.readFileSync(expectedPath, "utf-8"); - expect(clackMocks.info).toHaveBeenCalledWith( - "No entry point found in wrangler config, creating a new one.", - ); - expect(fs.existsSync(expectedPath)).toBe(true); - expect(content).toBe(template); expect(clackMocks.success).toHaveBeenCalledWith("Created src/index.ts."); - expect(getCloudflareWorkerTemplateWithHandlerSpy).toHaveBeenCalled(); + expect(content).toContain("Sentry.withSentry("); + expect(content).toContain(testDsn); + expect(content).toContain("ᕕ(⌐■_■)ᕗ ♪♬"); + }); + + it("wraps the starter worker template", async () => { + await createSentryInitFile(testDsn, testFeatures, false); + + const content = fs.readFileSync(path.join(tmpDir, "src/index.ts"), "utf-8"); + + expect(content).toContain('from "@sentry/cloudflare"'); + expect(content).toContain("Sentry.withSentry("); + expect(clackMocks.warn).not.toHaveBeenCalled(); + }); + + it("wraps an existing default entry point instead of overwriting it", async () => { + const existing = + 'export default { async fetch() { return new Response("mine"); } }'; + fs.mkdirSync(path.join(tmpDir, "src")); + fs.writeFileSync(path.join(tmpDir, "src/index.ts"), existing); + + await createSentryInitFile(testDsn, testFeatures, false); + + const content = fs.readFileSync(path.join(tmpDir, "src/index.ts"), "utf-8"); + expect(content).toContain('"mine"'); + expect(content).toContain("Sentry.withSentry("); }); describe("when entry point is found in wrangler config", () => { describe("and the entry point file exists", () => { - beforeEach(async () => { - await createSentryInitFile(testDsn, testFeatures, false); + beforeEach(() => { + fs.mkdirSync(path.join(tmpDir, "src")); + fs.writeFileSync( + path.join(tmpDir, defaultEntryPoint), + "export default { async fetch() { return new Response(); } }", + ); getEntryPointFromWranglerConfigMock.mockReturnValue(defaultEntryPoint); }); @@ -198,25 +223,41 @@ describe("createSentryInitFile", () => { }); }); - describe("and the entry point file does not exist", () => { - it("does not throw an error", async () => { - vi.spyOn(wrapWorker, "wrapWorkerWithSentry").mockResolvedValue( - undefined, - ); + it("writes a JavaScript starter worker to a missing .js entry point", async () => { + getEntryPointFromWranglerConfigMock.mockReturnValue("src/worker.js"); + + await createSentryInitFile(testDsn, testFeatures, false); + + const content = fs.readFileSync( + path.join(tmpDir, "src/worker.js"), + "utf-8", + ); + expect(content).toContain("Sentry.withSentry("); + expect(content).not.toContain("satisfies"); + expect(content).not.toContain("Promise"); + }); - await expect( - createSentryInitFile(testDsn, testFeatures, false), - ).resolves.not.toThrow(); + describe("and the entry point file does not exist", () => { + beforeEach(() => { + getEntryPointFromWranglerConfigMock.mockReturnValue("src/worker.ts"); }); - it("does not call wrapWorkerWithSentry", async () => { + it("creates the configured entry point and wraps it", async () => { const wrapWorkerWithSentrySpy = vi .spyOn(wrapWorker, "wrapWorkerWithSentry") .mockResolvedValue(undefined); await createSentryInitFile(testDsn, testFeatures, false); - expect(wrapWorkerWithSentrySpy).not.toHaveBeenCalled(); + const createdPath = path.join(tmpDir, "src/worker.ts"); + expect(fs.existsSync(createdPath)).toBe(true); + expect(fs.existsSync(path.join(tmpDir, defaultEntryPoint))).toBe(false); + expect(wrapWorkerWithSentrySpy).toHaveBeenCalledWith( + createdPath, + testDsn, + testFeatures, + false, + ); }); }); }); diff --git a/packages/cli/test/lib/wizard/cloudflare/update-wrangler-config.test.ts b/packages/cli/test/lib/wizard/cloudflare/update-wrangler-config.test.ts index 463dba558..415c742e5 100644 --- a/packages/cli/test/lib/wizard/cloudflare/update-wrangler-config.test.ts +++ b/packages/cli/test/lib/wizard/cloudflare/update-wrangler-config.test.ts @@ -3,6 +3,7 @@ import fs from "node:fs"; import path from "node:path"; import os from "node:os"; import { updateWranglerConfig } from "../../../../src/lib/wizard/cloudflare/wrangler/update-wrangler-config.js"; +import { showCopyPasteInstructions } from "../../../../src/lib/wizard/utils/clack/index.js"; const { clackMocks } = vi.hoisted(() => { return { @@ -19,6 +20,10 @@ const { clackMocks } = vi.hoisted(() => { }); vi.mock("@clack/prompts", () => clackMocks); +vi.mock("../../../../src/lib/wizard/utils/clack/index.js", async () => ({ + ...(await vi.importActual("../../../../src/lib/wizard/utils/clack/index.js")), + showCopyPasteInstructions: vi.fn(), +})); describe("updateWranglerConfig", () => { const fixturesDir = path.join(__dirname, "fixtures", "wrangler"); @@ -95,6 +100,40 @@ describe("updateWranglerConfig", () => { expect(parsed["compatibility_date"]).toEqual("1337-01-01"); }); + it("keeps an existing compatibility_date when asked to", async () => { + fs.writeFileSync( + path.join(tmpDir, "wrangler.json"), + '{ "name": "w", "compatibility_date": "2024-01-01" }', + ); + + await updateWranglerConfig( + { compatibility_date: "1337-01-01", main: "src/index.ts" }, + { keepCompatibilityDate: true }, + ); + + const parsed = JSON.parse(readResult("wrangler.json")) as Record< + string, + unknown + >; + expect(parsed["compatibility_date"]).toBe("2024-01-01"); + expect(parsed["main"]).toBe("src/index.ts"); + }); + + it("adds compatibility_date when asked to keep one the config doesn't have", async () => { + fs.writeFileSync(path.join(tmpDir, "wrangler.json"), '{ "name": "w" }'); + + await updateWranglerConfig( + { compatibility_date: "1337-01-01" }, + { keepCompatibilityDate: true }, + ); + + const parsed = JSON.parse(readResult("wrangler.json")) as Record< + string, + unknown + >; + expect(parsed["compatibility_date"]).toBe("1337-01-01"); + }); + it("merges array fields in JSON config", async () => { copyFixture("wrangler-with-flags.json", "wrangler.json"); @@ -276,4 +315,44 @@ describe("updateWranglerConfig", () => { ); }); }); + + describe("TOML format", () => { + function shownSnippet(): string { + const [args] = vi.mocked(showCopyPasteInstructions).mock.calls[0] ?? []; + return args?.codeSnippet ?? ""; + } + + it("tells the user to set main when the update includes it", async () => { + fs.writeFileSync(path.join(tmpDir, "wrangler.toml"), 'name = "w"\n'); + + await updateWranglerConfig({ + main: "src/index.ts", + compatibility_flags: ["nodejs_compat"], + }); + + expect(shownSnippet()).toContain('main = "src/index.ts"'); + }); + + it("tells the user to keep their compatibility_date when asked to", async () => { + fs.writeFileSync(path.join(tmpDir, "wrangler.toml"), 'name = "w"\n'); + + await updateWranglerConfig( + { compatibility_flags: ["nodejs_compat"] }, + { keepCompatibilityDate: true }, + ); + + expect(shownSnippet()).toMatch( + /compatibility_date = .* # only if not set yet/, + ); + }); + + it("leaves main out when the update doesn't include it", async () => { + fs.writeFileSync(path.join(tmpDir, "wrangler.toml"), 'name = "w"\n'); + + await updateWranglerConfig({ compatibility_flags: ["nodejs_compat"] }); + + expect(shownSnippet()).not.toContain("main ="); + expect(shownSnippet()).toContain("compatibility_flags"); + }); + }); }); diff --git a/packages/cli/test/lib/wizard/sourcemaps/tools/webpack.test.ts b/packages/cli/test/lib/wizard/sourcemaps/tools/webpack.test.ts index b61d8108d..38e3cc85e 100644 --- a/packages/cli/test/lib/wizard/sourcemaps/tools/webpack.test.ts +++ b/packages/cli/test/lib/wizard/sourcemaps/tools/webpack.test.ts @@ -310,4 +310,32 @@ describe("modifyWebpackConfig", () => { expect(fileContent).toContain('url: "https://santry.io/"'); expect(addedCode).toBe(true); }); + + it.each([ + ["a variable", "existingPlugins"], + ["a call", "getPlugins()"], + ])("keeps the plugins when plugins is %s", async (_kind, plugins) => { + updateFileContent(`module.exports = { + entry: "./src/index.js", + plugins: ${plugins}, +};`); + + const addedCode = await modifyWebpackConfig( + "", + { + authToken: "", + orgSlug: "my-org", + projectSlug: "my-project", + selfHosted: false, + url: "https://sentry.io/", + }, + "@sentry/bundler-plugins/webpack", + ); + + expect(addedCode).toBe(true); + const fileContent = writeFileSpy.mock.calls[0]?.[1]; + expect(fileContent).toContain( + `plugins: [...${plugins}, sentryWebpackPlugin(`, + ); + }); }); diff --git a/packages/cli/test/lib/wizard/sourcemaps/tools/wrangler-flow.test.ts b/packages/cli/test/lib/wizard/sourcemaps/tools/wrangler-flow.test.ts index 0a749e294..a7b39ccb9 100644 --- a/packages/cli/test/lib/wizard/sourcemaps/tools/wrangler-flow.test.ts +++ b/packages/cli/test/lib/wizard/sourcemaps/tools/wrangler-flow.test.ts @@ -1,18 +1,27 @@ import { promises } from "node:fs"; -import { describe, expect, it, vi } from "vitest"; +import { beforeEach, describe, expect, it, vi } from "vitest"; import { WizardExitError } from "../../../../../src/lib/errors.js"; +import { addUploadTargetToSentryCliRc } from "../../../../../src/lib/wizard/sourcemaps/tools/sentry-cli.js"; import { configureWrangler } from "../../../../../src/lib/wizard/sourcemaps/tools/wrangler.js"; -import { getPackageDotJson } from "../../../../../src/lib/wizard/utils/clack/index.js"; +import { + addSentryCliConfig, + getPackageDotJson, + getPackageManager, + showCopyPasteInstructions, +} from "../../../../../src/lib/wizard/utils/clack/index.js"; +import type { PackageDotJson } from "../../../../../src/lib/wizard/utils/package-json.js"; +import { + NPM, + YARN_V2, +} from "../../../../../src/lib/wizard/utils/package-manager.js"; const { selectMock } = vi.hoisted(() => ({ selectMock: vi.fn(), })); -const writeFileSpy = vi - .spyOn(promises, "writeFile") - .mockImplementation(() => Promise.resolve()); +const writeFileSpy = vi.spyOn(promises, "writeFile"); vi.mock("@clack/prompts", () => ({ log: { info: vi.fn(), warn: vi.fn(), success: vi.fn() }, @@ -29,6 +38,11 @@ vi.mock("../../../../../src/lib/wizard/utils/clack/index.js", async () => ({ installPackage: vi.fn().mockResolvedValue(undefined), addSentryCliConfig: vi.fn().mockResolvedValue(undefined), getPackageDotJson: vi.fn(), + getPackageManager: vi.fn(), + showCopyPasteInstructions: vi.fn().mockResolvedValue(undefined), +})); +vi.mock("../../../../../src/lib/wizard/sourcemaps/tools/sentry-cli.js", () => ({ + addUploadTargetToSentryCliRc: vi.fn().mockResolvedValue(undefined), })); const options = { @@ -39,17 +53,98 @@ const options = { url: "https://sentry.io/", }; +/** The package.json the wizard reads, updated by each write. */ +let pkg: PackageDotJson; + +function usePackageJson(scripts: Record): void { + pkg = { scripts }; + vi.mocked(getPackageDotJson).mockImplementation(() => + Promise.resolve(structuredClone(pkg)), + ); +} + describe("configureWrangler", () => { + beforeEach(() => { + vi.clearAllMocks(); + vi.mocked(getPackageManager).mockResolvedValue(NPM); + writeFileSpy.mockImplementation((_path, data) => { + if (typeof data === "string") { + pkg = JSON.parse(data) as PackageDotJson; + } + return Promise.resolve(); + }); + }); + it("exits when the user keeps the existing sentry:sourcemaps script", async () => { - vi.mocked(getPackageDotJson).mockResolvedValue({ - scripts: { - deploy: "wrangler deploy", - "sentry:sourcemaps": "echo existing", - }, + usePackageJson({ + deploy: "wrangler deploy", + "sentry:sourcemaps": "echo existing", }); selectMock.mockResolvedValueOnce(false); await expect(configureWrangler(options)).rejects.toThrow(WizardExitError); expect(writeFileSpy).not.toHaveBeenCalled(); }); + + it("uploads from a new postdeploy script", async () => { + usePackageJson({ deploy: "wrangler deploy" }); + + await configureWrangler(options); + + expect(pkg.scripts?.["postdeploy"]).toBe("npm run sentry:sourcemaps"); + expect(pkg.scripts?.["deploy"]).toContain("--upload-source-maps"); + }); + + it("keeps an existing postdeploy script and uploads after it", async () => { + usePackageJson({ deploy: "wrangler deploy", postdeploy: "echo done" }); + + await configureWrangler(options); + + expect(pkg.scripts?.["postdeploy"]).toBe( + "echo done && npm run sentry:sourcemaps", + ); + }); + + it("chains the upload onto the deploy script for Yarn 2+", async () => { + vi.mocked(getPackageManager).mockResolvedValue(YARN_V2); + usePackageJson({ deploy: "wrangler deploy" }); + + await configureWrangler(options); + + expect(pkg.scripts?.["postdeploy"]).toBeUndefined(); + expect(pkg.scripts?.["deploy"]).toMatch( + /^wrangler deploy .*--upload-source-maps.* && yarn sentry:sourcemaps$/, + ); + }); + + it("edits a deploy script that runs wrangler through npx", async () => { + usePackageJson({ deploy: "npx wrangler deploy" }); + + await configureWrangler(options); + + expect(pkg.scripts?.["deploy"]).toMatch( + /^npx wrangler deploy --outdir '.*' --upload-source-maps --var SENTRY_RELEASE:/, + ); + }); + + it("still sets up the upload when there is no deploy script", async () => { + usePackageJson({ build: "tsc" }); + selectMock.mockResolvedValueOnce("none"); + + await configureWrangler(options); + + expect(pkg.scripts?.["sentry:sourcemaps"]).toContain( + "sentry sourcemap upload", + ); + expect(pkg.scripts?.["build"]).toBe("tsc"); + expect(addUploadTargetToSentryCliRc).toHaveBeenCalledWith(options); + expect(addSentryCliConfig).toHaveBeenCalledWith({ authToken: "token" }); + expect(showCopyPasteInstructions).toHaveBeenCalledWith( + expect.objectContaining({ + codeSnippet: expect.stringMatching( + /^wrangler deploy --outdir .* --upload-source-maps && npm run sentry:sourcemaps$/, + ), + }), + ); + }); }); diff --git a/packages/cli/test/lib/wizard/sourcemaps/tools/wrangler.test.ts b/packages/cli/test/lib/wizard/sourcemaps/tools/wrangler.test.ts index a0824dc86..9bfea22c9 100644 --- a/packages/cli/test/lib/wizard/sourcemaps/tools/wrangler.test.ts +++ b/packages/cli/test/lib/wizard/sourcemaps/tools/wrangler.test.ts @@ -51,6 +51,17 @@ describe("getSentryCliCommand", () => { }); describe("safeInsertArgsToWranglerDeployCommand", () => { + it("adds the args to the deploy command, not to earlier text that matches it", () => { + const result = safeInsertArgsToWranglerDeployCommand( + "echo Running wrangler deploy && wrangler deploy", + "dist", + ); + + expect(result).toMatch( + /^echo Running wrangler deploy && wrangler deploy --outdir 'dist' --upload-source-maps --var SENTRY_RELEASE:/, + ); + }); + it("correctly inserts args into default command", () => { const newCommand = safeInsertArgsToWranglerDeployCommand( "wrangler deploy", @@ -138,6 +149,30 @@ describe("safeInsertArgsToWranglerDeployCommand", () => { ); }); + it("leaves a deploy command that already has every arg unchanged on a rerun", () => { + const once = safeInsertArgsToWranglerDeployCommand( + "wrangler deploy && echo done", + "dist", + ); + + expect(once).toBeDefined(); + expect(safeInsertArgsToWranglerDeployCommand(once ?? "", "dist")).toBe( + once, + ); + }); + + it.each([ + "--var=SENTRY_RELEASE:1.0.0", + "--var SENTRY_RELEASE=1.0.0", + "--var=SENTRY_RELEASE=1.0.0", + `--var "SENTRY_RELEASE:1.0.0"`, + "--var 'SENTRY_RELEASE=1.0.0'", + ])("keeps an existing %s arg", (arg) => { + expect( + safeInsertArgsToWranglerDeployCommand(`wrangler deploy ${arg}`, "dist"), + ).toBe(`wrangler deploy ${arg} --outdir 'dist' --upload-source-maps`); + }); + it.each([ "notwrangler deploy", "wrangler dev", @@ -201,6 +236,47 @@ describe("findOutDir", () => { }); describe("getWranglerDeployCommand", () => { + it.each([ + "npx wrangler deploy", + "pnpm wrangler deploy", + "yarn wrangler deploy", + "bunx wrangler deploy", + ])("finds wrangler deploy run through a runner: %s", (command) => { + expect(getWranglerDeployCommand(`tsc && ${command}`)?.trim()).toBe(command); + expect(safeInsertArgsToWranglerDeployCommand(command, "dist")).toBe( + `${command} --outdir 'dist' --upload-source-maps --var SENTRY_RELEASE:$(sentry release propose-version | head -n 1)`, + ); + }); + + it.each([ + "wrangler pages deploy ./public", + "npx wrangler pages deploy", + "yarn wrangler versions deploy", + "pnpm exec wrangler deploy", + "pnpm dlx wrangler deploy", + "bun x wrangler deploy", + "npx -y wrangler deploy", + "npx wrangler@3 deploy", + "npx -p wrangler wrangler deploy", + "pnpm -C wrangler deploy", + "pnpm --filter wrangler deploy", + "pnpm -w wrangler deploy", + "yarn --cwd wrangler deploy", + "yarn -p wrangler deploy", + "cross-env NODE_ENV=production wrangler deploy", + "cross-env NODE_ENV=production yarn --cwd wrangler deploy", + "FOO=1 wrangler deploy", + ])("leaves %s to the manual instructions", (command) => { + expect(getWranglerDeployCommand(command)).toBeUndefined(); + expect( + safeInsertArgsToWranglerDeployCommand(command, "dist"), + ).toBeUndefined(); + }); + + it("ignores commands that only mention wrangler deploy", () => { + expect(getWranglerDeployCommand("echo wrangler deploy")).toBeUndefined(); + }); + it("returns the deploy command", () => { const deployCommand = getWranglerDeployCommand( "wrangler deploy --outdir someplace", diff --git a/packages/cli/test/lib/wizard/sourcemaps/utils/other-wizards.test.ts b/packages/cli/test/lib/wizard/sourcemaps/utils/other-wizards.test.ts new file mode 100644 index 000000000..6cec99b3b --- /dev/null +++ b/packages/cli/test/lib/wizard/sourcemaps/utils/other-wizards.test.ts @@ -0,0 +1,69 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; + +import { + hasWizardRunner, + runWizard, +} from "../../../../../src/lib/wizard/run.js"; +import { checkIfMoreSuitableWizardExistsAndAskForRedirect } from "../../../../../src/lib/wizard/sourcemaps/utils/other-wizards.js"; +import { getPackageDotJson } from "../../../../../src/lib/wizard/utils/clack/index.js"; +import type { WizardOptions } from "../../../../../src/lib/wizard/utils/types.js"; + +const { selectMock } = vi.hoisted(() => ({ selectMock: vi.fn() })); + +vi.mock("@clack/prompts", () => ({ + log: { warn: vi.fn() }, + select: selectMock, + isCancel: vi.fn().mockReturnValue(false), +})); +vi.mock("../../../../../src/lib/wizard/utils/clack/index.js", async () => ({ + ...(await vi.importActual( + "../../../../../src/lib/wizard/utils/clack/index.js", + )), + getPackageDotJson: vi.fn(), +})); +vi.mock("../../../../../src/lib/wizard/run.js", () => ({ + hasWizardRunner: vi.fn(), + runWizard: vi.fn().mockResolvedValue(undefined), +})); + +type SelectArgs = { options: { value: string }[] }; + +function offeredChoices(): string[] { + const [args] = (selectMock.mock.calls[0] ?? []) as [SelectArgs?]; + return args?.options.map((option) => option.value) ?? []; +} + +describe("checkIfMoreSuitableWizardExistsAndAskForRedirect", () => { + beforeEach(() => { + vi.clearAllMocks(); + vi.mocked(getPackageDotJson).mockResolvedValue({ + dependencies: { "@sentry/sveltekit": "^10", "@sveltejs/kit": "^2" }, + }); + }); + + it("offers the framework wizard when this version has it", async () => { + vi.mocked(hasWizardRunner).mockReturnValue(true); + selectMock.mockResolvedValueOnce("redirect"); + + const wizard = await checkIfMoreSuitableWizardExistsAndAskForRedirect(); + const options = { telemetryEnabled: false } as WizardOptions; + await wizard?.(options); + + expect(offeredChoices()).toEqual(["redirect", "continue", "stop"]); + expect(runWizard).toHaveBeenCalledWith({ + integration: "sveltekit", + wizardOptions: options, + }); + }); + + it("only offers to continue or stop when this version lacks the wizard", async () => { + vi.mocked(hasWizardRunner).mockReturnValue(false); + selectMock.mockResolvedValueOnce("continue"); + + const wizard = await checkIfMoreSuitableWizardExistsAndAskForRedirect(); + + expect(offeredChoices()).toEqual(["continue", "stop"]); + expect(wizard).toBeUndefined(); + expect(runWizard).not.toHaveBeenCalled(); + }); +});