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
18 changes: 13 additions & 5 deletions packages/bundler-plugins/src/core/build-plugin-manager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -170,7 +170,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<void>;

Expand Down Expand Up @@ -1001,13 +1002,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...');

Expand Down
1 change: 1 addition & 0 deletions packages/bundler-plugins/src/core/options-mapping.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ export type NormalizedOptions = {
filesToDeleteAfterUpload?: string | string[] | Promise<string | string[] | undefined>;
deleteSourcemapsAfterUpload?: boolean;
sdkDeleteSourceMaps?: boolean | ((environment?: string) => boolean | undefined);
sdkFilesToDeleteAfterUpload?: string | string[] | Promise<string | string[] | undefined>;
}
| undefined;
release: {
Expand Down
14 changes: 10 additions & 4 deletions packages/bundler-plugins/src/core/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<Options, 'sourcemaps'> & {
sourcemaps?: NonNullable<Options['sourcemaps']> & {
Expand All @@ -754,5 +755,10 @@ export type InternalOptions = Omit<Options, 'sourcemaps'> & {
* 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<string | string[] | undefined>;
};
};
65 changes: 65 additions & 0 deletions packages/bundler-plugins/test/core/build-plugin-manager.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
4 changes: 2 additions & 2 deletions packages/nextjs/src/config/getBuildPluginOptions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down Expand Up @@ -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,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
34 changes: 26 additions & 8 deletions packages/nextjs/src/config/sourceMapOptions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<SentryBuildOptions>();

/**
* 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)
);
}

/**
Expand All @@ -37,19 +57,17 @@ 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(
userSourcemaps: SourceMapsOptions,
skipSourcemapsUpload: boolean,
): Pick<NonNullable<SentryBuildPluginOptions['sourcemaps']>, 'disable' | 'upload' | 'injectDebugIds'> {
if (skipSourcemapsUpload) {
return { disable: true };
return { upload: false, injectDebugIds: false };
}

const { disable, upload, injectDebugIds } = userSourcemaps ?? {};
const usesFeatureOptions = upload !== undefined || injectDebugIds !== undefined;
return { disable: disable ?? (usesFeatureOptions ? undefined : false), upload, injectDebugIds };
return { disable, upload, injectDebugIds };
}
18 changes: 9 additions & 9 deletions packages/nextjs/src/config/webpack.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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);
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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,
Expand All @@ -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);
}

/**
Expand Down
Loading
Loading