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
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
body {
font-family: sans-serif;
}
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import './globals.css';
import Link from 'next/link';
import { SpanContextProvider } from '../components/span-context';

Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import * as fs from 'fs';
import * as path from 'path';
import * as assert from 'assert/strict';
import { findSourceMapFiles } from '@sentry-internal/test-utils';
import { findSourceMapFiles, findSourceMappingUrlComments } from '@sentry-internal/test-utils';

const buildStdout = fs.readFileSync('.tmp_build_stdout', 'utf-8');
const buildStderr = fs.readFileSync('.tmp_build_stderr', 'utf-8');
Expand All @@ -25,3 +25,11 @@ assert.deepEqual(
[],
'Client bundle .map files found even though `sourcemaps.deleteSourcemapsAfterUpload` option is set!',
);
assert.deepEqual(
findSourceMappingUrlComments({
outputDir: path.join('.next', 'static'),
extensions: ['.js', '.mjs', '.cjs', '.css'],
}),
[],
'Client bundles reference source maps even though `sourcemaps.deleteSourcemapsAfterUpload` option is set!',
);
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
.page {
font-family: sans-serif;
}
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import Link from 'next/link';
import { ClientErrorDebugTools } from '../../components/client-error-debug-tools';
import styles from '../../components/page.module.css';

