From a239280d5496937d27aee803be2c174b76cf704f Mon Sep 17 00:00:00 2001 From: Tim Fish Date: Wed, 25 Nov 2026 20:44:19 +0000 Subject: [PATCH 1/2] ref(bundler-plugins): Pass the SDK's own deletion globs through an internal option Next.js, Nitro, Nuxt and SvelteKit passed their own globs through the public `filesToDeleteAfterUpload`. They now pass them through the internal `sdkFilesToDeleteAfterUpload`. Next.js no longer passes its own `disable` value or writes `deleteSourcemapsAfterUpload` into the user's options. SDK messages no longer tell users to set these options. --- .../src/core/build-plugin-manager.ts | 18 +++-- .../src/core/options-mapping.ts | 1 + packages/bundler-plugins/src/core/types.ts | 14 ++-- .../test/core/build-plugin-manager.test.ts | 65 +++++++++++++++++++ .../src/config/getBuildPluginOptions.ts | 4 +- .../config/handleRunAfterProductionCompile.ts | 2 +- .../nextjs/src/config/sourceMapOptions.ts | 32 +++++++-- packages/nextjs/src/config/webpack.ts | 18 ++--- .../withSentryConfig/getFinalConfigObject.ts | 2 +- .../getFinalConfigObjectBundlerUtils.ts | 20 +++--- .../test/config/getBuildPluginOptions.test.ts | 44 +++++++------ .../handleRunAfterProductionCompile.test.ts | 20 ++++++ .../test/config/sourceMapOptions.test.ts | 32 +++++++-- .../webpack/constructWebpackConfig.test.ts | 17 +++-- .../test/config/withSentryConfig.test.ts | 27 ++++---- packages/nitro/src/sourceMaps.ts | 10 +-- packages/nitro/test/sourceMaps.test.ts | 27 +++++--- packages/nuxt/src/vite/sourceMapDeletion.ts | 32 ++++----- packages/nuxt/src/vite/sourceMaps.ts | 27 ++++---- .../nuxt/test/vite/sourceMapDeletion.test.ts | 6 +- .../test/vite/sourceMaps-nuxtHooks.test.ts | 24 ++++--- packages/nuxt/test/vite/sourceMaps.test.ts | 7 +- .../src/vite/buildEnd/handleOnBuildEnd.ts | 6 +- .../vite/buildEnd/handleOnBuildEnd.test.ts | 4 +- packages/sveltekit/src/vite/sourceMaps.ts | 9 ++- .../sveltekit/test/vite/sourceMaps.test.ts | 11 ++-- 26 files changed, 320 insertions(+), 159 deletions(-) diff --git a/packages/bundler-plugins/src/core/build-plugin-manager.ts b/packages/bundler-plugins/src/core/build-plugin-manager.ts index 0169bfb4d948..758fd2ea0fe2 100644 --- a/packages/bundler-plugins/src/core/build-plugin-manager.ts +++ b/packages/bundler-plugins/src/core/build-plugin-manager.ts @@ -171,7 +171,8 @@ export type SentryBuildPluginManager = { }; /** - * Will delete artifacts based on the passed `sourcemaps.filesToDeleteAfterUpload` option. + * Deletes the files that match the user's `sourcemaps.filesToDeleteAfterUpload` and the SDK's + * `sourcemaps.sdkFilesToDeleteAfterUpload`. */ deleteArtifacts(): Promise; @@ -1002,13 +1003,20 @@ export function createSentryBuildPluginManager( }, /** - * Will delete artifacts based on the passed `sourcemaps.filesToDeleteAfterUpload` option. + * Deletes the files that match the user's `sourcemaps.filesToDeleteAfterUpload` and the SDK's + * `sourcemaps.sdkFilesToDeleteAfterUpload`. */ async deleteArtifacts() { try { - const filesToDelete = await options.sourcemaps?.filesToDeleteAfterUpload; - if (filesToDelete !== undefined) { - const filePathsToDelete = await globFiles(filesToDelete); + const patterns = ( + await Promise.all([ + options.sourcemaps?.filesToDeleteAfterUpload, + options.sourcemaps?.sdkFilesToDeleteAfterUpload, + ]) + ).filter(pattern => pattern !== undefined); + if (patterns.length > 0) { + const globbedPaths = await Promise.all(patterns.map(pattern => globFiles(pattern))); + const filePathsToDelete = [...new Set(globbedPaths.flat())]; logger.debug('Waiting for dependencies on generated files to be freed before deleting...'); diff --git a/packages/bundler-plugins/src/core/options-mapping.ts b/packages/bundler-plugins/src/core/options-mapping.ts index 1c1cad657957..5b39241971ea 100644 --- a/packages/bundler-plugins/src/core/options-mapping.ts +++ b/packages/bundler-plugins/src/core/options-mapping.ts @@ -36,6 +36,7 @@ export type NormalizedOptions = { filesToDeleteAfterUpload?: string | string[] | Promise; deleteSourcemapsAfterUpload?: boolean; sdkDeleteSourceMaps?: boolean | ((environment?: string) => boolean | undefined); + sdkFilesToDeleteAfterUpload?: string | string[] | Promise; } | undefined; release: { diff --git a/packages/bundler-plugins/src/core/types.ts b/packages/bundler-plugins/src/core/types.ts index c6854ea7e29e..227d4955b108 100644 --- a/packages/bundler-plugins/src/core/types.ts +++ b/packages/bundler-plugins/src/core/types.ts @@ -737,10 +737,11 @@ export type HandleRecoverableErrorFn = (error: unknown, throwByDefault: boolean) * @internal For Sentry SDK packages only. It can change in any release. * * Like `Options`, but with the SDK's own source map deletion decision in - * `sourcemaps.sdkDeleteSourceMaps`. The plugin calls its function form when it decides how to treat - * the bundler's source map setting, so an SDK can give a value that it only knows after it created - * the plugin. Vite passes the name of an environment with its own `build.sourcemap`, and `undefined` - * for the top-level `build.sourcemap`. + * `sourcemaps.sdkDeleteSourceMaps` and the SDK's own files to delete in + * `sourcemaps.sdkFilesToDeleteAfterUpload`. The plugin calls the function form of `sdkDeleteSourceMaps` + * when it decides how to treat the bundler's source map setting, so an SDK can give a value that it + * only knows after it created the plugin. Vite passes the name of an environment with its own + * `build.sourcemap`, and `undefined` for the top-level `build.sourcemap`. */ export type InternalOptions = Omit & { sourcemaps?: NonNullable & { @@ -754,5 +755,10 @@ export type InternalOptions = Omit & { * decides whether source maps are removed, and `true` here still makes that all of them. */ sdkDeleteSourceMaps?: boolean | ((environment?: string) => boolean | undefined); + /** + * The SDK's own files to delete after the upload. The plugin deletes them next to the files of + * the user's `sourcemaps.filesToDeleteAfterUpload`. + */ + sdkFilesToDeleteAfterUpload?: string | string[] | Promise; }; }; diff --git a/packages/bundler-plugins/test/core/build-plugin-manager.test.ts b/packages/bundler-plugins/test/core/build-plugin-manager.test.ts index 5349777dfc2b..3c86be006189 100644 --- a/packages/bundler-plugins/test/core/build-plugin-manager.test.ts +++ b/packages/bundler-plugins/test/core/build-plugin-manager.test.ts @@ -569,6 +569,71 @@ describe('createSentryBuildPluginManager', () => { }); }); + describe('deleteArtifacts', () => { + const managerOptions = { + authToken: 't', + org: 'o', + project: 'p', + release: { name: 'some-release-name' }, + telemetry: false, + silent: true, + }; + const meta = { buildTool: 'esbuild', loggerPrefix: '[sentry-esbuild-plugin]' }; + + it("deletes the files of the user's and the SDK's globs once", async () => { + const rmSpy = vi.spyOn(fs.promises, 'rm').mockResolvedValue(undefined); + mockGlobFiles.mockImplementation(async patterns => + patterns === 'user/**/*.map' ? ['/app/user/a.js.map', '/app/shared.js.map'] : ['/app/shared.js.map'], + ); + const manager = createSentryBuildPluginManager( + { + ...managerOptions, + sourcemaps: { + filesToDeleteAfterUpload: 'user/**/*.map', + sdkFilesToDeleteAfterUpload: Promise.resolve(['sdk/**/*.map']), + }, + }, + meta, + ); + + await manager.deleteArtifacts(); + + expect(mockGlobFiles).toHaveBeenCalledWith('user/**/*.map'); + expect(mockGlobFiles).toHaveBeenCalledWith(['sdk/**/*.map']); + expect(rmSpy).toHaveBeenCalledTimes(2); + expect(rmSpy).toHaveBeenCalledWith('/app/user/a.js.map', { force: true }); + expect(rmSpy).toHaveBeenCalledWith('/app/shared.js.map', { force: true }); + }); + + it('deletes the files of the SDK glob without a user glob', async () => { + const rmSpy = vi.spyOn(fs.promises, 'rm').mockResolvedValue(undefined); + mockGlobFiles.mockResolvedValue(['/app/sdk/a.js.map']); + const manager = createSentryBuildPluginManager( + { ...managerOptions, sourcemaps: { sdkFilesToDeleteAfterUpload: 'sdk/**/*.map' } }, + meta, + ); + + await manager.deleteArtifacts(); + + expect(mockGlobFiles).toHaveBeenCalledTimes(1); + expect(mockGlobFiles).toHaveBeenCalledWith('sdk/**/*.map'); + expect(rmSpy).toHaveBeenCalledWith('/app/sdk/a.js.map', { force: true }); + }); + + it('deletes nothing without a glob', async () => { + const rmSpy = vi.spyOn(fs.promises, 'rm').mockResolvedValue(undefined); + const manager = createSentryBuildPluginManager( + { ...managerOptions, sourcemaps: { sdkFilesToDeleteAfterUpload: Promise.resolve(undefined) } }, + meta, + ); + + await manager.deleteArtifacts(); + + expect(mockGlobFiles).not.toHaveBeenCalled(); + expect(rmSpy).not.toHaveBeenCalled(); + }); + }); + describe('injectDebugIds', () => { it('should call the CLI inject command for each build artifact path', async () => { mockSourcemapInject.mockResolvedValue(undefined); diff --git a/packages/nextjs/src/config/getBuildPluginOptions.ts b/packages/nextjs/src/config/getBuildPluginOptions.ts index 21d4e1ac86dc..bf431d02647d 100644 --- a/packages/nextjs/src/config/getBuildPluginOptions.ts +++ b/packages/nextjs/src/config/getBuildPluginOptions.ts @@ -302,7 +302,7 @@ export function getBuildPluginOptions({ const loggerPrefix = LOGGER_PREFIXES[buildTool]; const widenClientFileUpload = sentryBuildOptions.widenClientFileUpload ?? false; const userSourcemaps = sentryBuildOptions.sourcemaps; - const deleteSourcemapsAfterUpload = getDeleteSourceMapsOption(userSourcemaps) ?? false; + const deleteSourcemapsAfterUpload = getDeleteSourceMapsOption(sentryBuildOptions) ?? false; // `sourcemaps.delete: true` removes the source maps next to the user's `filesToDeleteAfterUpload`. const userFilesReplaceDeletion = userSourcemaps?.delete !== true; @@ -368,7 +368,7 @@ export function getBuildPluginOptions({ rewriteSources: sentryBuildOptions.sourcemaps?.rewriteSources ?? rewriteWebpackSources, assets: sentryBuildOptions.sourcemaps?.assets ?? sourcemapUploadAssets, ignore: finalIgnorePatterns, - filesToDeleteAfterUpload, + sdkFilesToDeleteAfterUpload: filesToDeleteAfterUpload, // Every client map goes, also those the user turned on with `productionBrowserSourceMaps` or // `devtool`, and those of chunks the upload leaves out. sdkDeleteSourceMaps: webpackPluginDeletesSourcemaps, diff --git a/packages/nextjs/src/config/handleRunAfterProductionCompile.ts b/packages/nextjs/src/config/handleRunAfterProductionCompile.ts index 7d44bc311ef4..5934362b4c45 100644 --- a/packages/nextjs/src/config/handleRunAfterProductionCompile.ts +++ b/packages/nextjs/src/config/handleRunAfterProductionCompile.ts @@ -72,7 +72,7 @@ export async function handleRunAfterProductionCompile( prepareArtifacts: false, }); - const deleteSourcemapsAfterUpload = getDeleteSourceMapsOption(sentryBuildOptions.sourcemaps) ?? false; + const deleteSourcemapsAfterUpload = getDeleteSourceMapsOption(sentryBuildOptions) ?? false; // Deletion covers all of `static/`, so if Next.js emits chunks outside the upload // patterns, their maps would be deleted without ever having been uploaded — warn instead diff --git a/packages/nextjs/src/config/sourceMapOptions.ts b/packages/nextjs/src/config/sourceMapOptions.ts index 6adb98b07825..f75fcc48adff 100644 --- a/packages/nextjs/src/config/sourceMapOptions.ts +++ b/packages/nextjs/src/config/sourceMapOptions.ts @@ -15,9 +15,29 @@ export function sentryEnablesSourceMaps(options: SentryBuildOptions): boolean { return (upload && hasSourceMapUploadCredentials(options)) || (sourcemaps?.delete === false && injectDebugIds); } -/** Reads `sourcemaps.delete`. When it is unset, `sourcemaps.deleteSourcemapsAfterUpload` decides. */ -export function getDeleteSourceMapsOption(sourcemaps: SourceMapsOptions): boolean | undefined { - return sourcemaps?.delete ?? sourcemaps?.deleteSourcemapsAfterUpload; +export const SDK_DELETES_SOURCE_MAPS_MESSAGE = + '[@sentry/nextjs] Source maps will be deleted after the upload to Sentry. To keep them, set `sourcemaps.delete: false` in `withSentryConfig()`. To neither generate nor upload source maps, set `sourcemaps.upload: false`.'; + +// Every build phase that runs in this process gets the same options object. +const sdkDeletesSourceMaps = new WeakSet(); + +/** + * Makes the SDK delete the source maps after the upload when the user set neither `sourcemaps.delete` + * nor `sourcemaps.deleteSourcemapsAfterUpload`. + */ +export function setSdkDeletesSourceMaps(options: SentryBuildOptions): void { + sdkDeletesSourceMaps.add(options); +} + +/** + * Reads `sourcemaps.delete`. When it is unset, `sourcemaps.deleteSourcemapsAfterUpload` decides, and + * then `setSdkDeletesSourceMaps`. + */ +export function getDeleteSourceMapsOption(options: SentryBuildOptions): boolean | undefined { + const { sourcemaps } = options; + return ( + sourcemaps?.delete ?? sourcemaps?.deleteSourcemapsAfterUpload ?? (sdkDeletesSourceMaps.has(options) || undefined) + ); } /** @@ -37,8 +57,7 @@ export function mergeFilesToDeleteAfterUpload( } /** - * `disable`, `upload` and `injectDebugIds` for the bundler plugin. It warns when `disable` is set next to the - * options that replace it, so `disable` gets no default then. + * `disable`, `upload` and `injectDebugIds` for the bundler plugin. `disable` is only ever the user's own value. */ // TODO(v12): Remove `disable`. export function getSourceMapFeatureOptions( @@ -52,6 +71,5 @@ export function getSourceMapFeatureOptions( } const { disable, upload, injectDebugIds } = userSourcemaps ?? {}; - const usesFeatureOptions = upload !== undefined || injectDebugIds !== undefined; - return { disable: disable ?? (usesFeatureOptions ? undefined : false), upload, injectDebugIds }; + return { disable, upload, injectDebugIds }; } diff --git a/packages/nextjs/src/config/webpack.ts b/packages/nextjs/src/config/webpack.ts index 28c33a81f1d3..5bccaf206b6a 100644 --- a/packages/nextjs/src/config/webpack.ts +++ b/packages/nextjs/src/config/webpack.ts @@ -10,7 +10,12 @@ import type { VercelCronsConfig } from '../common/types'; import { getBuildLogger } from './buildLogger'; import { externalizeOrchestrionRuntimePackages } from './diagnosticsChannelInjection'; import { getBuildPluginOptions, normalizePathForGlob } from './getBuildPluginOptions'; -import { getDeleteSourceMapsOption, sentryEnablesSourceMaps } from './sourceMapOptions'; +import { + getDeleteSourceMapsOption, + SDK_DELETES_SOURCE_MAPS_MESSAGE, + sentryEnablesSourceMaps, + setSdkDeletesSourceMaps, +} from './sourceMapOptions'; import type { RouteManifest } from './manifest/types'; import type { BuildContext, @@ -385,14 +390,9 @@ export function constructWebpackConfigFunction({ } // enable source map deletion if not explicitly disabled - if (!isServer && getDeleteSourceMapsOption(userSentryOptions.sourcemaps) === undefined) { - debug.warn( - '[@sentry/nextjs] Source maps will be automatically deleted after being uploaded to Sentry. If you want to keep the source maps, set the `sourcemaps.deleteSourcemapsAfterUpload` option to false in `withSentryConfig()`. If you do not want to generate and upload sourcemaps at all, set the `sourcemaps.disable` option to true.', - ); - userSentryOptions.sourcemaps = { - ...userSentryOptions.sourcemaps, - deleteSourcemapsAfterUpload: true, - }; + if (!isServer && getDeleteSourceMapsOption(userSentryOptions) === undefined) { + debug.warn(SDK_DELETES_SOURCE_MAPS_MESSAGE); + setSdkDeletesSourceMaps(userSentryOptions); } } diff --git a/packages/nextjs/src/config/withSentryConfig/getFinalConfigObject.ts b/packages/nextjs/src/config/withSentryConfig/getFinalConfigObject.ts index cc238b65824e..40261d2854f2 100644 --- a/packages/nextjs/src/config/withSentryConfig/getFinalConfigObject.ts +++ b/packages/nextjs/src/config/withSentryConfig/getFinalConfigObject.ts @@ -36,7 +36,7 @@ import { maybeAddReleaseServerTimingHeader } from './release'; /** * Materializes the final Next.js config object with Sentry's build-time integrations applied. * - * Note: this mutates both `incomingUserNextConfigObject` and `userSentryOptions` (to apply defaults). + * Note: this mutates `incomingUserNextConfigObject` (to apply defaults). */ export function getFinalConfigObject( incomingUserNextConfigObject: NextConfigObject, diff --git a/packages/nextjs/src/config/withSentryConfig/getFinalConfigObjectBundlerUtils.ts b/packages/nextjs/src/config/withSentryConfig/getFinalConfigObjectBundlerUtils.ts index b6172939b069..f1d8b20dc123 100644 --- a/packages/nextjs/src/config/withSentryConfig/getFinalConfigObjectBundlerUtils.ts +++ b/packages/nextjs/src/config/withSentryConfig/getFinalConfigObjectBundlerUtils.ts @@ -6,7 +6,12 @@ import { import { getBuildLogger } from '../buildLogger'; import { handleRunAfterProductionCompile } from '../handleRunAfterProductionCompile'; import type { RouteManifest } from '../manifest/types'; -import { getDeleteSourceMapsOption, sentryEnablesSourceMaps } from '../sourceMapOptions'; +import { + getDeleteSourceMapsOption, + SDK_DELETES_SOURCE_MAPS_MESSAGE, + sentryEnablesSourceMaps, + setSdkDeletesSourceMaps, +} from '../sourceMapOptions'; import { constructTurbopackConfig } from '../turbopack'; import type { NextConfigObject, SentryBuildOptions, TurbopackOptions } from '../types'; import { detectActiveBundler, supportsProductionCompileHook, supportsTurbopackRuleCondition } from '../util'; @@ -240,7 +245,7 @@ export function maybeSetUpRunAfterProductionCompileHook({ /** * For supported turbopack builds, auto-enables browser sourcemaps and defaults to deleting them after upload. * - * Note: this mutates both `incomingUserNextConfigObject` and `userSentryOptions`. + * Note: this mutates `incomingUserNextConfigObject`. */ export function maybeEnableTurbopackSourcemaps( incomingUserNextConfigObject: NextConfigObject, @@ -266,20 +271,15 @@ export function maybeEnableTurbopackSourcemaps( incomingUserNextConfigObject.productionBrowserSourceMaps = true; // Enable source map deletion if not explicitly disabled - if (getDeleteSourceMapsOption(userSentryOptions.sourcemaps) !== undefined) { + if (getDeleteSourceMapsOption(userSentryOptions) !== undefined) { return; } if (userSentryOptions.debug) { - logger.warn( - '[@sentry/nextjs] Source maps will be automatically deleted after being uploaded to Sentry. If you want to keep the source maps, set the `sourcemaps.deleteSourcemapsAfterUpload` option to false in `withSentryConfig()`. If you do not want to generate and upload sourcemaps at all, set the `sourcemaps.disable` option to true.', - ); + logger.warn(SDK_DELETES_SOURCE_MAPS_MESSAGE); } - userSentryOptions.sourcemaps = { - ...userSentryOptions.sourcemaps, - deleteSourcemapsAfterUpload: true, - }; + setSdkDeletesSourceMaps(userSentryOptions); } /** diff --git a/packages/nextjs/test/config/getBuildPluginOptions.test.ts b/packages/nextjs/test/config/getBuildPluginOptions.test.ts index a408b80bfdb3..cc9cfb443b58 100644 --- a/packages/nextjs/test/config/getBuildPluginOptions.test.ts +++ b/packages/nextjs/test/config/getBuildPluginOptions.test.ts @@ -55,7 +55,7 @@ describe('getBuildPluginOptions', () => { '**/route_client-reference-manifest.js', '**/middleware-react-loadable-manifest.js', ], - filesToDeleteAfterUpload: undefined, + sdkFilesToDeleteAfterUpload: undefined, rewriteSources: expect.any(Function), }, release: { @@ -401,10 +401,11 @@ describe('getBuildPluginOptions', () => { }); expect(result.sourcemaps).toEqual(expect.objectContaining({ upload: false, injectDebugIds: true })); + expect(result.sourcemaps?.disable).toBeUndefined(); }); }); - it('does not disable sourcemaps when useRunAfterProductionCompileHook is true for after-production-compile builds', () => { + it('passes the source map features on unchanged when useRunAfterProductionCompileHook is true for after-production-compile builds', () => { const afterProductionCompileBuildTools = [ 'after-production-compile-webpack', 'after-production-compile-turbopack', @@ -419,11 +420,11 @@ describe('getBuildPluginOptions', () => { useRunAfterProductionCompileHook: true, }); - expect(result.sourcemaps?.disable).toBe(false); + expect(result.sourcemaps).toMatchObject({ disable: undefined, upload: undefined, injectDebugIds: undefined }); }); }); - it('does not disable sourcemaps when useRunAfterProductionCompileHook is false', () => { + it('passes the source map features on unchanged when useRunAfterProductionCompileHook is false', () => { const result = getBuildPluginOptions({ sentryBuildOptions: baseSentryOptions, releaseName: mockReleaseName, @@ -432,7 +433,7 @@ describe('getBuildPluginOptions', () => { useRunAfterProductionCompileHook: false, }); - expect(result.sourcemaps?.disable).toBe(false); + expect(result.sourcemaps).toMatchObject({ disable: undefined, upload: undefined, injectDebugIds: undefined }); }); }); @@ -453,7 +454,7 @@ describe('getBuildPluginOptions', () => { buildTool: 'after-production-compile-webpack', }); - expect(result.sourcemaps?.filesToDeleteAfterUpload).toEqual([ + expect(result.sourcemaps?.sdkFilesToDeleteAfterUpload).toEqual([ '/path/to/.next/static/**/*.js.map', '/path/to/.next/static/**/*.mjs.map', '/path/to/.next/static/**/*.cjs.map', @@ -477,7 +478,7 @@ describe('getBuildPluginOptions', () => { buildTool: 'after-production-compile-turbopack', }); - expect(result.sourcemaps?.filesToDeleteAfterUpload).toEqual([ + expect(result.sourcemaps?.sdkFilesToDeleteAfterUpload).toEqual([ '/path/to/.next/static/**/*.js.map', '/path/to/.next/static/**/*.mjs.map', '/path/to/.next/static/**/*.cjs.map', @@ -499,7 +500,7 @@ describe('getBuildPluginOptions', () => { }); expect(result.sourcemaps).toMatchObject({ - filesToDeleteAfterUpload: undefined, + sdkFilesToDeleteAfterUpload: undefined, sdkDeleteSourceMaps: true, }); }); @@ -517,7 +518,7 @@ describe('getBuildPluginOptions', () => { }); expect(result.sourcemaps).toMatchObject({ - filesToDeleteAfterUpload: undefined, + sdkFilesToDeleteAfterUpload: undefined, sdkDeleteSourceMaps: false, }); }); @@ -537,7 +538,7 @@ describe('getBuildPluginOptions', () => { // The upload runs after the compile, and the after-production-compile options delete the maps. expect(result.sourcemaps).toMatchObject({ - filesToDeleteAfterUpload: undefined, + sdkFilesToDeleteAfterUpload: undefined, sdkDeleteSourceMaps: false, }); }); @@ -557,7 +558,7 @@ describe('getBuildPluginOptions', () => { }); expect(result.sourcemaps).toMatchObject({ - filesToDeleteAfterUpload: undefined, + sdkFilesToDeleteAfterUpload: undefined, sdkDeleteSourceMaps: false, }); }, @@ -617,7 +618,7 @@ describe('getBuildPluginOptions', () => { buildTool: 'webpack-client', }); - expect(result.sourcemaps?.filesToDeleteAfterUpload).toEqual(['.next/static/**/*.map']); + expect(result.sourcemaps?.sdkFilesToDeleteAfterUpload).toEqual(['.next/static/**/*.map']); expect(result.sourcemaps?.sdkDeleteSourceMaps).toBe(false); }); @@ -637,7 +638,10 @@ describe('getBuildPluginOptions', () => { buildTool: 'webpack-client', }); - expect(result.sourcemaps?.filesToDeleteAfterUpload).toEqual(['.next/static/**/*.map', '.next/server/**/*.map']); + expect(result.sourcemaps?.sdkFilesToDeleteAfterUpload).toEqual([ + '.next/static/**/*.map', + '.next/server/**/*.map', + ]); }); it('filesToDeleteAfterUpload overrides deleteSourcemapsAfterUpload default pattern', () => { @@ -657,7 +661,7 @@ describe('getBuildPluginOptions', () => { buildTool: 'webpack-client', }); - expect(result.sourcemaps?.filesToDeleteAfterUpload).toEqual(['custom/**/*.map']); + expect(result.sourcemaps?.sdkFilesToDeleteAfterUpload).toEqual(['custom/**/*.map']); expect(result.sourcemaps?.sdkDeleteSourceMaps).toBe(false); }); @@ -677,7 +681,7 @@ describe('getBuildPluginOptions', () => { buildTool: 'webpack-nodejs', }); - expect(result.sourcemaps?.filesToDeleteAfterUpload).toEqual(['.next/server/**/*.map']); + expect(result.sourcemaps?.sdkFilesToDeleteAfterUpload).toEqual(['.next/server/**/*.map']); }); it('uses custom sourcemap assets when provided', () => { @@ -784,7 +788,7 @@ describe('getBuildPluginOptions', () => { buildTool, }); - expect(result.sourcemaps?.filesToDeleteAfterUpload).toEqual([ + expect(result.sourcemaps?.sdkFilesToDeleteAfterUpload).toEqual([ '/path/to/.next/static/**/*.js.map', '/path/to/.next/static/**/*.mjs.map', '/path/to/.next/static/**/*.cjs.map', @@ -804,7 +808,7 @@ describe('getBuildPluginOptions', () => { buildTool: 'after-production-compile-turbopack', }); - expect(result.sourcemaps?.filesToDeleteAfterUpload).toEqual(['custom/**/*.map']); + expect(result.sourcemaps?.sdkFilesToDeleteAfterUpload).toEqual(['custom/**/*.map']); }); // The plugin would also remove the server source maps, which broke deployments on Vercel. @@ -1185,7 +1189,7 @@ describe('getBuildPluginOptions', () => { }); expect(result.sourcemaps).toMatchObject({ - disable: false, + disable: undefined, assets: ['/path/to/.next/server', '/path/to/.next/static/chunks/pages', '/path/to/.next/static/chunks/app'], ignore: [ '/path/to/.next/static/chunks/main-*', @@ -1201,7 +1205,7 @@ describe('getBuildPluginOptions', () => { '**/route_client-reference-manifest.js', '**/middleware-react-loadable-manifest.js', ], - filesToDeleteAfterUpload: undefined, + sdkFilesToDeleteAfterUpload: undefined, rewriteSources: expect.any(Function), }); }); @@ -1225,7 +1229,7 @@ describe('getBuildPluginOptions', () => { }); expect(result.sourcemaps?.assets).toEqual([`${complexPath}/server`, `${complexPath}/static/chunks`]); - expect(result.sourcemaps?.filesToDeleteAfterUpload).toEqual([ + expect(result.sourcemaps?.sdkFilesToDeleteAfterUpload).toEqual([ `${complexPath}/static/**/*.js.map`, `${complexPath}/static/**/*.mjs.map`, `${complexPath}/static/**/*.cjs.map`, diff --git a/packages/nextjs/test/config/handleRunAfterProductionCompile.test.ts b/packages/nextjs/test/config/handleRunAfterProductionCompile.test.ts index 2cfe68e173ce..5015cfd2738b 100644 --- a/packages/nextjs/test/config/handleRunAfterProductionCompile.test.ts +++ b/packages/nextjs/test/config/handleRunAfterProductionCompile.test.ts @@ -9,6 +9,7 @@ import { handleRunAfterProductionCompile, stripSourceMappingURLComments, } from '../../src/config/handleRunAfterProductionCompile'; +import { setSdkDeletesSourceMaps } from '../../src/config/sourceMapOptions'; import type { SentryBuildOptions } from '../../src/config/types'; vi.mock('@sentry/core/server', async importOriginal => ({ @@ -347,6 +348,25 @@ describe('handleRunAfterProductionCompile', () => { ); }); + it('strips sourceMappingURL comments for turbopack builds when the SDK turned deletion on', async () => { + const sentryBuildOptions: SentryBuildOptions = { ...mockSentryBuildOptions, sourcemaps: {} }; + setSdkDeletesSourceMaps(sentryBuildOptions); + + await handleRunAfterProductionCompile( + { + releaseName: 'test-release', + distDir: '/path/to/.next', + buildTool: 'turbopack', + }, + sentryBuildOptions, + ); + + expect(readdirSpy).toHaveBeenCalledWith( + path.join('/path/to/.next', 'static'), + expect.objectContaining({ recursive: true }), + ); + }); + it('does NOT strip sourceMappingURL comments for webpack builds even with deleteSourcemapsAfterUpload', async () => { await handleRunAfterProductionCompile( { diff --git a/packages/nextjs/test/config/sourceMapOptions.test.ts b/packages/nextjs/test/config/sourceMapOptions.test.ts index 33fe8d9236ad..92dd29092771 100644 --- a/packages/nextjs/test/config/sourceMapOptions.test.ts +++ b/packages/nextjs/test/config/sourceMapOptions.test.ts @@ -4,6 +4,7 @@ import { getSourceMapFeatureOptions, mergeFilesToDeleteAfterUpload, sentryEnablesSourceMaps, + setSdkDeletesSourceMaps, } from '../../src/config/sourceMapOptions'; import type { NextConfigObject, SentryBuildOptions } from '../../src/config/types'; import type { BundlerInfo } from '../../src/config/withSentryConfig/getFinalConfigObjectBundlerUtils'; @@ -53,13 +54,31 @@ describe('getDeleteSourceMapsOption', () => { [{ delete: false, deleteSourcemapsAfterUpload: true }, false], [{ delete: true, deleteSourcemapsAfterUpload: false }, true], ] as const)('with %j it returns %s', (sourcemaps, expected) => { - expect(getDeleteSourceMapsOption(sourcemaps)).toBe(expected); + expect(getDeleteSourceMapsOption({ sourcemaps })).toBe(expected); + }); + + it.each([ + [undefined, true], + [{ deleteSourcemapsAfterUpload: false }, false], + [{ delete: false }, false], + ] as const)('after `setSdkDeletesSourceMaps`, with %j it returns %s', (sourcemaps, expected) => { + const options: SentryBuildOptions = { sourcemaps }; + setSdkDeletesSourceMaps(options); + + expect(getDeleteSourceMapsOption(options)).toBe(expected); + expect(options.sourcemaps).toEqual(sourcemaps); + }); + + it('reads the SDK default only for the options object it was set on', () => { + setSdkDeletesSourceMaps({}); + + expect(getDeleteSourceMapsOption({})).toBeUndefined(); }); }); describe('getSourceMapFeatureOptions', () => { it.each([ - [undefined, { disable: false }], + [undefined, {}], [{ disable: 'disable-upload' }, { disable: 'disable-upload' }], [{ upload: false }, { disable: undefined, upload: false }], [{ injectDebugIds: false }, { disable: undefined, injectDebugIds: false }], @@ -103,7 +122,11 @@ describe('maybeEnableTurbopackSourcemaps with the new source map options', () => function run(sourcemaps: NonNullable, nextConfig: NextConfigObject = {}) { const userSentryOptions: SentryBuildOptions = { ...CREDENTIALS, sourcemaps }; maybeEnableTurbopackSourcemaps(nextConfig, userSentryOptions, TURBOPACK_SUPPORTED); - return { nextConfig, sourcemaps: userSentryOptions.sourcemaps }; + return { + nextConfig, + sourcemaps: userSentryOptions.sourcemaps, + deleteSourceMaps: getDeleteSourceMapsOption(userSentryOptions), + }; } it.each([{ upload: false }, { injectDebugIds: false }, { upload: false, delete: true }])( @@ -130,7 +153,8 @@ describe('maybeEnableTurbopackSourcemaps with the new source map options', () => const result = run({ upload: true }); expect(result.nextConfig.productionBrowserSourceMaps).toBe(true); - expect(result.sourcemaps).toEqual({ upload: true, deleteSourcemapsAfterUpload: true }); + expect(result.sourcemaps).toEqual({ upload: true }); + expect(result.deleteSourceMaps).toBe(true); }); it('turns no source maps on without upload credentials', () => { diff --git a/packages/nextjs/test/config/webpack/constructWebpackConfig.test.ts b/packages/nextjs/test/config/webpack/constructWebpackConfig.test.ts index a10ed7c44989..ddc507187a3c 100644 --- a/packages/nextjs/test/config/webpack/constructWebpackConfig.test.ts +++ b/packages/nextjs/test/config/webpack/constructWebpackConfig.test.ts @@ -6,6 +6,8 @@ import type * as os from 'os'; import * as path from 'path'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import * as getBuildPluginOptionsModule from '../../../src/config/getBuildPluginOptions'; +import { getDeleteSourceMapsOption } from '../../../src/config/sourceMapOptions'; +import type { SentryBuildOptions } from '../../../src/config/types'; import { CLIENT_SDK_CONFIG_FILE, clientBuildContext, @@ -76,35 +78,32 @@ describe('constructWebpackConfigFunction()', () => { expect(finalWebpackConfig.devtool).toEqual(customDevtool); }); - it('automatically enables deleteSourcemapsAfterUpload for client builds when not explicitly set', async () => { + it('turns source map deletion on for client builds when not explicitly set', async () => { const getBuildPluginOptionsSpy = vi.spyOn(getBuildPluginOptionsModule, 'getBuildPluginOptions'); vi.spyOn(coreServer, 'loadModule').mockImplementation(() => ({ sentryWebpackPlugin: () => ({ _name: 'sentry-webpack-plugin', }), })); + const sentryBuildTimeOptions: SentryBuildOptions = { sourcemaps: {} }; await materializeFinalWebpackConfig({ exportedNextConfig, incomingWebpackConfig: clientWebpackConfig, incomingWebpackBuildContext: clientBuildContext, - sentryBuildTimeOptions: { - sourcemaps: {}, - }, + sentryBuildTimeOptions, }); expect(getBuildPluginOptionsSpy).toHaveBeenCalledWith( expect.objectContaining({ - sentryBuildOptions: expect.objectContaining({ - sourcemaps: { - deleteSourcemapsAfterUpload: true, - }, - }), + sentryBuildOptions: sentryBuildTimeOptions, buildTool: 'webpack-client', distDirAbsPath: expect.any(String), releaseName: undefined, }), ); + expect(sentryBuildTimeOptions.sourcemaps).toEqual({}); + expect(getDeleteSourceMapsOption(sentryBuildTimeOptions)).toBe(true); getBuildPluginOptionsSpy.mockRestore(); }); diff --git a/packages/nextjs/test/config/withSentryConfig.test.ts b/packages/nextjs/test/config/withSentryConfig.test.ts index af2cc03a303b..bf167defd132 100644 --- a/packages/nextjs/test/config/withSentryConfig.test.ts +++ b/packages/nextjs/test/config/withSentryConfig.test.ts @@ -4,6 +4,7 @@ import { filterInstrumentedExternals, ORCHESTRION_RUNTIME_EXTERNAL_PACKAGES, } from '../../src/config/diagnosticsChannelInjection'; +import { getDeleteSourceMapsOption } from '../../src/config/sourceMapOptions'; import type { SentryBuildOptions } from '../../src/config/types'; import * as util from '../../src/config/util'; import { DEFAULT_SERVER_EXTERNAL_PACKAGES } from '../../src/config/withSentryConfig'; @@ -653,7 +654,7 @@ describe('withSentryConfig', () => { expect(finalConfig.productionBrowserSourceMaps).toBe(true); }); - it('automatically enables deleteSourcemapsAfterUpload for turbopack builds when not explicitly set', () => { + it('turns source map deletion on for turbopack builds when not explicitly set', () => { process.env.TURBOPACK = '1'; vi.spyOn(util, 'getNextjsVersion').mockReturnValue('15.4.1'); @@ -667,9 +668,9 @@ describe('withSentryConfig', () => { const finalConfig = materializeFinalNextConfig(cleanConfig, undefined, sentryOptions); - // Both productionBrowserSourceMaps and deleteSourcemapsAfterUpload should be enabled + // Both source map generation and deletion should be enabled expect(finalConfig.productionBrowserSourceMaps).toBe(true); - expect(sentryOptions.sourcemaps).toHaveProperty('deleteSourcemapsAfterUpload', true); + expect(getDeleteSourceMapsOption(sentryOptions)).toBe(true); }); it('does not auto-enable source map generation when `disable` is "disable-upload"', () => { @@ -690,7 +691,7 @@ describe('withSentryConfig', () => { // The SDK must not generate source maps it will neither upload nor delete - they would be served // publicly from `.next/static`. Generating them is the user's call via `productionBrowserSourceMaps`. expect(finalConfig.productionBrowserSourceMaps).toBeUndefined(); - expect(sentryOptions.sourcemaps).not.toHaveProperty('deleteSourcemapsAfterUpload'); + expect(getDeleteSourceMapsOption(sentryOptions)).toBeUndefined(); }); it('preserves explicitly configured deleteSourcemapsAfterUpload setting', () => { @@ -708,7 +709,7 @@ describe('withSentryConfig', () => { expect(sentryOptions.sourcemaps.deleteSourcemapsAfterUpload).toBe(false); }); - it('does not modify deleteSourcemapsAfterUpload when sourcemaps are disabled', () => { + it('does not turn source map deletion on when sourcemaps are disabled', () => { process.env.TURBOPACK = '1'; vi.spyOn(util, 'getNextjsVersion').mockReturnValue('15.4.1'); @@ -720,10 +721,10 @@ describe('withSentryConfig', () => { materializeFinalNextConfig(exportedNextConfig, undefined, sentryOptions); - expect(sentryOptions.sourcemaps).not.toHaveProperty('deleteSourcemapsAfterUpload'); + expect(getDeleteSourceMapsOption(sentryOptions)).toBeUndefined(); }); - it('does not enable deleteSourcemapsAfterUpload when user pre-configured productionBrowserSourceMaps: true', () => { + it('does not turn source map deletion on when user pre-configured productionBrowserSourceMaps: true', () => { process.env.TURBOPACK = '1'; vi.spyOn(util, 'getNextjsVersion').mockReturnValue('15.4.1'); @@ -739,7 +740,7 @@ describe('withSentryConfig', () => { materializeFinalNextConfig(configWithSourceMapsPreEnabled, undefined, sentryOptions); // Should NOT automatically enable deletion because productionBrowserSourceMaps was already set by user - expect(sentryOptions.sourcemaps).not.toHaveProperty('deleteSourcemapsAfterUpload'); + expect(getDeleteSourceMapsOption(sentryOptions)).toBeUndefined(); }); it('does not enable sourcemaps or deletion when user explicitly sets productionBrowserSourceMaps: false', () => { @@ -759,7 +760,7 @@ describe('withSentryConfig', () => { // Should NOT modify productionBrowserSourceMaps or enable deletion when user explicitly set to false expect(finalConfig.productionBrowserSourceMaps).toBe(false); - expect(sentryOptions.sourcemaps).not.toHaveProperty('deleteSourcemapsAfterUpload'); + expect(getDeleteSourceMapsOption(sentryOptions)).toBeUndefined(); }); it('logs correct message when enabling sourcemaps for turbopack', () => { @@ -800,7 +801,7 @@ describe('withSentryConfig', () => { materializeFinalNextConfig(cleanConfig, undefined, sentryOptions); expect(consoleWarnSpy).toHaveBeenCalledWith( - '[@sentry/nextjs] Source maps will be automatically deleted after being uploaded to Sentry. If you want to keep the source maps, set the `sourcemaps.deleteSourcemapsAfterUpload` option to false in `withSentryConfig()`. If you do not want to generate and upload sourcemaps at all, set the `sourcemaps.disable` option to true.', + '[@sentry/nextjs] Source maps will be deleted after the upload to Sentry. To keep them, set `sourcemaps.delete: false` in `withSentryConfig()`. To neither generate nor upload source maps, set `sourcemaps.upload: false`.', ); consoleWarnSpy.mockRestore(); @@ -897,7 +898,7 @@ describe('withSentryConfig', () => { materializeFinalNextConfig(cleanConfig, undefined, sentryOptions); - expect(sentryOptions.sourcemaps).toHaveProperty('deleteSourcemapsAfterUpload', true); + expect(getDeleteSourceMapsOption(sentryOptions)).toBe(true); }); it('works when TURBOPACK env var is truthy string', () => { @@ -937,7 +938,7 @@ describe('withSentryConfig', () => { const finalConfig = materializeFinalNextConfig(cleanConfig, undefined, sentryOptions); expect(finalConfig.productionBrowserSourceMaps).toBe(true); - expect(sentryOptions.sourcemaps).toHaveProperty('deleteSourcemapsAfterUpload', true); + expect(getDeleteSourceMapsOption(sentryOptions)).toBe(true); expect(finalConfig.env).toHaveProperty('_sentryTunnelRoute', '/custom-tunnel'); }); @@ -963,7 +964,7 @@ describe('withSentryConfig', () => { const finalConfig = materializeFinalNextConfig(cleanConfig, undefined, sentryOptions); expect(finalConfig.productionBrowserSourceMaps).toBe(true); - expect(sentryOptions.sourcemaps).toHaveProperty('deleteSourcemapsAfterUpload', true); + expect(getDeleteSourceMapsOption(sentryOptions)).toBe(true); expect(finalConfig.env).toHaveProperty('_sentryRelease', 'custom-release-1.0.0'); // Restore original env var diff --git a/packages/nitro/src/sourceMaps.ts b/packages/nitro/src/sourceMaps.ts index a32df5f81100..9d57495b78b2 100644 --- a/packages/nitro/src/sourceMaps.ts +++ b/packages/nitro/src/sourceMaps.ts @@ -1,4 +1,4 @@ -import type { Options as BundlerPluginOptions } from '@sentry/bundler-plugins/core'; +import type { InternalOptions as BundlerPluginOptions } from '@sentry/bundler-plugins/core'; import { createSentryBuildPluginManager } from '@sentry/bundler-plugins/core'; import { resolveSourceMapsFeatures, warnOnConflictingSourceMapOptions } from '@sentry/core'; import type { Nitro, NitroConfig } from 'nitro/types'; @@ -120,7 +120,7 @@ export function getPluginOptions( if (options?.debug && defaultFilesToDelete && userFilesToDelete === undefined) { // eslint-disable-next-line no-console console.log( - `[@sentry/nitro] Setting \`sourcemaps.filesToDeleteAfterUpload: ["${defaultFilesToDelete[0]}"]\` to delete generated source maps after they were uploaded to Sentry.`, + `[@sentry/nitro] Deleting the generated source maps after the upload: ${defaultFilesToDelete.join(', ')}`, ); } @@ -140,7 +140,7 @@ export function getPluginOptions( injectDebugIds: options?.sourcemaps?.injectDebugIds, assets: options?.sourcemaps?.assets, ignore: options?.sourcemaps?.ignore, - filesToDeleteAfterUpload, + sdkFilesToDeleteAfterUpload: filesToDeleteAfterUpload, rewriteSources: options?.sourcemaps?.rewriteSources ?? ((source: string) => normalizePath(source)), }, release: options?.release, @@ -162,7 +162,7 @@ export function getPluginOptions( 3. User did not set source maps (undefined) - We enable source maps when Sentry uploads them, or when `sourcemaps.delete: false` keeps them for a manual upload. Otherwise we leave the setting unset - - Configure `filesToDeleteAfterUpload` to clean up .map files after upload + - Delete the .map files after the upload */ export function configureSourcemapSettings( config: NitroConfig, @@ -185,7 +185,7 @@ export function configureSourcemapSettings( usesSourceMaps && // eslint-disable-next-line no-console console.warn( - '[@sentry/nitro] You have explicitly disabled source maps (`sourcemap: false`). Sentry will not upload source maps, and errors will not be unminified. To let Sentry handle source maps, remove the `sourcemap` option from your Nitro config, or use `sourcemaps: { disable: true }` in your Sentry options to silence this warning.', + '[@sentry/nitro] You have explicitly disabled source maps (`sourcemap: false`). Sentry will not upload source maps, and errors will not be unminified. To let Sentry handle source maps, remove the `sourcemap` option from your Nitro config, or set `sourcemaps: { upload: false }` in your Sentry options to silence this warning.', ); return { sentryEnabledSourcemaps: false }; } diff --git a/packages/nitro/test/sourceMaps.test.ts b/packages/nitro/test/sourceMaps.test.ts index 47d4f78f569f..8afaf0f021ae 100644 --- a/packages/nitro/test/sourceMaps.test.ts +++ b/packages/nitro/test/sourceMaps.test.ts @@ -28,7 +28,7 @@ describe('getPluginOptions', () => { debug: false, silent: false, sourcemaps: expect.objectContaining({ - filesToDeleteAfterUpload: ['/project/.output/server/**/*.map'], + sdkFilesToDeleteAfterUpload: ['/project/.output/server/**/*.map'], rewriteSources: expect.any(Function), }), _metaOptions: expect.objectContaining({ @@ -38,6 +38,7 @@ describe('getPluginOptions', () => { }), }), ); + expect(options.sourcemaps?.filesToDeleteAfterUpload).toBeUndefined(); expect(options.org).toBeUndefined(); expect(options.project).toBeUndefined(); expect(options.authToken).toBeUndefined(); @@ -47,7 +48,7 @@ describe('getPluginOptions', () => { it('does not default filesToDeleteAfterUpload when user enabled sourcemaps themselves', () => { const options = getPluginOptions(undefined, false); - expect(options.sourcemaps?.filesToDeleteAfterUpload).toBeUndefined(); + expect(options.sourcemaps?.sdkFilesToDeleteAfterUpload).toBeUndefined(); }); it('respects user-provided filesToDeleteAfterUpload even when Sentry enabled sourcemaps', () => { @@ -57,14 +58,16 @@ describe('getPluginOptions', () => { '/project/.output/server', ); - expect(options.sourcemaps?.filesToDeleteAfterUpload).toEqual(['dist/**/*.map']); + expect(options.sourcemaps?.sdkFilesToDeleteAfterUpload).toEqual(['dist/**/*.map']); }); - it('logs the default filesToDeleteAfterUpload glob in debug mode', () => { + it('logs the default deletion glob in debug mode', () => { const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {}); getPluginOptions({ debug: true }, true, '/project/.output/server'); - expect(logSpy).toHaveBeenCalledWith(expect.stringContaining('/project/.output/server/**/*.map')); + expect(logSpy).toHaveBeenCalledWith( + '[@sentry/nitro] Deleting the generated source maps after the upload: /project/.output/server/**/*.map', + ); logSpy.mockRestore(); }); @@ -76,7 +79,7 @@ describe('getPluginOptions', () => { '/project/.output/server', ); - expect(logSpy).not.toHaveBeenCalledWith(expect.stringContaining('filesToDeleteAfterUpload')); + expect(logSpy).not.toHaveBeenCalledWith(expect.stringContaining('Deleting the generated source maps')); logSpy.mockRestore(); }); @@ -143,7 +146,7 @@ describe('getPluginOptions', () => { expect(options.release).toEqual({ name: 'v1.0.0' }); expect(options.sourcemaps?.assets).toEqual(['dist/**']); expect(options.sourcemaps?.ignore).toEqual(['dist/test/**']); - expect(options.sourcemaps?.filesToDeleteAfterUpload).toEqual(['dist/**/*.map']); + expect(options.sourcemaps?.sdkFilesToDeleteAfterUpload).toEqual(['dist/**/*.map']); }); it('normalizes source paths via rewriteSources', () => { @@ -198,6 +201,14 @@ describe('configureSourcemapSettings', () => { warnSpy.mockRestore(); }); + it('does not warn about `sourcemap: false` with `sourcemaps.upload: false`', () => { + const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {}); + configureSourcemapSettings({ sourcemap: false }, { sourcemaps: { upload: false } }); + + expect(warnSpy).not.toHaveBeenCalled(); + warnSpy.mockRestore(); + }); + it('does not modify experimental config when user disabled sourcemaps', () => { vi.spyOn(console, 'warn').mockImplementation(() => {}); const config: NitroConfig = { sourcemap: false }; @@ -322,7 +333,7 @@ describe('getPluginOptions with the new source map options', () => { '/output/server', ); - expect(result.sourcemaps?.filesToDeleteAfterUpload).toEqual(expected); + expect(result.sourcemaps?.sdkFilesToDeleteAfterUpload).toEqual(expected); }); }); diff --git a/packages/nuxt/src/vite/sourceMapDeletion.ts b/packages/nuxt/src/vite/sourceMapDeletion.ts index 7d1089d6986b..92cf4b67a6ca 100644 --- a/packages/nuxt/src/vite/sourceMapDeletion.ts +++ b/packages/nuxt/src/vite/sourceMapDeletion.ts @@ -83,13 +83,13 @@ export function logSentryEnabledSourceMaps(fallback: DeletionFallback, deleteOpt } else if (fallback[side]) { // eslint-disable-next-line no-console console.log( - `[Sentry] We enabled \`'hidden'\` source maps for your ${side}-side build. Sentry deletes them after the upload, unless you set \`sourcemaps.filesToDeleteAfterUpload\`.`, + `[Sentry] We enabled \`'hidden'\` source maps for your ${side}-side build. Sentry deletes them after the upload. Set \`sourcemaps.delete: false\` to keep them.`, ); } } } -/** `filesToDeleteAfterUpload` is matched from the working directory and needs forward slashes, also on Windows. */ +/** The deletion globs are matched from the working directory and need forward slashes, also on Windows. */ function toGlobPath(directory: string): string { return path.relative(process.cwd(), directory).split(path.sep).join('/') || '.'; } @@ -107,7 +107,7 @@ function toGlobPath(directory: string): string { * the same rules to the server maps there. */ export function withClientSourceMapDeletion( - options: Options, + options: InternalOptions, userSourcemaps: Pick, 'delete' | 'filesToDeleteAfterUpload'> | undefined, fallback: DeletionFallback, viteServer = false, @@ -127,6 +127,7 @@ export function withClientSourceMapDeletion( sourcemaps: { ...options.sourcemaps, filesToDeleteAfterUpload: undefined, + sdkFilesToDeleteAfterUpload: undefined, delete: undefined, deleteSourcemapsAfterUpload: undefined, // The Vite plugin reads this in its `config` hook, after `modules:done` set the fallback. @@ -152,12 +153,13 @@ function isClientEnvironment(environment: string | undefined): boolean { return environment === undefined || environment === 'client'; } -export function withoutSourceMapDeletion(options: Options): InternalOptions { +export function withoutSourceMapDeletion(options: InternalOptions): InternalOptions { return { ...options, sourcemaps: { ...options.sourcemaps, filesToDeleteAfterUpload: undefined, + sdkFilesToDeleteAfterUpload: undefined, delete: undefined, deleteSourcemapsAfterUpload: undefined, sdkDeleteSourceMaps: false, @@ -165,18 +167,18 @@ export function withoutSourceMapDeletion(options: Options): InternalOptions { }; } -export async function deleteSourceMapsAfterBuild(options: Options): Promise { - const filesToDeleteAfterUpload = await options.sourcemaps?.filesToDeleteAfterUpload; +export async function deleteSourceMapsAfterBuild(options: InternalOptions): Promise { + const sdkFilesToDeleteAfterUpload = await options.sourcemaps?.sdkFilesToDeleteAfterUpload; - if (filesToDeleteAfterUpload === undefined) { + if (sdkFilesToDeleteAfterUpload === undefined) { return; } - const deletionOptions: Options = { + const deletionOptions: InternalOptions = { ...options, sourcemaps: { ...options.sourcemaps, - filesToDeleteAfterUpload, + sdkFilesToDeleteAfterUpload, }, }; @@ -189,17 +191,17 @@ export async function deleteSourceMapsAfterBuild(options: Options): Promise { - const filesToDeleteAfterUpload = await options.sourcemaps?.filesToDeleteAfterUpload; +export async function deletePublicSourceMaps(options: InternalOptions, publicDir: string): Promise { + const sdkFilesToDeleteAfterUpload = await options.sourcemaps?.sdkFilesToDeleteAfterUpload; - if (filesToDeleteAfterUpload === undefined) { + if (sdkFilesToDeleteAfterUpload === undefined) { return; } - const files = await globFiles(filesToDeleteAfterUpload); + const files = await globFiles(sdkFilesToDeleteAfterUpload); const publicFiles = files.filter(file => isInDirectory(file, publicDir)); await Promise.all( diff --git a/packages/nuxt/src/vite/sourceMaps.ts b/packages/nuxt/src/vite/sourceMaps.ts index 655f5768f148..619b25910c09 100644 --- a/packages/nuxt/src/vite/sourceMaps.ts +++ b/packages/nuxt/src/vite/sourceMaps.ts @@ -1,7 +1,7 @@ import type { Nuxt } from '@nuxt/schema'; -import { resolveReleaseName } from '@sentry/bundler-plugins/core'; -import { sentryRollupPlugin, type SentryRollupPluginOptions } from '@sentry/bundler-plugins/rollup'; -import { sentryVitePlugin, type SentryVitePluginOptions } from '@sentry/bundler-plugins/vite'; +import { type InternalOptions, resolveReleaseName } from '@sentry/bundler-plugins/core'; +import { sentryRollupPlugin } from '@sentry/bundler-plugins/rollup'; +import { sentryVitePlugin } from '@sentry/bundler-plugins/vite'; import { resolveSourceMapsFeatures, warnOnRemovedBuildOptions } from '@sentry/core'; import type { NitroConfig } from 'nitropack'; import type { Plugin } from 'vite'; @@ -180,8 +180,8 @@ export function setupSourceMaps( function moveClientReleaseToRuntimeConfig( nuxt: Nuxt, moduleOptions: SentryNuxtModuleOptions, - pluginOptions: SentryVitePluginOptions, -): SentryVitePluginOptions { + pluginOptions: InternalOptions, +): InternalOptions { if (moduleOptions.release?.inject === false) { return pluginOptions; } @@ -210,7 +210,7 @@ function normalizePath(path: string): string { export function getPluginOptions( moduleOptions: SentryNuxtModuleOptions, shouldDeleteFilesFallback?: DeletionFallback, -): SentryVitePluginOptions | SentryRollupPluginOptions { +): InternalOptions { const sourcemapsOptions = moduleOptions.sourcemaps || {}; const filesToDeleteAfterUpload = resolveFilesToDeleteAfterUpload(moduleOptions, shouldDeleteFilesFallback); @@ -243,13 +243,13 @@ export function getPluginOptions( upload: sourcemapsOptions.upload, injectDebugIds: sourcemapsOptions.injectDebugIds, // `sourcemaps.delete` does not reach the plugins: `withClientSourceMapDeletion` and - // `filesToDeleteAfterUpload` apply it, because Nitro still needs the maps of the SSR build. + // `sdkFilesToDeleteAfterUpload` apply it, because Nitro still needs the maps of the SSR build. // The server/client files are in different places depending on the nitro preset (e.g. '.output/server' or '.netlify/functions-internal/server') // We cannot determine automatically how the build folder looks like (depends on the preset), so each plugin uploads its own build output (the vitePlugin for the Nuxt client and the rollupPlugin for Nitro). // If we could know where the server/client assets are located, we could do something like this (based on the Nitro preset): isNitro ? ['./.output/server/**/*'] : ['./.output/public/**/*'], assets: sourcemapsOptions.assets ?? undefined, ignore: sourcemapsOptions.ignore ?? undefined, - filesToDeleteAfterUpload, + sdkFilesToDeleteAfterUpload: filesToDeleteAfterUpload, rewriteSources: sourcemapsOptions.rewriteSources ?? normalizePath, resolveSourceMap: sourcemapsOptions.resolveSourceMap, }, @@ -284,12 +284,7 @@ function resolveFilesToDeleteAfterUpload( if (typeof filesToDeleteAfterUpload === 'undefined' && shouldDeleteFilesAfterUpload && moduleOptions.debug) { // eslint-disable-next-line no-console - console.log( - `[Sentry] Setting \`sentry.sourcemaps.filesToDeleteAfterUpload: [${fallbackFilesToDelete - // Logging it as strings in the array - .map(path => `"${path}"`) - .join(', ')}]\` to delete generated source maps after they were uploaded to Sentry.`, - ); + console.log(`[Sentry] Deleting the generated source maps after the upload: ${fallbackFilesToDelete.join(', ')}`); } return filesToDeleteAfterUpload !== undefined @@ -309,8 +304,8 @@ function resolveFilesToDeleteAfterUpload( - we enable 'hidden' source maps generation when Sentry uploads the maps, or when `sourcemaps.delete: false` keeps them for a manual upload. Otherwise we leave it unset - client with the Vite builder: pass `sdkDeleteSourceMaps: true`, so the maps never reach the build output - - client with another builder: configure `filesToDeleteAfterUpload` for the .map files in Nitro's public dir - - server: configure `filesToDeleteAfterUpload` to delete the .map files after the build (we emit a log about this) + - client with another builder: delete the .map files in Nitro's public dir + - server: delete the .map files after the build (we emit a log about this) Users only have to explicitly enable client source maps. Sentry only overwrites the base Nuxt source map settings as they propagate. */ diff --git a/packages/nuxt/test/vite/sourceMapDeletion.test.ts b/packages/nuxt/test/vite/sourceMapDeletion.test.ts index 73f180cd5c83..9e66e8576e4f 100644 --- a/packages/nuxt/test/vite/sourceMapDeletion.test.ts +++ b/packages/nuxt/test/vite/sourceMapDeletion.test.ts @@ -45,7 +45,7 @@ describe('deletePublicSourceMaps', () => { await deletePublicSourceMaps( { sourcemaps: { - filesToDeleteAfterUpload: [toGlob('.*/**/public*/**/*.map'), toGlob('.*/**/server/**/*.map')], + sdkFilesToDeleteAfterUpload: [toGlob('.*/**/public*/**/*.map'), toGlob('.*/**/server/**/*.map')], }, }, publicDir, @@ -61,7 +61,7 @@ describe('deletePublicSourceMaps', () => { it('keeps the files in the public dir that no pattern matches', async () => { await deletePublicSourceMaps( - { sourcemaps: { filesToDeleteAfterUpload: toGlob('.output/public/_nuxt/pages/*.map') } }, + { sourcemaps: { sdkFilesToDeleteAfterUpload: toGlob('.output/public/_nuxt/pages/*.map') } }, publicDir, ); @@ -76,7 +76,7 @@ describe('deletePublicSourceMaps', () => { it('resolves a promised list of patterns', async () => { await deletePublicSourceMaps( - { sourcemaps: { filesToDeleteAfterUpload: Promise.resolve([toGlob('.output/public/**/*.map')]) } }, + { sourcemaps: { sdkFilesToDeleteAfterUpload: Promise.resolve([toGlob('.output/public/**/*.map')]) } }, publicDir, ); diff --git a/packages/nuxt/test/vite/sourceMaps-nuxtHooks.test.ts b/packages/nuxt/test/vite/sourceMaps-nuxtHooks.test.ts index c36ea805aea3..ed2f9edb7593 100644 --- a/packages/nuxt/test/vite/sourceMaps-nuxtHooks.test.ts +++ b/packages/nuxt/test/vite/sourceMaps-nuxtHooks.test.ts @@ -370,6 +370,7 @@ describe('setupSourceMaps hooks', () => { assets: undefined, ignore: undefined, filesToDeleteAfterUpload: undefined, + sdkFilesToDeleteAfterUpload: undefined, deleteSourcemapsAfterUpload: undefined, sdkDeleteSourceMaps: expect.any(Function), rewriteSources: expect.any(Function), @@ -377,7 +378,7 @@ describe('setupSourceMaps hooks', () => { }); }); - it('sentryRollupPlugin is called without filesToDeleteAfterUpload when source maps are explicitly enabled', async () => { + it('sentryRollupPlugin is called without deletion globs when source maps are explicitly enabled', async () => { const mockNuxt = createMockNuxt({ _prepare: false, dev: false, @@ -393,7 +394,10 @@ describe('setupSourceMaps hooks', () => { expect(mockSentryRollupPlugin).toHaveBeenCalledWith( expect.objectContaining({ - sourcemaps: expect.objectContaining({ filesToDeleteAfterUpload: undefined }), + sourcemaps: expect.objectContaining({ + filesToDeleteAfterUpload: undefined, + sdkFilesToDeleteAfterUpload: undefined, + }), }), ); }); @@ -415,6 +419,7 @@ describe('setupSourceMaps hooks', () => { expect(mockNuxt.options.sourcemap).toEqual({ client: 'hidden', server: true }); expect(getDeleteOption()).toBe(true); expect(capturedViteOptions.options?.sourcemaps?.filesToDeleteAfterUpload).toBeUndefined(); + expect(capturedViteOptions.options?.sourcemaps?.sdkFilesToDeleteAfterUpload).toBeUndefined(); }); // The plugin then also removes the maps of chunks that the user's `assets` or `ignore` leave out. @@ -529,9 +534,9 @@ describe('setupSourceMaps hooks', () => { return mockNuxt; } - function expectFilesDeletedAfterBuild(filesToDeleteAfterUpload: string[]): void { + function expectFilesDeletedAfterBuild(sdkFilesToDeleteAfterUpload: string[]): void { expect(mockCreateSentryBuildPluginManager).toHaveBeenCalledWith( - expect.objectContaining({ sourcemaps: expect.objectContaining({ filesToDeleteAfterUpload }) }), + expect.objectContaining({ sourcemaps: expect.objectContaining({ sdkFilesToDeleteAfterUpload }) }), { buildTool: 'nuxt', loggerPrefix: '[Sentry Nuxt]' }, ); } @@ -610,9 +615,12 @@ describe('setupSourceMaps hooks', () => { await mockNuxt.triggerHook('close'); expect(capturedViteOptions.options?.sourcemaps?.filesToDeleteAfterUpload).toBeUndefined(); + expect(capturedViteOptions.options?.sourcemaps?.sdkFilesToDeleteAfterUpload).toBeUndefined(); expect(getDeleteOption()).toBeUndefined(); expect(mockCreateSentryBuildPluginManager).toHaveBeenCalledWith( - expect.objectContaining({ sourcemaps: expect.objectContaining({ filesToDeleteAfterUpload }) }), + expect.objectContaining({ + sourcemaps: expect.objectContaining({ sdkFilesToDeleteAfterUpload: filesToDeleteAfterUpload }), + }), { buildTool: 'nuxt', loggerPrefix: '[Sentry Nuxt]' }, ); }); @@ -634,7 +642,7 @@ describe('setupSourceMaps hooks', () => { expect(mockCreateSentryBuildPluginManager).toHaveBeenCalledWith( expect.objectContaining({ - sourcemaps: expect.objectContaining({ filesToDeleteAfterUpload: defaultFilesToDeleteAfterUpload }), + sourcemaps: expect.objectContaining({ sdkFilesToDeleteAfterUpload: defaultFilesToDeleteAfterUpload }), }), { buildTool: 'nuxt', loggerPrefix: '[Sentry Nuxt]' }, ); @@ -669,7 +677,7 @@ describe('setupSourceMaps hooks', () => { expect(mockCreateSentryBuildPluginManager).toHaveBeenCalledWith( expect.objectContaining({ - sourcemaps: expect.objectContaining({ filesToDeleteAfterUpload }), + sourcemaps: expect.objectContaining({ sdkFilesToDeleteAfterUpload: filesToDeleteAfterUpload }), }), { buildTool: 'nuxt', loggerPrefix: '[Sentry Nuxt]' }, ); @@ -895,7 +903,7 @@ describe('setupSourceMaps hooks', () => { for (const side of ['client', 'server']) { expect(consoleLogSpy).toHaveBeenCalledWith( - `[Sentry] We enabled \`'hidden'\` source maps for your ${side}-side build. Sentry deletes them after the upload, unless you set \`sourcemaps.filesToDeleteAfterUpload\`.`, + `[Sentry] We enabled \`'hidden'\` source maps for your ${side}-side build. Sentry deletes them after the upload. Set \`sourcemaps.delete: false\` to keep them.`, ); } }, diff --git a/packages/nuxt/test/vite/sourceMaps.test.ts b/packages/nuxt/test/vite/sourceMaps.test.ts index e6df2bfc5305..90c3334987b9 100644 --- a/packages/nuxt/test/vite/sourceMaps.test.ts +++ b/packages/nuxt/test/vite/sourceMaps.test.ts @@ -105,7 +105,7 @@ describe('getPluginOptions', () => { sourcemaps: expect.objectContaining({ assets: ['custom-assets/**/*'], ignore: ['ignore-this.js'], - filesToDeleteAfterUpload: ['delete-this.js'], + sdkFilesToDeleteAfterUpload: ['delete-this.js'], rewriteSources: expect.any(Function), }), _metaOptions: expect.objectContaining({ @@ -256,7 +256,7 @@ describe('getPluginOptions', () => { expected: undefined, }, ])( - 'sets filesToDeleteAfterUpload correctly when $name', + 'sets sdkFilesToDeleteAfterUpload correctly when $name', ({ clientFallback, serverFallback, customOptions = {}, serverDir = NODE_SERVER_DIR, expected }) => { const options = getPluginOptions(customOptions as SentryNuxtModuleOptions, { client: clientFallback, @@ -264,7 +264,8 @@ describe('getPluginOptions', () => { serverDir: serverDir ?? undefined, }); - expect(options?.sourcemaps?.filesToDeleteAfterUpload).toEqual(expected); + expect(options?.sourcemaps?.sdkFilesToDeleteAfterUpload).toEqual(expected); + expect(options?.sourcemaps?.filesToDeleteAfterUpload).toBeUndefined(); }, ); }); diff --git a/packages/react-router/src/vite/buildEnd/handleOnBuildEnd.ts b/packages/react-router/src/vite/buildEnd/handleOnBuildEnd.ts index a83b7ab5d279..265da9c130c3 100644 --- a/packages/react-router/src/vite/buildEnd/handleOnBuildEnd.ts +++ b/packages/react-router/src/vite/buildEnd/handleOnBuildEnd.ts @@ -137,11 +137,7 @@ export const sentryOnBuildEnd: BuildEndHook = async ({ reactRouterConfig, viteCo updatedFilesToDeleteAfterUpload = defaultFilesToDelete; debug && // eslint-disable-next-line no-console - console.info( - `[Sentry] Automatically setting \`sourcemaps.filesToDeleteAfterUpload: ${JSON.stringify( - updatedFilesToDeleteAfterUpload, - )}\` to delete generated source maps after they were uploaded to Sentry.`, - ); + console.info(`[Sentry] Deleting the generated source maps after the upload: ${defaultFilesToDelete.join(', ')}`); } if (updatedFilesToDeleteAfterUpload) { try { diff --git a/packages/react-router/test/vite/buildEnd/handleOnBuildEnd.test.ts b/packages/react-router/test/vite/buildEnd/handleOnBuildEnd.test.ts index 61f223724d4e..056a0c2bbfc3 100644 --- a/packages/react-router/test/vite/buildEnd/handleOnBuildEnd.test.ts +++ b/packages/react-router/test/vite/buildEnd/handleOnBuildEnd.test.ts @@ -459,7 +459,9 @@ describe('sentryOnBuildEnd', () => { // @ts-expect-error - mocking the React config await sentryOnBuildEnd(config); - expect(consoleSpy).toHaveBeenCalledWith(expect.stringContaining('[Sentry] Automatically setting')); + expect(consoleSpy).toHaveBeenCalledWith( + expect.stringContaining('[Sentry] Deleting the generated source maps after the upload: '), + ); expect(consoleSpy).toHaveBeenCalledWith(expect.stringContaining('Deleting asset after upload:')); expect(mockSentrySdkInstance.sourcemap.inject).toHaveBeenCalledWith({ directory: '/build' }); diff --git a/packages/sveltekit/src/vite/sourceMaps.ts b/packages/sveltekit/src/vite/sourceMaps.ts index 24b94484f28e..3dfcad229994 100644 --- a/packages/sveltekit/src/vite/sourceMaps.ts +++ b/packages/sveltekit/src/vite/sourceMaps.ts @@ -79,7 +79,8 @@ export async function makeCustomSentryVitePlugins( }, sourcemaps: { ...options?.sourcemaps, - filesToDeleteAfterUpload: filesToDeleteAfterUploadPromise, + filesToDeleteAfterUpload: undefined, + sdkFilesToDeleteAfterUpload: filesToDeleteAfterUploadPromise, // The adapter runs after the bundler and still needs the source maps, so // the SDK deletes them from disk afterwards instead of the plugin. deleteSourcemapsAfterUpload: undefined, @@ -174,9 +175,7 @@ export async function makeCustomSentryVitePlugins( debug && // eslint-disable-next-line no-console console.info( - `[Sentry] Automatically setting \`sourcemaps.filesToDeleteAfterUpload: [${defaultFileDeletionGlob - .map(file => `"${file}"`) - .join(', ')}]\` to delete generated source maps after they were uploaded to Sentry.`, + `[Sentry] Deleting the generated source maps after the upload: ${defaultFileDeletionGlob.join(', ')}`, ); _resolveFilesToDeleteAfterUpload?.( @@ -332,7 +331,7 @@ export async function makeCustomSentryVitePlugins( * 3. Users didn't set source maps generation * - we enable 'hidden' source maps generation when Sentry uploads the maps, or when * `sourcemaps.delete: false` keeps them for a manual upload. Otherwise we leave it unset - * - configure `filesToDeleteAfterUpload` to delete all .map files (we emit a log about this) + * - delete all .map files after the upload (we emit a log about this) * * --> only exported for testing */ diff --git a/packages/sveltekit/test/vite/sourceMaps.test.ts b/packages/sveltekit/test/vite/sourceMaps.test.ts index f162821fc5ae..85b0e8b8ddf3 100644 --- a/packages/sveltekit/test/vite/sourceMaps.test.ts +++ b/packages/sveltekit/test/vite/sourceMaps.test.ts @@ -487,8 +487,9 @@ describe('source map deletion with `sourcemaps.delete`', () => { deleteSourcemapsAfterUpload: undefined, sdkDeleteSourceMaps: false, delete: undefined, + filesToDeleteAfterUpload: undefined, }); - return mergedOptions.sourcemaps?.filesToDeleteAfterUpload; + return mergedOptions.sourcemaps?.sdkFilesToDeleteAfterUpload; } beforeEach(() => { @@ -623,7 +624,7 @@ describe('deleteFilesAfterUpload', () => { inject: false, }, sourcemaps: { - filesToDeleteAfterUpload: expect.any(Promise), + sdkFilesToDeleteAfterUpload: expect.any(Promise), sdkDeleteSourceMaps: false, }, }); @@ -643,7 +644,7 @@ describe('deleteFilesAfterUpload', () => { // @ts-expect-error this function exists! await filesToDeleteAfterUploadSettingPlugin.configResolved(); - await expect(mergedOptions.sourcemaps.filesToDeleteAfterUpload).resolves.toEqual([ + await expect(mergedOptions.sourcemaps.sdkFilesToDeleteAfterUpload).resolves.toEqual([ './.*/**/*.map', './.svelte-kit/output/**/*.map', ]); @@ -703,7 +704,7 @@ describe('deleteFilesAfterUpload', () => { inject: false, }, sourcemaps: { - filesToDeleteAfterUpload: expect.any(Promise), + sdkFilesToDeleteAfterUpload: expect.any(Promise), sdkDeleteSourceMaps: false, }, }); @@ -723,7 +724,7 @@ describe('deleteFilesAfterUpload', () => { // @ts-expect-error this function exists! await filesToDeleteAfterUploadSettingPlugin.configResolved(); - await expect(mergedOptions.sourcemaps.filesToDeleteAfterUpload).resolves.toEqual( + await expect(mergedOptions.sourcemaps.sdkFilesToDeleteAfterUpload).resolves.toEqual( filesToDeleteAfterUploadExpected, ); }, From f95ffa7ebc692ebff5cf39b90709d3d6e3d363f2 Mon Sep 17 00:00:00 2001 From: Tim Fish Date: Wed, 2 Dec 2026 10:38:23 +0000 Subject: [PATCH 2/2] fix(nextjs): Don't turn on source maps when the after-compile hook does not run (#26935) Stacked on #26906. With the `runAfterProductionCompile` hook, only the hook uploads and deletes source maps. The SDK still turned source maps on when the hook was not set up, so they stayed in `.next/static`, where they are served publicly. - Turbopack: the SDK no longer sets `productionBrowserSourceMaps: true` when `useRunAfterProductionCompileHook` is `false`, or when `compiler.runAfterProductionCompile` is set to something that is not a function. - Webpack with `useRunAfterProductionCompileHook: true`: the SDK no longer changes `devtool` when the Next.js version is below 15.4.1, or when `compiler.runAfterProductionCompile` is not a function. - `sourcemaps.delete: false` still turns the maps on, because the user asked to keep them. - Source maps that the user turned on are not changed. - The two hook call sites now share one function. This keeps the file under the 300-line lint limit. - Covered by unit tests only. No E2E app builds with the hook off. --- .../nextjs/src/config/sourceMapOptions.ts | 9 ++- packages/nextjs/src/config/webpack.ts | 5 +- .../withSentryConfig/getFinalConfigObject.ts | 10 +++- .../getFinalConfigObjectBundlerUtils.ts | 60 ++++++++++--------- packages/nextjs/test/config/silent.test.ts | 2 +- .../test/config/sourceMapOptions.test.ts | 16 +++-- packages/nextjs/test/config/testUtils.ts | 1 + .../webpack/constructWebpackConfig.test.ts | 43 +++++++++++++ .../test/config/withSentryConfig.test.ts | 44 ++++++++++++++ 9 files changed, 151 insertions(+), 39 deletions(-) diff --git a/packages/nextjs/src/config/sourceMapOptions.ts b/packages/nextjs/src/config/sourceMapOptions.ts index f75fcc48adff..8b5b603ab8ec 100644 --- a/packages/nextjs/src/config/sourceMapOptions.ts +++ b/packages/nextjs/src/config/sourceMapOptions.ts @@ -8,11 +8,16 @@ type SourceMapsOptions = SentryBuildOptions['sourcemaps']; /** * Whether Sentry turns source maps on that the user did not set: when it can upload them, or when * `sourcemaps.delete: false` keeps them for a manual upload. + * + * @param uploadStepRuns Whether a build step runs that uploads and deletes the source maps. */ -export function sentryEnablesSourceMaps(options: SentryBuildOptions): boolean { +export function sentryEnablesSourceMaps(options: SentryBuildOptions, uploadStepRuns: boolean): boolean { const { sourcemaps } = options; const { injectDebugIds, upload } = resolveSourceMapsFeatures(sourcemaps); - return (upload && hasSourceMapUploadCredentials(options)) || (sourcemaps?.delete === false && injectDebugIds); + return ( + (uploadStepRuns && upload && hasSourceMapUploadCredentials(options)) || + (sourcemaps?.delete === false && injectDebugIds) + ); } export const SDK_DELETES_SOURCE_MAPS_MESSAGE = diff --git a/packages/nextjs/src/config/webpack.ts b/packages/nextjs/src/config/webpack.ts index 5bccaf206b6a..98017af0711d 100644 --- a/packages/nextjs/src/config/webpack.ts +++ b/packages/nextjs/src/config/webpack.ts @@ -58,6 +58,7 @@ export function constructWebpackConfigFunction({ routeManifest, nextJsVersion, useRunAfterProductionCompileHook, + sourceMapUploadStepRuns, vercelCronsConfigResult, }: { userNextConfig: NextConfigObject; @@ -66,6 +67,8 @@ export function constructWebpackConfigFunction({ routeManifest: RouteManifest | undefined; nextJsVersion: string | undefined; useRunAfterProductionCompileHook: boolean | undefined; + /** Whether a build step uploads and deletes the source maps. Without one, Sentry turns none on. */ + sourceMapUploadStepRuns: boolean; vercelCronsConfigResult: VercelCronsConfigResult; }): WebpackConfigFunction { // Will be called by nextjs and passed its default webpack configuration and context data about the build (whether @@ -367,7 +370,7 @@ export function constructWebpackConfigFunction({ loadModule<{ sentryWebpackPlugin: any }>('@sentry/bundler-plugins/webpack', module) ?? {}; if (sentryWebpackPlugin) { - if (sentryEnablesSourceMaps(userSentryOptions)) { + if (sentryEnablesSourceMaps(userSentryOptions, sourceMapUploadStepRuns)) { // Source maps can be configured in 3 ways: // 1. (next config): productionBrowserSourceMaps // 2. (next config): experimental.serverSourceMaps diff --git a/packages/nextjs/src/config/withSentryConfig/getFinalConfigObject.ts b/packages/nextjs/src/config/withSentryConfig/getFinalConfigObject.ts index 40261d2854f2..db5e727d940f 100644 --- a/packages/nextjs/src/config/withSentryConfig/getFinalConfigObject.ts +++ b/packages/nextjs/src/config/withSentryConfig/getFinalConfigObject.ts @@ -90,7 +90,7 @@ export function getFinalConfigObject( bundlerInfo, ); - maybeSetUpRunAfterProductionCompileHook({ + const runAfterProductionCompileHookIsSetUp = maybeSetUpRunAfterProductionCompileHook({ incomingUserNextConfigObject, userSentryOptions, releaseName, @@ -100,7 +100,12 @@ export function getFinalConfigObject( shouldUseRunAfterProductionCompileHook, }); - maybeEnableTurbopackSourcemaps(incomingUserNextConfigObject, userSentryOptions, bundlerInfo); + maybeEnableTurbopackSourcemaps( + incomingUserNextConfigObject, + userSentryOptions, + bundlerInfo, + runAfterProductionCompileHookIsSetUp, + ); maybeSetTurbopackTreeshakeDefines(incomingUserNextConfigObject, userSentryOptions, bundlerInfo); const buildTimeInstrumentation = resolveBuildTimeInstrumentationOption(userSentryOptions, bundlerInfo, nextJsVersion); @@ -115,6 +120,7 @@ export function getFinalConfigObject( routeManifest, nextJsVersion, shouldUseRunAfterProductionCompileHook, + hookIsSetUp: runAfterProductionCompileHookIsSetUp, bundlerInfo, vercelCronsConfigResult, }), diff --git a/packages/nextjs/src/config/withSentryConfig/getFinalConfigObjectBundlerUtils.ts b/packages/nextjs/src/config/withSentryConfig/getFinalConfigObjectBundlerUtils.ts index f1d8b20dc123..85fc1dae28fc 100644 --- a/packages/nextjs/src/config/withSentryConfig/getFinalConfigObjectBundlerUtils.ts +++ b/packages/nextjs/src/config/withSentryConfig/getFinalConfigObjectBundlerUtils.ts @@ -170,6 +170,8 @@ export function resolveUseRunAfterProductionCompileHookOption( * Hooks into Next.js' `compiler.runAfterProductionCompile` to run Sentry release/sourcemap handling. * * Note: this mutates `incomingUserNextConfigObject`. + * + * @returns Whether the hook is set up. */ export function maybeSetUpRunAfterProductionCompileHook({ incomingUserNextConfigObject, @@ -187,31 +189,30 @@ export function maybeSetUpRunAfterProductionCompileHook({ bundlerInfo: BundlerInfo; turboPackConfig: TurbopackOptions | undefined; shouldUseRunAfterProductionCompileHook: boolean; -}): void { - if (!shouldUseRunAfterProductionCompileHook) { - return; +}): boolean { + if (!shouldUseRunAfterProductionCompileHook || !supportsProductionCompileHook(nextJsVersion ?? '')) { + return false; } - if (!supportsProductionCompileHook(nextJsVersion ?? '')) { - return; - } + const runSentryHook = (distDir: string): Promise => + handleRunAfterProductionCompile( + { + releaseName, + distDir, + buildTool: bundlerInfo.isTurbopack ? 'turbopack' : 'webpack', + usesNativeDebugIds: bundlerInfo.isTurbopack ? turboPackConfig?.debugIds : undefined, + sriEnabled: !!incomingUserNextConfigObject.experimental?.sri, + }, + userSentryOptions, + ); if (incomingUserNextConfigObject?.compiler?.runAfterProductionCompile === undefined) { incomingUserNextConfigObject.compiler ??= {}; incomingUserNextConfigObject.compiler.runAfterProductionCompile = async ({ distDir }) => { - await handleRunAfterProductionCompile( - { - releaseName, - distDir, - buildTool: bundlerInfo.isTurbopack ? 'turbopack' : 'webpack', - usesNativeDebugIds: bundlerInfo.isTurbopack ? turboPackConfig?.debugIds : undefined, - sriEnabled: !!incomingUserNextConfigObject.experimental?.sri, - }, - userSentryOptions, - ); + await runSentryHook(distDir); }; - return; + return true; } if (typeof incomingUserNextConfigObject.compiler.runAfterProductionCompile === 'function') { @@ -221,40 +222,37 @@ export function maybeSetUpRunAfterProductionCompileHook({ async apply(target, thisArg, argArray) { const { distDir }: { distDir: string } = argArray[0] ?? { distDir: '.next' }; await target.apply(thisArg, argArray); - await handleRunAfterProductionCompile( - { - releaseName, - distDir, - buildTool: bundlerInfo.isTurbopack ? 'turbopack' : 'webpack', - usesNativeDebugIds: bundlerInfo.isTurbopack ? turboPackConfig?.debugIds : undefined, - sriEnabled: !!incomingUserNextConfigObject.experimental?.sri, - }, - userSentryOptions, - ); + await runSentryHook(distDir); }, }, ); - return; + return true; } getBuildLogger(userSentryOptions.silent).warn( '[@sentry/nextjs] The configured `compiler.runAfterProductionCompile` option is not a function. Will not run source map and release management logic.', ); + return false; } /** * For supported turbopack builds, auto-enables browser sourcemaps and defaults to deleting them after upload. * * Note: this mutates `incomingUserNextConfigObject`. + * + * @param hookIsSetUp Whether the `runAfterProductionCompile` hook is set up. Only this hook uploads and + * deletes the source maps of a turbopack build. Without it they would stay in `.next/static`, where + * they are served publicly. */ export function maybeEnableTurbopackSourcemaps( incomingUserNextConfigObject: NextConfigObject, userSentryOptions: SentryBuildOptions, bundlerInfo: BundlerInfo, + hookIsSetUp: boolean, ): void { // Enable source maps for turbopack builds const { isTurbopack, isTurbopackSupported } = bundlerInfo; - if (!isTurbopackSupported || !isTurbopack || !sentryEnablesSourceMaps(userSentryOptions)) { + if (!isTurbopackSupported || !isTurbopack || !sentryEnablesSourceMaps(userSentryOptions, hookIsSetUp)) { return; } @@ -334,6 +332,7 @@ export function getWebpackPatch({ routeManifest, nextJsVersion, shouldUseRunAfterProductionCompileHook, + hookIsSetUp, bundlerInfo, vercelCronsConfigResult, }: { @@ -343,6 +342,7 @@ export function getWebpackPatch({ routeManifest: RouteManifest | undefined; nextJsVersion: string | undefined; shouldUseRunAfterProductionCompileHook: boolean; + hookIsSetUp: boolean; bundlerInfo: BundlerInfo; vercelCronsConfigResult: VercelCronsConfigResult; }): Partial { @@ -358,6 +358,8 @@ export function getWebpackPatch({ routeManifest, nextJsVersion, useRunAfterProductionCompileHook: shouldUseRunAfterProductionCompileHook, + // With the hook option, the webpack plugins leave the upload and the deletion to the hook. + sourceMapUploadStepRuns: !shouldUseRunAfterProductionCompileHook || hookIsSetUp, vercelCronsConfigResult, }), }; diff --git a/packages/nextjs/test/config/silent.test.ts b/packages/nextjs/test/config/silent.test.ts index b0236067b765..f41dea40ab49 100644 --- a/packages/nextjs/test/config/silent.test.ts +++ b/packages/nextjs/test/config/silent.test.ts @@ -101,7 +101,7 @@ describe('`silent` build option', () => { ], [ 'turbopack source map auto-enabling', - (silent?: boolean) => maybeEnableTurbopackSourcemaps({}, { silent, debug: true }, TURBOPACK_SUPPORTED), + (silent?: boolean) => maybeEnableTurbopackSourcemaps({}, { silent, debug: true }, TURBOPACK_SUPPORTED, true), ], [ 'undetectable Next.js version', diff --git a/packages/nextjs/test/config/sourceMapOptions.test.ts b/packages/nextjs/test/config/sourceMapOptions.test.ts index 92dd29092771..ab18b8b4cb0b 100644 --- a/packages/nextjs/test/config/sourceMapOptions.test.ts +++ b/packages/nextjs/test/config/sourceMapOptions.test.ts @@ -36,14 +36,22 @@ describe('sentryEnablesSourceMaps', () => { [{ disable: 'disable-upload', delete: false }, true], [{ disable: true, upload: true }, true], ] as const)('with %j it returns %s', (sourcemaps, expected) => { - expect(sentryEnablesSourceMaps({ ...CREDENTIALS, sourcemaps })).toBe(expected); + expect(sentryEnablesSourceMaps({ ...CREDENTIALS, sourcemaps }, true)).toBe(expected); }); it.each([ [undefined, false], [{ delete: false }, true], ] as const)('without upload credentials, with %j it returns %s', (sourcemaps, expected) => { - expect(sentryEnablesSourceMaps({ sourcemaps })).toBe(expected); + expect(sentryEnablesSourceMaps({ sourcemaps }, true)).toBe(expected); + }); + + it.each([ + [undefined, false], + [{ upload: true }, false], + [{ delete: false }, true], + ] as const)('without an upload step, with %j it returns %s', (sourcemaps, expected) => { + expect(sentryEnablesSourceMaps({ ...CREDENTIALS, sourcemaps }, false)).toBe(expected); }); }); @@ -121,7 +129,7 @@ describe('mergeFilesToDeleteAfterUpload', () => { describe('maybeEnableTurbopackSourcemaps with the new source map options', () => { function run(sourcemaps: NonNullable, nextConfig: NextConfigObject = {}) { const userSentryOptions: SentryBuildOptions = { ...CREDENTIALS, sourcemaps }; - maybeEnableTurbopackSourcemaps(nextConfig, userSentryOptions, TURBOPACK_SUPPORTED); + maybeEnableTurbopackSourcemaps(nextConfig, userSentryOptions, TURBOPACK_SUPPORTED, true); return { nextConfig, sourcemaps: userSentryOptions.sourcemaps, @@ -159,7 +167,7 @@ describe('maybeEnableTurbopackSourcemaps with the new source map options', () => it('turns no source maps on without upload credentials', () => { const nextConfig: NextConfigObject = {}; - maybeEnableTurbopackSourcemaps(nextConfig, { sourcemaps: {} }, TURBOPACK_SUPPORTED); + maybeEnableTurbopackSourcemaps(nextConfig, { sourcemaps: {} }, TURBOPACK_SUPPORTED, true); expect(nextConfig.productionBrowserSourceMaps).toBeUndefined(); }); diff --git a/packages/nextjs/test/config/testUtils.ts b/packages/nextjs/test/config/testUtils.ts index 278ee9865600..ac3222ef9f8e 100644 --- a/packages/nextjs/test/config/testUtils.ts +++ b/packages/nextjs/test/config/testUtils.ts @@ -78,6 +78,7 @@ export async function materializeFinalWebpackConfig(options: { nextJsVersion: options.nextJsVersion, useRunAfterProductionCompileHook: options.useRunAfterProductionCompileHook ?? options.sentryBuildTimeOptions?.useRunAfterProductionCompileHook, + sourceMapUploadStepRuns: true, vercelCronsConfigResult: { config: undefined, strategy: undefined }, }); diff --git a/packages/nextjs/test/config/webpack/constructWebpackConfig.test.ts b/packages/nextjs/test/config/webpack/constructWebpackConfig.test.ts index ddc507187a3c..0c0faca7acd6 100644 --- a/packages/nextjs/test/config/webpack/constructWebpackConfig.test.ts +++ b/packages/nextjs/test/config/webpack/constructWebpackConfig.test.ts @@ -8,6 +8,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import * as getBuildPluginOptionsModule from '../../../src/config/getBuildPluginOptions'; import { getDeleteSourceMapsOption } from '../../../src/config/sourceMapOptions'; import type { SentryBuildOptions } from '../../../src/config/types'; +import * as util from '../../../src/config/util'; import { CLIENT_SDK_CONFIG_FILE, clientBuildContext, @@ -210,6 +211,48 @@ describe('constructWebpackConfigFunction()', () => { expect(finalWebpackConfig?.devtool).toBeUndefined(); }); + // With `useRunAfterProductionCompileHook`, the webpack plugins leave the upload and the deletion to + // the hook. Each row: why the hook is or is not set up, the Next.js config, the Next.js version, + // the user's `sourcemaps` options, and the client `devtool` of the final config. + it.each([ + ['the hook is set up', {}, '15.4.1', undefined, 'hidden-source-map'], + ['the Next.js version does not support the hook', {}, '15.3.0', undefined, undefined], + [ + '`compiler.runAfterProductionCompile` is not a function', + { compiler: { runAfterProductionCompile: 'not a function' } }, + '15.4.1', + undefined, + undefined, + ], + ['the hook is not set up and `delete` is `false`', {}, '15.3.0', { delete: false }, 'hidden-source-map'], + ] as const)( + 'sets the expected client devtool with `useRunAfterProductionCompileHook` when %s', + (_, nextConfig, nextJsVersion, sourcemaps, expectedDevtool) => { + const getNextjsVersionSpy = vi.spyOn(util, 'getNextjsVersion').mockReturnValue(nextJsVersion); + const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {}); + const sentryOptions: SentryBuildOptions = { useRunAfterProductionCompileHook: true, sourcemaps }; + + const finalNextConfig = materializeFinalNextConfig( + { + ...exportedNextConfig, + ...nextConfig, + webpack: () => ({ ...clientWebpackConfig }) as any, + } as typeof exportedNextConfig, + undefined, + sentryOptions, + ); + + const finalWebpackConfig = finalNextConfig.webpack?.(clientWebpackConfig, clientBuildContext); + + // Without the hook, no step uploads or deletes the source maps. They would be served publicly + // from `.next/static`. + expect(finalWebpackConfig?.devtool).toBe(expectedDevtool); + + getNextjsVersionSpy.mockRestore(); + warnSpy.mockRestore(); + }, + ); + it('passes useRunAfterProductionCompileHook to getBuildPluginOptions when enabled', async () => { const getBuildPluginOptionsSpy = vi.spyOn(getBuildPluginOptionsModule, 'getBuildPluginOptions'); vi.spyOn(coreServer, 'loadModule').mockImplementation(() => ({ diff --git a/packages/nextjs/test/config/withSentryConfig.test.ts b/packages/nextjs/test/config/withSentryConfig.test.ts index bf167defd132..f625b8f33f83 100644 --- a/packages/nextjs/test/config/withSentryConfig.test.ts +++ b/packages/nextjs/test/config/withSentryConfig.test.ts @@ -694,6 +694,50 @@ describe('withSentryConfig', () => { expect(getDeleteSourceMapsOption(sentryOptions)).toBeUndefined(); }); + it.each([ + ['`useRunAfterProductionCompileHook` is `false`', { useRunAfterProductionCompileHook: false }, {}], + [ + '`compiler.runAfterProductionCompile` is not a function', + {}, + { compiler: { runAfterProductionCompile: 'not a function' } }, + ], + ])('does not enable productionBrowserSourceMaps when %s', (_, sentryOptions: SentryBuildOptions, nextConfig) => { + process.env.TURBOPACK = '1'; + vi.spyOn(util, 'getNextjsVersion').mockReturnValue('15.4.1'); + vi.spyOn(console, 'warn').mockImplementation(() => {}); + + const cleanConfig = { ...exportedNextConfig, ...nextConfig }; + delete cleanConfig.productionBrowserSourceMaps; + + const finalConfig = materializeFinalNextConfig( + cleanConfig as typeof exportedNextConfig, + undefined, + sentryOptions, + ); + + // Only the hook uploads and deletes the source maps of a turbopack build. Without it they + // would be served publicly from `.next/static`. + expect(finalConfig.productionBrowserSourceMaps).toBeUndefined(); + expect(getDeleteSourceMapsOption(sentryOptions)).toBeUndefined(); + }); + + it('enables productionBrowserSourceMaps without the hook when `sourcemaps.delete` is `false`', () => { + process.env.TURBOPACK = '1'; + vi.spyOn(util, 'getNextjsVersion').mockReturnValue('15.4.1'); + + const cleanConfig = { ...exportedNextConfig }; + delete cleanConfig.productionBrowserSourceMaps; + + const sentryOptions: SentryBuildOptions = { + useRunAfterProductionCompileHook: false, + sourcemaps: { delete: false }, + }; + + const finalConfig = materializeFinalNextConfig(cleanConfig, undefined, sentryOptions); + + expect(finalConfig.productionBrowserSourceMaps).toBe(true); + }); + it('preserves explicitly configured deleteSourcemapsAfterUpload setting', () => { process.env.TURBOPACK = '1'; vi.spyOn(util, 'getNextjsVersion').mockReturnValue('15.4.1');