Repository navigation
feat(cli): add source maps and Cloudflare to sentry wizard #2529
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
+7,631
−10
Open
Changes from all commits
Commits
Show all changes
27 commits
Select commit
Hold shift + click to select a range
949060d
feat(cli): add sentry wizard with Next.js
sentry-junior[bot] 76e162b
feat(cli): add the wizard's shared AST and URL helpers
sentry-junior[bot] 0113841
feat(cli): reject the wizard's removed sign-up flags
sentry-junior[bot] 7e5f894
Merge branch 'feat/cli-wizard-scaffold' into feat/cli-wizard-shared-a…
sentry-junior[bot] f230698
feat(cli): add source maps and Cloudflare to sentry wizard
sentry-junior[bot] da594ec
Merge origin/feat/cli-wizard-shared-ast-helpers into feat/cli-wizard-…
sentry-junior[bot] 94377df
feat(cli): read wizard source map upload target from .sentryclirc
sentry-junior[bot] 0c11351
test(cli): list the Cloudflare wizard fixtures as unchecked TypeScript
sentry-junior[bot] 39e20d5
fix(cli): address review findings in sentry wizard
sentry-junior[bot] c4786b3
Merge branch 'feat/cli-wizard-scaffold' into feat/cli-wizard-shared-a…
sentry-junior[bot] e40669b
feat(cli): write the self-hosted URL to .sentryclirc in the wizard
sentry-junior[bot] 2c98751
refactor(cli): reuse existing CLI helpers in the wizard AST utils
sentry-junior[bot] ac6b75d
feat(cli): use positionals and existing CLI flags in sentry wizard
sentry-junior[bot] 4c93aa8
fix(cli): use the credential host for the project issues URL
sentry-junior[bot] 2f2f91a
fix(mcp): regenerate the chart app after the for…of conversion
sentry-junior[bot] f0a48de
Merge remote-tracking branch 'origin/feat/cli-wizard-scaffold' into f…
sentry-junior[bot] 553f2a9
fix(cli): update the source maps and Cloudflare wizards for the new w…
sentry-junior[bot] e99e91c
fix(cli): don't add a second source map upload when the build script …
sentry-junior[bot] 5b0ee00
fix(cli): use the shared sentry-cli.ts from the Nuxt and Angular wizards
sentry-junior[bot] 5bad502
Merge remote-tracking branch 'origin/main' into feat/cli-wizard-sourc…
sentry-junior[bot] 8506fd0
fix(cli): sync sentry-cli and Angular source map tools with #2525
sentry-junior[bot] c438f13
fix(cli): fix small bugs in the source maps and Cloudflare wizards
sentry-junior[bot] f067cc1
Merge remote-tracking branch 'origin/main' into feat/cli-wizard-sourc…
sentry-junior[bot] f3053fe
fix(cli): drop the redundant inject step from the sentry:sourcemaps s…
sentry-junior[bot] 03510b3
docs(cli): say the wizard's source map script only runs the upload
sentry-junior[bot] 62880e2
Merge remote-tracking branch 'origin/main' into feat/cli-wizard-sourc…
sentry-junior[bot] 453ef22
Merge remote-tracking branch 'origin/main' into feat/cli-wizard-sourc…
sentry-junior[bot] File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
191 changes: 191 additions & 0 deletions
191
packages/cli/src/lib/wizard/cloudflare/cloudflare-wizard.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,191 @@ | ||
| /** | ||
| * The Cloudflare Workers setup wizard: installs `@sentry/cloudflare`, wraps | ||
| * the worker with `Sentry.withSentry()`, and adds the compatibility flags | ||
| * and version metadata binding the SDK needs to the Wrangler config. | ||
| */ | ||
|
|
||
| import chalk from "chalk"; | ||
|
|
||
| import { traceStep, withTelemetry } from "../telemetry.js"; | ||
| import { abortIfSpotlightNotSupported } from "../utils/abort-if-sportlight-not-supported.js"; | ||
| import { | ||
| confirmContinueIfNoOrDirtyGitRepo, | ||
| ensurePackageIsInstalled, | ||
| featureSelectionPrompt, | ||
| getOrAskForProjectData, | ||
| getPackageDotJson, | ||
| installPackage, | ||
| printSdkV11MigrationGuideIfOutdated, | ||
| printWelcome, | ||
| runPrettierIfInstalled, | ||
| } from "../utils/clack/index.js"; | ||
| import { offerProjectScopedMcpConfig } from "../utils/clack/mcp-config.js"; | ||
| import { clack } from "../utils/clack/prompts.js"; | ||
| import { | ||
| askShouldReduceDataCollection, | ||
| sdkSupportsDataCollection, | ||
| } from "../utils/data-collection.js"; | ||
| import { debug } from "../utils/debug.js"; | ||
| import { warnIfNodeVersionUnsupportedBySdkV11 } from "../utils/node-version.js"; | ||
| import { | ||
| getPackageVersion, | ||
| hasPackageInstalled, | ||
| } from "../utils/package-json.js"; | ||
| import type { WizardOptions } from "../utils/types.js"; | ||
| import { createSentryInitFile } from "./sdk-setup.js"; | ||
| import { ensureWranglerConfig } from "./wrangler/ensure-wrangler-config.js"; | ||
| import { | ||
| defaultEntryPoint, | ||
| getEntryPointFromWranglerConfig, | ||
| } from "./wrangler/get-entry-point-from-wrangler-config.js"; | ||
| import { updateWranglerConfig } from "./wrangler/update-wrangler-config.js"; | ||
|
|
||
| /** The `@sentry/cloudflare` range the wizard installs. */ | ||
| const SDK_INSTALL_RANGE = "^11"; | ||
|
|
||
| /** Run the Cloudflare wizard (`sentry wizard -i cloudflare`). */ | ||
| export async function runCloudflareWizard( | ||
| options: WizardOptions, | ||
| ): Promise<void> { | ||
| return await withTelemetry( | ||
| { | ||
| enabled: options.telemetryEnabled, | ||
| integration: "cloudflare", | ||
| wizardOptions: options, | ||
| }, | ||
| () => runCloudflareWizardWithTelemetry(options), | ||
| ); | ||
| } | ||
|
|
||
| async function runCloudflareWizardWithTelemetry( | ||
| options: WizardOptions, | ||
| ): Promise<void> { | ||
| const { telemetryEnabled, forceInstall } = options; | ||
|
|
||
| printWelcome({ | ||
| wizardName: "Sentry Cloudflare Wizard", | ||
| telemetryEnabled, | ||
| }); | ||
|
|
||
| warnIfNodeVersionUnsupportedBySdkV11(); | ||
|
|
||
| await confirmContinueIfNoOrDirtyGitRepo({ | ||
| ignoreGitChanges: options.ignoreGitChanges, | ||
| cwd: undefined, | ||
| }); | ||
|
|
||
| const packageJson = await getPackageDotJson(); | ||
|
|
||
| await ensurePackageIsInstalled(packageJson, "wrangler", "Cloudflare"); | ||
|
|
||
| traceStep("Ensure Wrangler config", () => { | ||
| ensureWranglerConfig(); | ||
| }); | ||
|
|
||
| const projectData = await getOrAskForProjectData( | ||
| options, | ||
| "node-cloudflare-workers", | ||
| ); | ||
|
|
||
| if (projectData.spotlight) { | ||
| return await abortIfSpotlightNotSupported("Cloudflare"); | ||
| } | ||
|
|
||
| const { selectedProject } = projectData; | ||
|
|
||
| printSdkV11MigrationGuideIfOutdated("@sentry/cloudflare", packageJson); | ||
|
|
||
| await installPackage({ | ||
| packageName: `@sentry/cloudflare@${SDK_INSTALL_RANGE}`, | ||
| packageNameDisplayLabel: "@sentry/cloudflare", | ||
| alreadyInstalled: hasPackageInstalled("@sentry/cloudflare", 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/cloudflare", | ||
| await getPackageDotJson(), | ||
| ); | ||
|
|
||
| const selectedFeatures = await featureSelectionPrompt([ | ||
| { | ||
| id: "performance", | ||
| prompt: `Do you want to enable ${chalk.bold( | ||
| "Tracing", | ||
| )} to track the performance of your application?`, | ||
| enabledHint: "recommended", | ||
| }, | ||
| ] as const); | ||
|
|
||
| // 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, SDK_INSTALL_RANGE) && | ||
| (await askShouldReduceDataCollection()); | ||
|
cursor[bot] marked this conversation as resolved.
Resolved
|
||
|
|
||
| await traceStep("Create Sentry initialization", async () => { | ||
| try { | ||
| await createSentryInitFile( | ||
| selectedProject.keys[0].dsn.public, | ||
| selectedFeatures, | ||
| reduceDataCollection, | ||
| ); | ||
| } catch (e) { | ||
| clack.log.warn( | ||
| "Could not automatically set up Sentry initialization. Please set it up manually using instructions from https://docs.sentry.io/platforms/javascript/guides/cloudflare/", | ||
| ); | ||
| debug(e); | ||
| } | ||
| }); | ||
|
sentry-junior[bot] marked this conversation as resolved.
Resolved
|
||
|
|
||
| const mainFile = getEntryPointFromWranglerConfig(); | ||
|
|
||
| await traceStep("Update Wrangler config with Sentry requirements", () => | ||
| updateWranglerConfig( | ||
| { | ||
| ...(mainFile ? {} : { main: defaultEntryPoint }), | ||
| // The SDK needs Node.js compatibility. `nodejs_compat` is a superset of | ||
| // the `nodejs_als` flag older setups used, and the only one SDK v11 accepts. | ||
| compatibility_flags: ["nodejs_compat"], | ||
| compatibility_date: new Date().toISOString().slice(0, 10), | ||
|
sentry-junior[bot] marked this conversation as resolved.
Resolved
|
||
| version_metadata: { | ||
| binding: "CF_VERSION_METADATA", | ||
| }, | ||
| }, | ||
| { removeCompatibilityFlags: ["nodejs_als"] }, | ||
| ), | ||
| ); | ||
|
|
||
| await runPrettierIfInstalled({ cwd: undefined }); | ||
|
|
||
| // Offer optional project-scoped MCP config for Sentry with org and project scope | ||
| await offerProjectScopedMcpConfig( | ||
| selectedProject.organization.slug, | ||
| selectedProject.slug, | ||
| ); | ||
|
|
||
| clack.outro(buildOutroMessage()); | ||
| } | ||
|
|
||
| /** The closing message, with the next steps. */ | ||
| function buildOutroMessage(): string { | ||
| return ` | ||
| ${chalk.green( | ||
| "Sentry has been successfully configured for your Cloudflare project.", | ||
| )} | ||
| ${chalk.dim("Next steps:")} | ||
| ${chalk.dim("1. Wrap your worker with Sentry as instructed above")} | ||
| ${chalk.dim("2. Deploy your application with:")} ${chalk.cyan( | ||
| "wrangler deploy", | ||
| )} | ||
| ${chalk.dim("3. Trigger an error to test Sentry integration")} | ||
| ${chalk.cyan( | ||
| `To learn more about using Sentry with Cloudflare, visit: | ||
| https://docs.sentry.io/platforms/javascript/guides/cloudflare/`, | ||
| )} | ||
| `; | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,95 @@ | ||
| /** | ||
| * Write the Sentry initialization into the worker entry point: wrap an | ||
| * existing handler, or create an entry point when the Wrangler config names | ||
| * none. | ||
| */ | ||
|
|
||
| import chalk from "chalk"; | ||
| import { existsSync, promises } from "node:fs"; | ||
| import path from "node:path"; | ||
|
|
||
| import { clack } from "../utils/clack/prompts.js"; | ||
| import { debug } from "../utils/debug.js"; | ||
| import { | ||
| getCloudflareWorkerTemplate, | ||
| getCloudflareWorkerTemplateWithHandler, | ||
| } from "./templates.js"; | ||
| import { | ||
| defaultEntryPoint, | ||
| getEntryPointFromWranglerConfig, | ||
| } from "./wrangler/get-entry-point-from-wrangler-config.js"; | ||
| import { wrapWorkerWithSentry } from "./wrap-worker.js"; | ||
|
|
||
| /** | ||
| * Creates or updates the main worker file with Sentry initialization. | ||
| * Currently focused on Cloudflare Workers | ||
| */ | ||
| export async function createSentryInitFile( | ||
| dsn: string, | ||
| selectedFeatures: { | ||
| performance: boolean; | ||
| }, | ||
| reduceDataCollection: boolean, | ||
| ): Promise<void> { | ||
| const entryPointFromConfig = getEntryPointFromWranglerConfig(); | ||
|
|
||
| if (!entryPointFromConfig) { | ||
| clack.log.info( | ||
| "No entry point found in wrangler config, creating a new one.", | ||
| ); | ||
|
|
||
| const cloudflareWorkerTemplate = getCloudflareWorkerTemplateWithHandler(); | ||
|
|
||
| await promises.mkdir( | ||
| path.join(process.cwd(), path.dirname(defaultEntryPoint)), | ||
| { | ||
| recursive: true, | ||
| }, | ||
| ); | ||
| await promises.writeFile( | ||
| path.join(process.cwd(), defaultEntryPoint), | ||
| cloudflareWorkerTemplate, | ||
| { encoding: "utf-8", flag: "w" }, | ||
| ); | ||
|
|
||
| clack.log.success(`Created ${chalk.cyan(defaultEntryPoint)}.`); | ||
|
|
||
| return; | ||
|
sentry-junior[bot] marked this conversation as resolved.
Resolved
|
||
| } | ||
|
|
||
| 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( | ||
| 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, | ||
| ), | ||
| ), | ||
| ); | ||
| } | ||
| } | ||
|
sentry-junior[bot] marked this conversation as resolved.
Resolved
|
||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,57 @@ | ||
| /** | ||
| * Worker source the Cloudflare wizard writes or shows: a worker wrapped with | ||
| * `Sentry.withSentry()`, and a starter worker. | ||
| */ | ||
|
|
||
| import { getDataCollectionSnippet } from "../utils/data-collection.js"; | ||
|
|
||
| export function getCloudflareWorkerTemplate( | ||
| dsn: string, | ||
| selectedFeatures: { | ||
| performance: boolean; | ||
| }, | ||
| reduceDataCollection: boolean, | ||
| ): string { | ||
| let performanceOptions = ""; | ||
| if (selectedFeatures.performance) { | ||
| performanceOptions = ` | ||
| // Define how likely traces are sampled. Adjust this value in production, or use tracesSampler for greater control. | ||
| tracesSampleRate: 1,`; | ||
| } | ||
|
|
||
| const dataCollectionOptions = reduceDataCollection | ||
| ? `\n${getDataCollectionSnippet("\t\t")}` | ||
| : ""; | ||
|
|
||
| return `import * as Sentry from '@sentry/cloudflare'; | ||
|
|
||
| export default Sentry.withSentry( | ||
| (env) => ({ | ||
| dsn: '${dsn}',${performanceOptions}${dataCollectionOptions} | ||
| }), | ||
| { | ||
| async fetch(request, env, ctx): Promise<Response> { | ||
| // Your worker logic here | ||
| return new Response('Hello World!'); | ||
| }, | ||
| } satisfies ExportedHandler<Env>, | ||
| ); | ||
| `; | ||
| } | ||
|
|
||
| export function getCloudflareWorkerTemplateWithHandler(): string { | ||
| return `export default { | ||
| async fetch(request, env, ctx): Promise<Response> { | ||
| const url = new URL(request.url); | ||
| switch (url.pathname) { | ||
| case '/message': | ||
| return new Response('Hello, World!'); | ||
| case '/random': | ||
| return new Response(crypto.randomUUID()); | ||
| default: | ||
| return new Response('Not Found', { status: 404 }); | ||
| } | ||
| }, | ||
| } satisfies ExportedHandler<Env>; | ||
| `; | ||
| } |
36 changes: 36 additions & 0 deletions
36
packages/cli/src/lib/wizard/cloudflare/wrangler/create-wrangler-config.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,36 @@ | ||
| /** | ||
| * Create a minimal `wrangler.jsonc` for a project that has no Wrangler | ||
| * config yet. | ||
| */ | ||
|
|
||
| import chalk from "chalk"; | ||
| import { writeFileSync } from "node:fs"; | ||
| import path from "node:path"; | ||
|
|
||
| import { clack } from "../../utils/clack/prompts.js"; | ||
|
|
||
| /** | ||
| * Creates a basic wrangler.jsonc config file for a Cloudflare Worker | ||
| */ | ||
| export function createWranglerConfig(): void { | ||
| const configPath = path.join(process.cwd(), "wrangler.jsonc"); | ||
|
|
||
| const config = { | ||
| $schema: "node_modules/wrangler/config-schema.json", | ||
| name: "my-worker", | ||
| main: "src/index.ts", | ||
| }; | ||
|
|
||
| writeFileSync(configPath, JSON.stringify(config, null, 2), "utf-8"); | ||
|
|
||
| clack.log.success( | ||
| `Created ${chalk.cyan("wrangler.jsonc")} configuration file.`, | ||
| ); | ||
| clack.log.info( | ||
| `Please update the ${chalk.cyan("name")} and ${chalk.cyan( | ||
| "main", | ||
| )} fields in ${chalk.cyan( | ||
| "wrangler.jsonc", | ||
| )} to match your worker name and entry point.`, | ||
| ); | ||
| } |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.