export default function Page() {
return (
<div>
<div className={styles.page}>
<h2>Page (/pages-router)</h2>
<ClientErrorDebugTools />
<Link href="/user/5" id="navigation">
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
body {
font-family: sans-serif;
}
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import './globals.css';
export default function Layout({ children }: { children: React.ReactNode }) {
return (
<html lang="en">
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ if (process.env.E2E_DELETE_SOURCEMAPS) {
const staticDir = '.next/static';
assert.deepEqual(findSourceMapFiles({ outputDir: staticDir }), [], `Expected no source maps in ${staticDir}`);
assert.deepEqual(
findSourceMappingUrlComments({ outputDir: staticDir }),
findSourceMappingUrlComments({ outputDir: staticDir, extensions: ['.js', '.mjs', '.cjs', '.css'] }),
[],
`Expected no sourceMappingURL comments in ${staticDir}`,
);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import * as assert from 'assert/strict';
import * as fs from 'fs';
import { findSourceMapFiles, getChunkUploadPosts, loadMockServerResults } from '@sentry-internal/test-utils';

const STATIC_DIR = '.next/static';

// `upload: false` with `delete: false`: nothing reaches Sentry, and the client source maps Sentry turned on
// stay with their debug IDs, ready for an upload with the CLI.
assert.deepEqual(getChunkUploadPosts(loadMockServerResults()), [], 'Expected no source map upload');

const sourceMaps = findSourceMapFiles({ outputDir: STATIC_DIR }).filter(file => /\.[cm]?js\.map$/.test(file));
assert.ok(sourceMaps.length > 0, `Expected Sentry to turn on and keep the source maps in ${STATIC_DIR}`);

const mapsWithDebugId = sourceMaps.filter(file => {
const map = JSON.parse(fs.readFileSync(file, 'utf8')) as { debug_id?: string; debugId?: string };
return !!(map.debug_id ?? map.debugId);
});
assert.ok(mapsWithDebugId.length > 0, `Expected source maps with a debug ID in ${STATIC_DIR}`);

console.log(` ${STATIC_DIR}: ${sourceMaps.length} kept source map(s), ${mapsWithDebugId.length} with a debug ID`);
console.log('All source map assertions passed!');
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
const { withSentryConfig } = require('@sentry/nextjs/config');

// `delete-option`: the app turns the client source maps on itself, and `sourcemaps.delete: true` removes them.
// `manual-upload`: Sentry uploads nothing and keeps the maps it turned on, for an upload with the CLI.
const variant = process.env.E2E_VARIANT;

/** @type {import('next').NextConfig} */
const nextConfig = {};
const nextConfig = variant === 'delete-option' ? { productionBrowserSourceMaps: true } : {};

module.exports = withSentryConfig(nextConfig, {
sentryUrl: 'http://localhost:3032',
Expand All @@ -11,9 +15,14 @@ module.exports = withSentryConfig(nextConfig, {
release: {
name: 'test-release',
},
sourcemaps: {
// The delete variants use the SDK default, which removes the client maps after the upload.
deleteSourcemapsAfterUpload: process.env.E2E_DELETE_SOURCEMAPS ? undefined : false,
},
sourcemaps:
variant === 'delete-option'
? { delete: true }
: variant === 'manual-upload'
? { upload: false, delete: false }
: {
// The delete variants use the SDK default, which removes the client maps after the upload.
deleteSourcemapsAfterUpload: process.env.E2E_DELETE_SOURCEMAPS ? undefined : false,
},
debug: true,
});
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,12 @@
"test:build:delete-webpack": "pnpm install && E2E_DELETE_SOURCEMAPS=1 E2E_NEXT_WEBPACK=1 pnpm build",
"test:build:delete-bun": "pnpm install && E2E_DELETE_SOURCEMAPS=1 bun --bun run build",
"test:build:delete-webpack-bun": "pnpm install && E2E_DELETE_SOURCEMAPS=1 E2E_NEXT_WEBPACK=1 bun --bun run build",
"test:assert:delete": "E2E_DELETE_SOURCEMAPS=1 pnpm test:assert"
"test:assert:delete": "E2E_DELETE_SOURCEMAPS=1 pnpm test:assert",
"test:build:delete-option": "pnpm install && E2E_VARIANT=delete-option pnpm build",
"test:build:delete-option-webpack": "pnpm install && E2E_VARIANT=delete-option E2E_NEXT_WEBPACK=1 pnpm build",
"test:build:manual-upload": "pnpm install && E2E_VARIANT=manual-upload pnpm build",
"test:build:manual-upload-webpack": "pnpm install && E2E_VARIANT=manual-upload E2E_NEXT_WEBPACK=1 pnpm build",
"test:assert:manual-upload": "pnpm ts-node --script-mode assert-manual-upload.ts"
},
"dependencies": {
"@sentry/nextjs": "file:../../packed/sentry-nextjs-packed.tgz",
Expand Down Expand Up @@ -51,6 +56,26 @@
"build-command": "pnpm test:build:delete-webpack-bun",
"assert-command": "pnpm test:assert:delete",
"label": "nextjs-16-sourcemaps (delete, webpack, bun)"
},
{
"build-command": "pnpm test:build:delete-option",
"assert-command": "pnpm test:assert:delete",
"label": "nextjs-16-sourcemaps (delete option, turbopack)"
},
{
"build-command": "pnpm test:build:delete-option-webpack",
"assert-command": "pnpm test:assert:delete",
"label": "nextjs-16-sourcemaps (delete option, webpack)"
},
{
"build-command": "pnpm test:build:manual-upload",
"assert-command": "pnpm test:assert:manual-upload",
"label": "nextjs-16-sourcemaps (manual upload, turbopack)"
},
{
"build-command": "pnpm test:build:manual-upload-webpack",
"assert-command": "pnpm test:assert:manual-upload",
"label": "nextjs-16-sourcemaps (manual upload, webpack)"
}
]
}
Expand Down
81 changes: 53 additions & 28 deletions packages/nextjs/src/config/getBuildPluginOptions.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,12 @@
import type { Options as SentryBuildPluginOptions } from '@sentry/bundler-plugins/core';
import type { InternalOptions as SentryBuildPluginOptions } from '@sentry/bundler-plugins/core';
import * as fs from 'fs';
import * as path from 'path';
import { getBuildLogger } from './buildLogger';
import {
getDeleteSourceMapsOption,
getSourceMapFeatureOptions,
mergeFilesToDeleteAfterUpload,
} from './sourceMapOptions';
import type { SentryBuildOptions } from './types';

const LOGGER_PREFIXES = {
Expand Down Expand Up @@ -179,30 +184,39 @@ function createSourcemapUploadIgnorePattern(
}

/**
* Creates file patterns for deletion after source map upload
* Creates file patterns for deletion after the source map upload that runs after the production compile.
* The webpack plugin removes the maps of webpack builds itself (see `deleteSourcemapsAfterUpload`).
*/
function createFilesToDeleteAfterUploadPattern(
normalizedDistPath: string,
buildTool: BuildTool,
deleteSourcemapsAfterUpload: boolean,
useRunAfterProductionCompileHook: boolean = false,
): string[] | undefined {
if (!deleteSourcemapsAfterUpload) {
if (!deleteSourcemapsAfterUpload || !buildTool.startsWith('after-production-compile')) {
return undefined;
}

return SOURCEMAP_EXTENSIONS.map(ext => path.posix.join(normalizedDistPath, 'static', '**', ext));
}

/**
* Whether the webpack plugin removes the source maps of this compiler from the build output.
*/
function shouldWebpackPluginDeleteSourcemaps(
buildTool: BuildTool,
deleteSourcemapsAfterUpload: boolean,
userFilesToDeleteAfterUpload: string | string[] | undefined,
useRunAfterProductionCompileHook: boolean = false,
): boolean {
// We don't want to delete source maps for server builds as this led to errors on Vercel in the past
// See: https://github.com/getsentry/sentry-javascript/issues/13099
if (buildTool === 'webpack-nodejs' || buildTool === 'webpack-edge') {
return undefined;
}

// Skip deletion for webpack client builds when using the experimental hook
if (buildTool === 'webpack-client' && useRunAfterProductionCompileHook) {
return undefined;
}

return SOURCEMAP_EXTENSIONS.map(ext => path.posix.join(normalizedDistPath, 'static', '**', ext));
// With the hook, the upload runs after the compile and must still find the maps.
return (
buildTool === 'webpack-client' &&
!useRunAfterProductionCompileHook &&
userFilesToDeleteAfterUpload === undefined &&
deleteSourcemapsAfterUpload
);
}

/**
Expand Down Expand Up @@ -287,7 +301,10 @@ export function getBuildPluginOptions({
const normalizedDistDirAbsPath = normalizePathForGlob(distDirAbsPath);
const loggerPrefix = LOGGER_PREFIXES[buildTool];
const widenClientFileUpload = sentryBuildOptions.widenClientFileUpload ?? false;
const deleteSourcemapsAfterUpload = sentryBuildOptions.sourcemaps?.deleteSourcemapsAfterUpload ?? false;
const userSourcemaps = sentryBuildOptions.sourcemaps;
const deleteSourcemapsAfterUpload = getDeleteSourceMapsOption(userSourcemaps) ?? false;
// `sourcemaps.delete: true` removes the source maps next to the user's `filesToDeleteAfterUpload`.
const userFilesReplaceDeletion = userSourcemaps?.delete !== true;

const sourcemapUploadAssets = createSourcemapUploadAssetPatterns(
normalizedDistDirAbsPath,
Expand All @@ -301,27 +318,30 @@ export function getBuildPluginOptions({

const userFilesToDeleteAfterUpload = sentryBuildOptions.sourcemaps?.filesToDeleteAfterUpload;

if (sentryBuildOptions.debug && userFilesToDeleteAfterUpload !== undefined) {
if (sentryBuildOptions.debug && userFilesToDeleteAfterUpload !== undefined && userFilesReplaceDeletion) {
logger.debug(
'[@sentry/nextjs] Skipping auto-deletion of source maps as user has provided filesToDeleteAfterUpload:',
userFilesToDeleteAfterUpload,
);
}

const filesToDeleteAfterUpload =
userFilesToDeleteAfterUpload !== undefined
? Array.isArray(userFilesToDeleteAfterUpload)
? userFilesToDeleteAfterUpload
: [userFilesToDeleteAfterUpload]
: createFilesToDeleteAfterUploadPattern(
normalizedDistDirAbsPath,
buildTool,
deleteSourcemapsAfterUpload,
useRunAfterProductionCompileHook,
);
const filesToDeleteAfterUpload = mergeFilesToDeleteAfterUpload(
createFilesToDeleteAfterUploadPattern(normalizedDistDirAbsPath, buildTool, deleteSourcemapsAfterUpload),
userFilesToDeleteAfterUpload,
userFilesReplaceDeletion,
);

const skipSourcemapsUpload = shouldSkipSourcemapUpload(buildTool, useRunAfterProductionCompileHook);

const webpackPluginDeletesSourcemaps = buildTool.startsWith('webpack')
? shouldWebpackPluginDeleteSourcemaps(
buildTool,
deleteSourcemapsAfterUpload,
userFilesReplaceDeletion ? userFilesToDeleteAfterUpload : undefined,
useRunAfterProductionCompileHook,
)
: undefined;

return {
// Only the browser reads these tags (`thirdPartyErrorFilterIntegration`), so server bundles skip the per-module cost.
applicationKey:
Expand All @@ -343,11 +363,16 @@ export function getBuildPluginOptions({
silent: sentryBuildOptions.silent,
url: sentryBuildOptions.sentryUrl,
sourcemaps: {
disable: skipSourcemapsUpload ? true : (sentryBuildOptions.sourcemaps?.disable ?? false),
...getSourceMapFeatureOptions(userSourcemaps, skipSourcemapsUpload),
// `sourcemaps.delete` does not reach the plugin, which would also remove the server source maps.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Since delete isn't forwarded, the plugin's conflict warnings never fire here: delete: false + filesToDeleteAfterUpload still deletes, and deleteSourcemapsAfterUpload is silently ignored when delete is set. Should we warn from the SDK, like we do for disable?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes. #26626 moves those warnings into @sentry/core, and a follow-up PR calls them from the SDKs that don't forward delete once both land.

rewriteSources: sentryBuildOptions.sourcemaps?.rewriteSources ?? rewriteWebpackSources,
assets: sentryBuildOptions.sourcemaps?.assets ?? sourcemapUploadAssets,
ignore: finalIgnorePatterns,
filesToDeleteAfterUpload,
deleteSourcemapsAfterUpload: webpackPluginDeletesSourcemaps,
// Every client map goes, also those the user turned on with `productionBrowserSourceMaps` or
// `devtool`, and those of chunks the upload leaves out.
sdkEnabledSourceMaps: webpackPluginDeletesSourcemaps,
resolveSourceMap: sentryBuildOptions.sourcemaps?.resolveSourceMap,
},
release: createReleaseConfig(releaseName, sentryBuildOptions),
Expand Down
10 changes: 7 additions & 3 deletions packages/nextjs/src/config/handleRunAfterProductionCompile.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
import type { createSentryBuildPluginManager as createSentryBuildPluginManagerType } from '@sentry/bundler-plugins/core';
import { resolveSourceMapsFeatures } from '@sentry/core';
import { loadModule } from '@sentry/core/server';
import * as fs from 'fs';
import * as path from 'path';
import { getBuildLogger } from './buildLogger';
import { getBuildPluginOptions } from './getBuildPluginOptions';
import { getDeleteSourceMapsOption } from './sourceMapOptions';
import type { SentryBuildOptions } from './types';

/**
Expand Down Expand Up @@ -59,7 +61,9 @@ export async function handleRunAfterProductionCompile(
await sentryBuildPluginManager.createRelease();

// Skip debug ID injection if sourcemaps are disabled which are only relevant for sourcemap correlation
if (!usesNativeDebugIds && sentryBuildOptions.sourcemaps?.disable !== true) {
const { injectDebugIds } = resolveSourceMapsFeatures(sentryBuildOptions.sourcemaps);

if (!usesNativeDebugIds && injectDebugIds) {
await sentryBuildPluginManager.injectDebugIds([distDir]);
}

Expand All @@ -68,7 +72,7 @@ export async function handleRunAfterProductionCompile(
prepareArtifacts: false,
});

const deleteSourcemapsAfterUpload = sentryBuildOptions.sourcemaps?.deleteSourcemapsAfterUpload ?? false;
const deleteSourcemapsAfterUpload = getDeleteSourceMapsOption(sentryBuildOptions.sourcemaps) ?? 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
Expand All @@ -77,7 +81,7 @@ export async function handleRunAfterProductionCompile(
deleteSourcemapsAfterUpload &&
buildTool === 'turbopack' &&
!sentryBuildOptions.sourcemaps?.assets &&
options.sourcemaps?.disable !== true
resolveSourceMapsFeatures(options.sourcemaps).injectDebugIds
) {
await warnAboutUncoveredSourcemaps(
path.join(distDir, 'static'),
Expand Down
53 changes: 53 additions & 0 deletions packages/nextjs/src/config/sourceMapOptions.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import type { InternalOptions as SentryBuildPluginOptions } from '@sentry/bundler-plugins/core';
import { resolveSourceMapsFeatures } from '@sentry/core';
import type { SentryBuildOptions } from './types';

type SourceMapsOptions = SentryBuildOptions['sourcemaps'];

/**
* Whether Sentry turns source maps on that the user did not set: when it uploads them, or when
* `sourcemaps.delete: false` keeps them for a manual upload.
*/
export function sentryEnablesSourceMaps(sourcemaps: SourceMapsOptions): boolean {
const { injectDebugIds, upload } = resolveSourceMapsFeatures(sourcemaps);
return upload || (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;
}

/**
* The user's `filesToDeleteAfterUpload` replace the SDK's patterns. With `sourcemaps.delete: true` both apply.
*/
export function mergeFilesToDeleteAfterUpload(
defaultFiles: string[] | undefined,
userFiles: string | string[] | undefined,
userFilesReplaceDeletion: boolean,
): string[] | undefined {
if (userFiles === undefined) {
return defaultFiles;
}

const userFilesArray = [userFiles].flat();
return defaultFiles && !userFilesReplaceDeletion ? [...defaultFiles, ...userFilesArray] : userFilesArray;
}

/**
* `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.
*/
// TODO(v12): Remove `disable`.
export function getSourceMapFeatureOptions(
userSourcemaps: SourceMapsOptions,
skipSourcemapsUpload: boolean,
): Pick<NonNullable<SentryBuildPluginOptions['sourcemaps']>, 'disable' | 'upload' | 'injectDebugIds'> {
if (skipSourcemapsUpload) {
return { disable: true };
}

const { disable, upload, injectDebugIds } = userSourcemaps ?? {};
const usesFeatureOptions = upload !== undefined || injectDebugIds !== undefined;
return { disable: disable ?? (usesFeatureOptions ? undefined : false), upload, injectDebugIds };
}
Loading
Loading