Skip to content

Commit dec1d10

Browse files
committed
feat(remix): Delete source maps through the bundler plugin instead of a glob
1 parent ff39dee commit dec1d10

7 files changed

Lines changed: 149 additions & 165 deletions

File tree

‎dev-packages/e2e-tests/test-applications/remix-sourcemaps/assert-build.ts‎

Lines changed: 17 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import * as assert from 'assert/strict';
22
import * as fs from 'fs';
33
import * as path from 'path';
4-
import { assertSourceMapUpload } from '@sentry-internal/test-utils';
4+
import { assertSourceMapUpload, findSourceMapFiles, findSourceMappingUrlComments } from '@sentry-internal/test-utils';
55

66
const BUILD_DIR = 'build';
77
const CLIENT_OUTPUT = path.join(BUILD_DIR, 'client');
@@ -39,13 +39,21 @@ for (const chunk of chunks) {
3939
}
4040
console.log(`no client chunk carries more than one debug ID (${chunks.length} chunks)\n`);
4141

42-
// The plugin defaults `filesToDeleteAfterUpload` when the app configures no source map setting. Remix
43-
// runs a client and an SSR pass with different `outDir`s, while the deletion glob is held in a promise
44-
// that settles once, so a leftover `.map` means the second pass was left behind.
45-
assertSourceMapUpload({
46-
outputDirs: [CLIENT_OUTPUT, SERVER_OUTPUT],
47-
strippedDirs: [BUILD_DIR],
48-
markers: { 'client source': 'SOURCEMAP_MARKER_CLIENT', 'server source': 'SOURCEMAP_MARKER_SERVER' },
49-
});
42+
// The SDK turns on hidden source maps when the app sets none, and asks the bundler plugin to
43+
// remove them from both the client and the SSR output, also when no upload runs.
44+
if (process.env.E2E_NO_UPLOAD) {
45+
assert.deepEqual(findSourceMapFiles({ outputDir: BUILD_DIR }), [], `Expected no source maps in ${BUILD_DIR}`);
46+
assert.deepEqual(
47+
findSourceMappingUrlComments({ outputDir: BUILD_DIR }),
48+
[],
49+
`Expected no sourceMappingURL comments in ${BUILD_DIR}`,
50+
);
51+
} else {
52+
assertSourceMapUpload({
53+
outputDirs: [CLIENT_OUTPUT, SERVER_OUTPUT],
54+
strippedDirs: [BUILD_DIR],
55+
markers: { 'client source': 'SOURCEMAP_MARKER_CLIENT', 'server source': 'SOURCEMAP_MARKER_SERVER' },
56+
});
57+
}
5058

5159
console.log('All sourcemap assertions passed!');

‎dev-packages/e2e-tests/test-applications/remix-sourcemaps/package.json‎

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,9 @@
66
"build": "node start-mock-sentry-server.mjs & remix vite:build > .tmp_build_stdout 2> .tmp_build_stderr; BUILD_EXIT=$?; kill %1 2>/dev/null; cat .tmp_build_stdout .tmp_build_stderr; exit $BUILD_EXIT",
77
"clean": "npx rimraf node_modules pnpm-lock.yaml",
88
"test:build": "pnpm install && pnpm build",
9-
"test:assert": "pnpm tsx assert-build.ts"
9+
"test:build:no-upload": "pnpm install && E2E_NO_UPLOAD=1 pnpm build",
10+
"test:assert": "pnpm tsx assert-build.ts",
11+
"test:assert:no-upload": "E2E_NO_UPLOAD=1 pnpm test:assert"
1012
},
1113
"dependencies": {
1214
"@sentry/remix": "file:../../packed/sentry-remix-packed.tgz",
@@ -26,5 +28,14 @@
2628
"tsx": "^4.23.0",
2729
"typescript": "^5.1.6",
2830
"vite": "^5.4.11"
31+
},
32+
"sentryTest": {
33+
"variants": [
34+
{
35+
"build-command": "pnpm test:build:no-upload",
36+
"assert-command": "pnpm test:assert:no-upload",
37+
"label": "remix-sourcemaps (no upload)"
38+
}
39+
]
2940
}
3041
}

