Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 7 additions & 2 deletions packages/nextjs/src/config/sourceMapOptions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 = true): 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 =
Expand Down
5 changes: 4 additions & 1 deletion packages/nextjs/src/config/webpack.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ export function constructWebpackConfigFunction({
routeManifest,
nextJsVersion,
useRunAfterProductionCompileHook,
sourceMapUploadStepRuns,
vercelCronsConfigResult,
}: {
userNextConfig: NextConfigObject;
Expand All @@ -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
Expand Down Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ export function getFinalConfigObject(
bundlerInfo,
);

maybeSetUpRunAfterProductionCompileHook({
const runAfterProductionCompileHookIsSetUp = maybeSetUpRunAfterProductionCompileHook({
incomingUserNextConfigObject,
userSentryOptions,
releaseName,
Expand All @@ -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);
Expand All @@ -115,6 +120,7 @@ export function getFinalConfigObject(
routeManifest,
nextJsVersion,
shouldUseRunAfterProductionCompileHook,
hookIsSetUp: runAfterProductionCompileHookIsSetUp,
bundlerInfo,
vercelCronsConfigResult,
}),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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<void> =>
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') {
Expand All @@ -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;
}

Expand Down Expand Up @@ -334,6 +332,7 @@ export function getWebpackPatch({
routeManifest,
nextJsVersion,
shouldUseRunAfterProductionCompileHook,
hookIsSetUp,
bundlerInfo,
vercelCronsConfigResult,
}: {
Expand All @@ -343,6 +342,7 @@ export function getWebpackPatch({
routeManifest: RouteManifest | undefined;
nextJsVersion: string | undefined;
shouldUseRunAfterProductionCompileHook: boolean;
hookIsSetUp: boolean;
bundlerInfo: BundlerInfo;
vercelCronsConfigResult: VercelCronsConfigResult;
}): Partial<NextConfigObject> {
Expand All @@ -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,
}),
};
Expand Down
2 changes: 1 addition & 1 deletion packages/nextjs/test/config/silent.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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',
Expand Down
4 changes: 2 additions & 2 deletions packages/nextjs/test/config/sourceMapOptions.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,7 @@ describe('mergeFilesToDeleteAfterUpload', () => {
describe('maybeEnableTurbopackSourcemaps with the new source map options', () => {
function run(sourcemaps: NonNullable<SentryBuildOptions['sourcemaps']>, nextConfig: NextConfigObject = {}) {
const userSentryOptions: SentryBuildOptions = { ...CREDENTIALS, sourcemaps };
maybeEnableTurbopackSourcemaps(nextConfig, userSentryOptions, TURBOPACK_SUPPORTED);
maybeEnableTurbopackSourcemaps(nextConfig, userSentryOptions, TURBOPACK_SUPPORTED, true);
return {
nextConfig,
sourcemaps: userSentryOptions.sourcemaps,
Expand Down Expand Up @@ -154,7 +154,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();
});
Expand Down
1 change: 1 addition & 0 deletions packages/nextjs/test/config/testUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 },
});

Expand Down
43 changes: 43 additions & 0 deletions packages/nextjs/test/config/webpack/constructWebpackConfig.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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(() => ({
Expand Down
44 changes: 44 additions & 0 deletions packages/nextjs/test/config/withSentryConfig.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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');
Expand Down
Loading