‎dev-packages/e2e-tests/test-applications/remix-sourcemaps/vite.config.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ export default defineConfig({
88
ignoredRouteFiles: ['**/.*'],
99
}),
1010
sentryRemixVitePlugin({
11-
authToken: 'fake-auth-token',
11+
authToken: process.env.E2E_NO_UPLOAD ? undefined : 'fake-auth-token',
1212
org: 'test-org',
1313
project: 'test-project',
1414
sentryUrl: 'http://localhost:3033',

‎packages/remix/src/vite/index.ts‎

Lines changed: 11 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import type { Plugin } from 'vite';
22
import { makeOrchestrionPlugin } from './orchestrionPlugin';
33
import { makeRouteManifestPlugin } from './routeManifestPlugin';
4+
import type { SourceMapState } from './sourceMaps';
45
import { makeAddSentryVitePlugin, makeEnableSourceMapsPlugin } from './sourceMaps';
56
import type { SentryRemixVitePluginOptions } from './types';
67

@@ -42,18 +43,20 @@ export function sentryRemixVitePlugin(options: SentryRemixVitePluginOptions = {}
4243
return plugins;
4344
}
4445

45-
// Added even when source maps are disabled: the bundler plugin also applies bundle size
46-
// optimizations, module metadata, the application key and release management, and it already
47-
// skips the upload itself.
48-
//
49-
// Order matters: Vite passes the already-merged config to every `config` hook, so the deletion
50-
// plugin has to read `build.sourcemap` before `makeEnableSourceMapsPlugin` sets it to 'hidden'.
51-
plugins.push(...makeAddSentryVitePlugin(options));
46+
const sourceMapState: SourceMapState = { sdkEnabledSourceMaps: false };
5247

5348
// `'disable-upload'` still generates them - debug IDs are injected and the user uploads by hand.
49+
//
50+
// Order matters: the bundler plugin decides on the `build.sourcemap` it finds in its own
51+
// `config` hook, so this plugin has to set it first.
5452
if (options.sourcemaps?.disable !== true) {
55-
plugins.push(makeEnableSourceMapsPlugin(options));
53+
plugins.push(makeEnableSourceMapsPlugin(options, sourceMapState));
5654
}
5755

56+
// Added even when source maps are disabled: the bundler plugin also applies bundle size
57+
// optimizations, module metadata, the application key and release management, and it already
58+
// skips the upload itself.
59+
plugins.push(...makeAddSentryVitePlugin(options, sourceMapState));
60+
5861
return plugins;
5962
}

‎packages/remix/src/vite/sourceMaps.ts‎

Lines changed: 25 additions & 64 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,20 @@
1-
import * as path from 'path';
21
import { sentryVitePlugin } from '@sentry/bundler-plugins/vite';
32
import type { Plugin, UserConfig } from 'vite';
43
import type { SentryRemixVitePluginOptions } from './types';
54

6-
type FilesToDeleteAfterUpload = string | string[] | undefined;
5+
/** Shared by the two plugins of one build. */
6+
export type SourceMapState = {
7+
/** The SDK turned on hidden source maps because the user did not set `build.sourcemap`. */
8+
sdkEnabledSourceMaps: boolean;
9+
};
710

811
/**
912
* Adds the Sentry bundler plugin, which injects debug IDs and uploads source maps to Sentry.
1013
*/
11-
export function makeAddSentryVitePlugin(options: SentryRemixVitePluginOptions): Plugin[] {
14+
export function makeAddSentryVitePlugin(
15+
options: SentryRemixVitePluginOptions,
16+
state: SourceMapState = { sdkEnabledSourceMaps: false },
17+
): Plugin[] {
1218
const {
1319
applicationKey,
1420
authToken,
@@ -26,59 +32,7 @@ export function makeAddSentryVitePlugin(options: SentryRemixVitePluginOptions):
2632
telemetry,
2733
} = options;
2834

29-
// The default depends on `build.sourcemap`, which is only known once Vite resolves the config.
30-
let resolveFilesToDeleteAfterUpload: ((value: FilesToDeleteAfterUpload) => void) | undefined;
31-
const filesToDeleteAfterUploadPromise = new Promise<FilesToDeleteAfterUpload>(resolve => {
32-
resolveFilesToDeleteAfterUpload = resolve;
33-
});
34-
35-
const configPlugin: Plugin = {
36-
name: 'sentry-remix-files-to-delete-after-upload',
37-
apply: 'build',
38-
enforce: 'post',
39-
config(config) {
40-
const userFilesToDelete = sourcemaps?.filesToDeleteAfterUpload;
41-
42-
// Only clean up after ourselves: if the user asked for source maps, they are theirs to keep.
43-
// Scoped to the build output rather than `./**/*.map`, which the bundler plugin globs without
44-
// ignoring `node_modules` and then deletes with `force: true`.
45-
//
46-
// `disable: 'disable-upload'` injects debug IDs but leaves uploading to the user, and the
47-
// bundler plugin deletes in a `finally` block even when it skipped the upload - so defaulting
48-
// the deletion there would remove the very maps they still have to upload by hand.
49-
if (
50-
typeof userFilesToDelete === 'undefined' &&
51-
typeof config.build?.sourcemap === 'undefined' &&
52-
!sourcemaps?.disable
53-
) {
54-
// Derived from the configured `outDir` rather than hardcoding `build`, so a custom Remix
55-
// `buildDirectory` still gets cleaned up. Remix runs a client and an SSR build, each with
56-
// its own `outDir`, so each pass deletes only what it emitted.
57-
//
58-
// Separators are normalised because `glob` reads a backslash as an escape, and both path
59-
// flavours are checked because `path.isAbsolute` only recognises the host platform's form.
60-
// Only a relative path may take the `./` prefix: `.//abs/path/**/*.map` matches nothing.
61-
const outDir = (config.build?.outDir || 'build').replace(/\\/g, '/').replace(/\/+$/, '');
62-
const isAbsoluteOutDir = path.posix.isAbsolute(outDir) || path.win32.isAbsolute(outDir);
63-
const outDirGlob = isAbsoluteOutDir ? outDir : `./${outDir.replace(/^\.\//, '')}`;
64-
const filesToDelete = [`${outDirGlob}/**/*.map`];
65-
66-
if (debug) {
67-
// eslint-disable-next-line no-console
68-
console.log(
69-
`[Sentry] Automatically setting \`sourcemaps.filesToDeleteAfterUpload: ${JSON.stringify(
70-
filesToDelete,
71-
)}\` to delete generated source maps after they were uploaded to Sentry.`,
72-
);
73-
}
74-
resolveFilesToDeleteAfterUpload?.(filesToDelete);
75-
} else {
76-
resolveFilesToDeleteAfterUpload?.(userFilesToDelete);
77-
}
78-
},
79-
};
80-
81-
const sentryPlugins = sentryVitePlugin({
35+
return sentryVitePlugin({
8236
applicationKey,
8337
authToken: authToken ?? process.env.SENTRY_AUTH_TOKEN,
8438
bundleSizeOptimizations,
@@ -96,7 +50,13 @@ export function makeAddSentryVitePlugin(options: SentryRemixVitePluginOptions):
9650
ignore: sourcemaps?.ignore,
9751
rewriteSources: sourcemaps?.rewriteSources,
9852
resolveSourceMap: sourcemaps?.resolveSourceMap,
99-
filesToDeleteAfterUpload: filesToDeleteAfterUploadPromise,
53+
filesToDeleteAfterUpload: sourcemaps?.filesToDeleteAfterUpload,
54+
// Called when the bundler plugin decides, after `makeEnableSourceMapsPlugin` ran.
55+
// With `disable: 'disable-upload'` the user uploads the maps by hand, so they stay.
56+
deleteSourcemapsAfterUpload: () =>
57+
sourcemaps?.deleteSourcemapsAfterUpload ??
58+
(state.sdkEnabledSourceMaps && !sourcemaps?.disable ? true : undefined),
59+
sdkEnabledSourceMaps: () => state.sdkEnabledSourceMaps,
10060
},
10161
telemetry: telemetry ?? true,
10262
url: sentryUrl,
@@ -106,25 +66,26 @@ export function makeAddSentryVitePlugin(options: SentryRemixVitePluginOptions):
10666
},
10767
},
10868
});
109-
110-
return [configPlugin, ...sentryPlugins];
11169
}
11270

11371
/**
11472
* Enables "hidden" source maps if the user did not configure them.
11573
*/
116-
export function makeEnableSourceMapsPlugin(options: SentryRemixVitePluginOptions): Plugin {
74+
export function makeEnableSourceMapsPlugin(
75+
options: SentryRemixVitePluginOptions,
76+
state: SourceMapState = { sdkEnabledSourceMaps: false },
77+
): Plugin {
11778
return {
11879
name: 'sentry-remix-update-source-map-setting',
11980
apply: 'build',
12081
enforce: 'post',
12182
// Returning only the changed key: Vite concatenates arrays when merging a `config` return
12283
// value, so echoing the whole config back duplicates `ssr.noExternal`, `resolve.alias` etc.
12384
config(viteConfig) {
85+
const sourcemap = getUpdatedSourceMapSettings(viteConfig, options);
86+
state.sdkEnabledSourceMaps = sourcemap !== viteConfig.build?.sourcemap;
12487
return {
125-
build: {
126-
sourcemap: getUpdatedSourceMapSettings(viteConfig, options),
127-
},
88+
build: { sourcemap },
12889
};
12990
},
13091
};
@@ -141,7 +102,7 @@ export function makeEnableSourceMapsPlugin(options: SentryRemixVitePluginOptions
141102
*
142103
* 3. Users didn't set source maps generation
143104
* - we enable 'hidden' source maps generation
144-
* - configure `filesToDeleteAfterUpload` to delete all .map files (we emit a log about this)
105+
* - pass `deleteSourcemapsAfterUpload: true`, so the maps never reach the build output
145106
*
146107
* --> only exported for testing
147108
*/

‎packages/remix/test/vite/index.test.ts‎

Lines changed: 33 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -31,23 +31,32 @@ vi.mock('@sentry/server-utils/orchestrion/vite', () => ({
3131
type CapturedSentryOptions = {
3232
applicationKey?: string;
3333
bundleSizeOptimizations?: { excludeTracing?: boolean };
34-
sourcemaps?: { filesToDeleteAfterUpload?: Promise<unknown> };
34+
sourcemaps?: { deleteSourcemapsAfterUpload?: boolean | (() => boolean | undefined) };
3535
};
3636

3737
let capturedSentryOptions: CapturedSentryOptions | undefined;
38+
let deleteOptionInConfigHook: boolean | undefined | 'not called';
39+
40+
function getDeleteOption(): boolean | undefined {
41+
const value = capturedSentryOptions?.sourcemaps?.deleteSourcemapsAfterUpload;
42+
return typeof value === 'function' ? value() : value;
43+
}
3844

3945
vi.mock('@sentry/bundler-plugins/vite', () => ({
4046
sentryVitePlugin: (options: CapturedSentryOptions) => {
4147
capturedSentryOptions = options;
42-
return [{ name: 'sentry-vite-plugin' }];
48+
return [
49+
{
50+
name: 'sentry-vite-plugin',
51+
config: () => {
52+
deleteOptionInConfigHook = getDeleteOption();
53+
},
54+
},
55+
];
4356
},
4457
}));
4558

46-
const SOURCE_MAP_PLUGINS = [
47-
'sentry-remix-files-to-delete-after-upload',
48-
'sentry-vite-plugin',
49-
'sentry-remix-update-source-map-setting',
50-
];
59+
const SOURCE_MAP_PLUGINS = ['sentry-remix-update-source-map-setting', 'sentry-vite-plugin'];
5160

5261
const NODE_CONFIG = { ssr: { target: 'node' } } as UserConfig;
5362
const WORKER_CONFIG = { ssr: { target: 'webworker' } } as UserConfig;
@@ -73,15 +82,10 @@ describe('sentryRemixVitePlugin', () => {
7382
vi.clearAllMocks();
7483
vi.unstubAllEnvs();
7584
capturedSentryOptions = undefined;
85+
deleteOptionInConfigHook = 'not called';
7686
});
7787

78-
// Vite hands every `config` hook the already-merged config, so the deletion plugin has to read
79-
// `build.sourcemap` before `makeEnableSourceMapsPlugin` sets it. Running the hooks in isolation
80-
// hides that, which is why this drives them in plugin order over one shared config.
81-
it('still deletes the generated source maps once the hooks run in plugin order', async () => {
82-
const plugins = sentryRemixVitePlugin();
83-
const config: UserConfig = {};
84-
88+
function runConfigHooks(plugins: ReturnType<typeof sentryRemixVitePlugin>, config: UserConfig): UserConfig {
8589
for (const plugin of plugins) {
8690
if (!plugin.config) {
8791
continue;
@@ -94,8 +98,22 @@ describe('sentryRemixVitePlugin', () => {
9498
config.build = { ...config.build, sourcemap };
9599
}
96100
}
101+
return config;
102+
}
103+
104+
// The bundler plugin reads the option when its own `config` hook runs, which comes after ours.
105+
it('enables hidden source maps and asks the bundler plugin to delete them', () => {
106+
const config = runConfigHooks(sentryRemixVitePlugin(), {});
107+
108+
expect(config.build?.sourcemap).toBe('hidden');
109+
expect(deleteOptionInConfigHook).toBe(true);
110+
});
111+
112+
it('keeps source maps the user enabled', () => {
113+
const config = runConfigHooks(sentryRemixVitePlugin(), { build: { sourcemap: 'hidden' } });
97114

98-
await expect(capturedSentryOptions?.sourcemaps?.filesToDeleteAfterUpload).resolves.toEqual(['./build/**/*.map']);
115+
expect(config.build?.sourcemap).toBe('hidden');
116+
expect(deleteOptionInConfigHook).toBeUndefined();
99117
});
100118

101119
it('returns the route manifest, orchestrion and source map plugins', () => {
@@ -127,7 +145,6 @@ describe('sentryRemixVitePlugin', () => {
127145
expect(plugins.map(plugin => plugin.name)).toEqual([
128146
'sentry-remix-route-manifest',
129147
'code-transformer',
130-
'sentry-remix-files-to-delete-after-upload',
131148
'sentry-vite-plugin',
132149
]);
133150
});

0 commit comments

Comments
 (0)