Skip to content
Draft
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
Expand Up @@ -4,4 +4,5 @@ minimumReleaseAge: 0
overrides:
'@sentry/bundler-plugins': 'file:../../../../packages/bundler-plugins/sentry-bundler-plugins-11.16.0.tgz'
'@sentry/core': 'file:../../../../packages/core/sentry-core-11.16.0.tgz'
'@sentry/server-utils': 'file:../../../../packages/server-utils/sentry-server-utils-11.16.0.tgz'
'sentry': 'file:../sentry-stub'
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,5 @@ minimumReleaseAge: 0
overrides:
'@sentry/bundler-plugins': 'file:../../../../packages/bundler-plugins/sentry-bundler-plugins-11.16.0.tgz'
'@sentry/core': 'file:../../../../packages/core/sentry-core-11.16.0.tgz'
'@sentry/server-utils': 'file:../../../../packages/server-utils/sentry-server-utils-11.16.0.tgz'
'sentry': 'file:../sentry-stub'
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,5 @@ minimumReleaseAge: 0
overrides:
'@sentry/bundler-plugins': 'file:../../../../packages/bundler-plugins/sentry-bundler-plugins-11.16.0.tgz'
'@sentry/core': 'file:../../../../packages/core/sentry-core-11.16.0.tgz'
'@sentry/server-utils': 'file:../../../../packages/server-utils/sentry-server-utils-11.16.0.tgz'
'sentry': 'file:../sentry-stub'
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,5 @@ minimumReleaseAge: 0
overrides:
'@sentry/bundler-plugins': 'file:../../../../packages/bundler-plugins/sentry-bundler-plugins-11.16.0.tgz'
'@sentry/core': 'file:../../../../packages/core/sentry-core-11.16.0.tgz'
'@sentry/server-utils': 'file:../../../../packages/server-utils/sentry-server-utils-11.16.0.tgz'
'sentry': 'file:../sentry-stub'
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,5 @@ minimumReleaseAge: 0
overrides:
'@sentry/bundler-plugins': 'file:../../../../packages/bundler-plugins/sentry-bundler-plugins-11.16.0.tgz'
'@sentry/core': 'file:../../../../packages/core/sentry-core-11.16.0.tgz'
'@sentry/server-utils': 'file:../../../../packages/server-utils/sentry-server-utils-11.16.0.tgz'
'sentry': 'file:../sentry-stub'
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,5 @@ minimumReleaseAge: 0
overrides:
'@sentry/bundler-plugins': 'file:../../../../packages/bundler-plugins/sentry-bundler-plugins-11.16.0.tgz'
'@sentry/core': 'file:../../../../packages/core/sentry-core-11.16.0.tgz'
'@sentry/server-utils': 'file:../../../../packages/server-utils/sentry-server-utils-11.16.0.tgz'
'sentry': 'file:../sentry-stub'
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,5 @@ minimumReleaseAge: 0
overrides:
'@sentry/bundler-plugins': 'file:../../../../packages/bundler-plugins/sentry-bundler-plugins-11.16.0.tgz'
'@sentry/core': 'file:../../../../packages/core/sentry-core-11.16.0.tgz'
'@sentry/server-utils': 'file:../../../../packages/server-utils/sentry-server-utils-11.16.0.tgz'
'sentry': 'file:../sentry-stub'
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,5 @@ minimumReleaseAge: 0
overrides:
'@sentry/bundler-plugins': 'file:../../../../packages/bundler-plugins/sentry-bundler-plugins-11.16.0.tgz'
'@sentry/core': 'file:../../../../packages/core/sentry-core-11.16.0.tgz'
'@sentry/server-utils': 'file:../../../../packages/server-utils/sentry-server-utils-11.16.0.tgz'
'sentry': 'file:../sentry-stub'
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,5 @@ minimumReleaseAge: 0
overrides:
'@sentry/bundler-plugins': 'file:../../../../packages/bundler-plugins/sentry-bundler-plugins-11.16.0.tgz'
'@sentry/core': 'file:../../../../packages/core/sentry-core-11.16.0.tgz'
'@sentry/server-utils': 'file:../../../../packages/server-utils/sentry-server-utils-11.16.0.tgz'
'sentry': 'file:../sentry-stub'
6 changes: 6 additions & 0 deletions dev-packages/bundler-plugin-integration-tests/setup.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,12 @@ execSync('pnpm run build:dev:filter @sentry/core', { cwd: repoRoot, stdio: 'inhe
console.log('Packing @sentry/core...');
execSync('pnpm run build:tarball', { cwd: coreDir, stdio: 'inherit' });

const serverUtilsDir = join(repoRoot, 'packages', 'server-utils');
console.log('Building @sentry/server-utils and its workspace dependencies...');
execSync('pnpm run build:dev:filter @sentry/server-utils', { cwd: repoRoot, stdio: 'inherit' });
console.log('Packing @sentry/server-utils...');
execSync('pnpm run build:tarball', { cwd: serverUtilsDir, stdio: 'inherit' });

console.log('Building @sentry/bundler-plugins and its workspace dependencies...');
execSync('pnpm run build:dev:filter @sentry/bundler-plugins', { cwd: repoRoot, stdio: 'inherit' });
console.log('Packing @sentry/bundler-plugins...');
Expand Down
6 changes: 6 additions & 0 deletions packages/astro/src/integration/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
/* oxlint-disable max-lines */
import { getDisabledSourcemapsOptions } from '@sentry/bundler-plugins/core';
import { sentryVitePlugin } from '@sentry/bundler-plugins/vite';
import { warnOnRemovedBuildOptions } from '@sentry/core';
import { sentryOrchestrionPlugin } from '@sentry/server-utils/orchestrion/vite';
Expand Down Expand Up @@ -134,6 +136,10 @@ export const sentryAstro = (options: SentryOptions = {}): AstroIntegration => {
],
},
});
} else if (sdkEnabled.server && command !== 'dev') {
// TODO: Revisit which features the plugin should run when source maps are off. For now it only injects
// module versions, so `modulesIntegration` reports them when `node_modules` is missing at runtime.
updateConfig({ vite: { plugins: [sentryVitePlugin(getDisabledSourcemapsOptions({ debug }))] } });
}

runtimeRelease && injectScript('head-inline', buildReleaseSnippet(runtimeRelease));
Expand Down
4 changes: 3 additions & 1 deletion packages/astro/test/integration/index.files.test.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import type * as BundlerPluginsCore from '@sentry/bundler-plugins/core';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { sentryAstro } from '../../src/integration';

Expand All @@ -9,7 +10,8 @@ vi.mock('fs', async requireActual => {
});

// Without a configured name, the real resolver falls back to the git revision of this checkout.
vi.mock('@sentry/bundler-plugins/core', () => ({
vi.mock('@sentry/bundler-plugins/core', async importOriginal => ({
...(await importOriginal<typeof BundlerPluginsCore>()),
resolveReleaseName: (name?: string) => name,
}));

Expand Down
44 changes: 41 additions & 3 deletions packages/astro/test/integration/index.test.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import type * as BundlerPluginsCore from '@sentry/bundler-plugins/core';
import type * as FsModule from 'fs';
import type { AstroConfig, AstroIntegrationLogger } from 'astro';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
Expand All @@ -13,7 +14,8 @@ vi.mock('@sentry/bundler-plugins/vite', () => ({

// Without a configured name, the real resolver falls back to the git revision of this checkout.
const resolveReleaseName = vi.fn((name?: string) => name);
vi.mock('@sentry/bundler-plugins/core', () => ({
vi.mock('@sentry/bundler-plugins/core', async importOriginal => ({
...(await importOriginal<typeof BundlerPluginsCore>()),
resolveReleaseName: (name?: string) => resolveReleaseName(name),
}));

Expand Down Expand Up @@ -347,19 +349,55 @@ describe('sentryAstro integration', () => {
it("doesn't enable source maps if `sourcemaps.disable` is `true`", async () => {
const integration = sentryAstro({
sourcemaps: { disable: true },
debug: true,
});

expect(integration.hooks['astro:config:setup']).toBeDefined();
// @ts-expect-error - the hook exists and we only need to pass what we actually use
await integration.hooks['astro:config:setup']({ ...baseConfigHookObject, updateConfig, injectScript, config });

// only the orchestrion plugin and the server init are wired, no sourcemaps plugin
expect(updateConfig).toHaveBeenCalledTimes(2);
// one call each for the module versions plugin, the orchestrion plugin and the server init
expect(updateConfig).toHaveBeenCalledTimes(3);
expect(updateConfig).toHaveBeenCalledWith({
vite: {
plugins: [{ name: 'sentry-orchestrion-vite' }],
},
});
expect(updateConfig).not.toHaveBeenCalledWith({ vite: expect.objectContaining({ build: expect.anything() }) });
// the bundler plugin only injects module versions
expect(sentryVitePluginSpy).toHaveBeenCalledTimes(1);
expect(sentryVitePluginSpy).toHaveBeenCalledWith({
debug: true,
telemetry: false,
sourcemaps: { upload: false, injectDebugIds: false },
release: { inject: false, create: false, finalize: false, setCommits: false, deploy: false },
});
});

it("doesn't add the module versions plugin if `sourcemaps.disable` is `true` and the server SDK is disabled", async () => {
const integration = sentryAstro({
sourcemaps: { disable: true },
enabled: { client: true, server: false },
});

// @ts-expect-error - the hook exists and we only need to pass what we actually use
await integration.hooks['astro:config:setup']({ ...baseConfigHookObject, updateConfig, injectScript, config });

expect(sentryVitePluginSpy).toHaveBeenCalledTimes(0);
});

it("doesn't add the module versions plugin in dev mode", async () => {
const integration = sentryAstro({ sourcemaps: { disable: true } });

// @ts-expect-error - the hook exists and we only need to pass what we actually use
await integration.hooks['astro:config:setup']({
...baseConfigHookObject,
updateConfig,
injectScript,
config,
command: 'dev',
});

expect(sentryVitePluginSpy).toHaveBeenCalledTimes(0);
});

Expand Down
1 change: 1 addition & 0 deletions packages/bundler-plugins/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,7 @@
},
"dependencies": {
"@sentry/core": "11.16.0",
"@sentry/server-utils": "11.16.0",
"dotenv": "^17.4.2",
"glob": "^14.0.3",
"magic-string": "~0.30.8 || ^1.0.0",
Expand Down
9 changes: 9 additions & 0 deletions packages/bundler-plugins/src/bun/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {
createDebugIdUploadFunction,
CodeInjection,
getSourceMapFeatures,
getServerModulesDefinition,
} from '../core';
import * as fs from 'node:fs';

Expand All @@ -20,6 +21,7 @@ interface BunBuildConfig {
sourcemap?: 'none' | 'linked' | 'inline' | 'external' | boolean;
outdir?: string;
define?: Record<string, string>;
target?: 'browser' | 'bun' | 'node';
}

interface BunPluginBuilder {
Expand Down Expand Up @@ -150,6 +152,13 @@ export function sentryBunPlugin(userOptions: Options = {}): BunPlugin {
config.define = { ...config.define, ...replacementStringValues };
}

const serverModules = sentryBuildPluginManager.getModuleVersions({
isServerBuild: config.target === 'bun' || config.target === 'node',
});
if (serverModules) {
config.define = { ...config.define, ...getServerModulesDefinition(serverModules) };
}

const freeGlobalDependencyOnBuildArtifacts = createDependencyOnBuildArtifacts();
const upload = createDebugIdUploadFunction({ sentryBuildPluginManager });

Expand Down
34 changes: 34 additions & 0 deletions packages/bundler-plugins/src/core/build-plugin-manager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import { createLogger } from './logger';
import { allowedToSendTelemetry, createSentryInstance, safeFlushTelemetry } from './sentry/telemetry';
import type { InternalOptions, SentrySDKBuildFlags } from './types';
import { arrayify, getProjects, getTurborepoEnvPassthroughWarning, stripQueryAndHashFromPath } from './utils';
import { getInstalledModules } from './installed-modules';
import {
defaultRewriteSourcesHook,
prepareArtifactForUpload,
Expand Down Expand Up @@ -97,6 +98,12 @@ export type SentryBuildPluginManager = {
// See `generateModuleMetadataInjectorCode` for how this should be used exactly
bundleMetadata: Record<string, unknown>;

/**
* Returns the app's module versions to replace `__SENTRY_SERVER_MODULES__` with in a build, or `undefined` when the
* build gets none (see the `injectModuleVersions` option). The versions are read once per root.
*/
getModuleVersions(build: { root?: string; isServerBuild: boolean }): Record<string, string> | undefined;

/**
* Contains utility functions for emitting telemetry via the build plugin manager.
*/
Expand Down Expand Up @@ -239,6 +246,7 @@ export function createSentryBuildPluginManager(
},
},
bundleMetadata: {},
getModuleVersions: () => undefined,
createRelease: async () => {
/* noop */
},
Expand Down Expand Up @@ -474,6 +482,25 @@ export function createSentryBuildPluginManager(
}
}

const moduleVersionsByRoot = new Map<string, Record<string, string> | undefined>();
function getModuleVersions({
root = process.cwd(),
isServerBuild,
}: {
root?: string;
isServerBuild: boolean;
}): Record<string, string> | undefined {
if (!(options.injectModuleVersions ?? isServerBuild)) {
return undefined;
}

if (!moduleVersionsByRoot.has(root)) {
const modules = getInstalledModules(root);
moduleVersionsByRoot.set(root, Object.keys(modules).length > 0 ? modules : undefined);
}
return moduleVersionsByRoot.get(root);
}

return {
/**
* A logger instance that takes the options passed to the build plugin manager into account. (for silencing and log level etc.)
Expand All @@ -497,6 +524,8 @@ export function createSentryBuildPluginManager(
// See `generateModuleMetadataInjectorCode` for how this should be used exactly
bundleMetadata,

getModuleVersions,

/**
* Contains utility functions for emitting telemetry via the build plugin manager.
*/
Expand Down Expand Up @@ -527,6 +556,11 @@ export function createSentryBuildPluginManager(
* - adds deploy information
*/
async createRelease() {
const { create, finalize, setCommits, deploy, uploadLegacySourcemaps } = options.release;
if (!create && !finalize && setCommits === false && !deploy && !uploadLegacySourcemaps) {
return;
}

if (!options.release.name) {
logger.debug(
'No release name provided. Will not create release. Please set the `release.name` option to identify your release.',
Expand Down
3 changes: 3 additions & 0 deletions packages/bundler-plugins/src/core/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -109,8 +109,11 @@ export {
generateReleaseInjectorCode,
generateModuleMetadataInjectorCode,
resolveReleaseName,
getServerModulesDefinition,
SERVER_MODULES_PLACEHOLDER,
} from './utils';
export { createSentryBuildPluginManager } from './build-plugin-manager';
export { getDisabledSourcemapsOptions } from './installed-modules';
export type { SentryBuildPluginManager, UploadResult, UploadStaging } from './build-plugin-manager';
export { createDebugIdUploadFunction, addDebugIdToEmittedArtifacts, stampDebugId } from './debug-id-upload';
export {
Expand Down
28 changes: 28 additions & 0 deletions packages/bundler-plugins/src/core/installed-modules.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import * as fs from 'fs';
import { collectInstalledModules } from '@sentry/server-utils/no-diagnostic-channels';
import type { Options } from './types';

/**
* The dependencies of the app at `root`, with the exact version installed in `node_modules` where it resolves and
* the declared range otherwise.
*/
export function getInstalledModules(root: string): Record<string, string> {
return collectInstalledModules({
readFile: filePath => (fs.existsSync(filePath) ? fs.readFileSync(filePath, 'utf8') : undefined),
cwd: root,
});
}

/**
* Plugin options for frameworks that add the plugin although the user turned source maps off. For now they turn off
* everything except injecting module versions: no source map upload, deletion or debug IDs, no release creation or
* injection, and no telemetry.
*/
export function getDisabledSourcemapsOptions(options: Pick<Options, 'debug' | 'injectModuleVersions'> = {}): Options {
return {
...options,
telemetry: false,
sourcemaps: { upload: false, injectDebugIds: false },
release: { inject: false, create: false, finalize: false, setCommits: false, deploy: false },
};
}
2 changes: 2 additions & 0 deletions packages/bundler-plugins/src/core/options-mapping.ts
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,7 @@ export type NormalizedOptions = {
};
applicationKey: string | undefined;
moduleMetadata: ModuleMetadata | ModuleMetadataCallback | undefined;
injectModuleVersions: boolean | undefined;
_experiments: {
injectBuildInformation?: boolean;
} & Record<string, unknown>;
Expand Down Expand Up @@ -138,6 +139,7 @@ export function normalizeUserOptions(userOptions: UserOptions): NormalizedOption
},
applicationKey: userOptions.applicationKey,
moduleMetadata: userOptions.moduleMetadata,
injectModuleVersions: userOptions.injectModuleVersions,
_experiments: userOptions._experiments ?? {},
};

Expand Down
9 changes: 9 additions & 0 deletions packages/bundler-plugins/src/core/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -495,6 +495,15 @@ export interface Options {
*/
applicationKey?: string;

/**
Comment thread
sentry-junior[bot] marked this conversation as resolved.
Resolved
* Injects the installed versions of the app's dependencies for the Node SDK's `modulesIntegration`, which
* otherwise reads them from `node_modules` at runtime. Only takes effect when the SDK is bundled.
*
* Defaults to server builds only (Vite SSR, webpack `node` targets, esbuild `platform: 'node'`, Bun); plain Rollup
* needs `true`, and `false` disables it. Avoid `true` for browser builds, as it ships the list to users.
*/
injectModuleVersions?: boolean;

/**
* Options that are considered experimental and subject to change.
*
Expand Down
17 changes: 17 additions & 0 deletions packages/bundler-plugins/src/core/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -343,9 +343,22 @@ export function stripQueryAndHashFromPath(path: string): string {
return path.split('?')[0]!.split('#')[0]!;
}

/** The placeholder that the Node SDK's `modulesIntegration` reads the module versions from. */
export const SERVER_MODULES_PLACEHOLDER = '__SENTRY_SERVER_MODULES__';

/** The `define` entry that replaces the module versions placeholder, for bundlers with `define` support. */
export function getServerModulesDefinition(serverModules: Record<string, string>): Record<string, string> {
return { [SERVER_MODULES_PLACEHOLDER]: stringifyForCodeInjection(serverModules) };
}

/**
* Replaces the boolean flags, and the `__SENTRY_SERVER_MODULES__` placeholder that the Node SDK's `modulesIntegration`
* reads when `serverModules` is set.
*/
export function replaceBooleanFlagsInCode(
code: string,
replacementValues: Record<string, boolean | undefined>,
serverModules?: Record<string, string>,
): { code: string; map: SourceMap } | null {
const ms = new MagicString(code);

Expand All @@ -357,6 +370,10 @@ export function replaceBooleanFlagsInCode(
}
});

if (serverModules) {
ms.replaceAll(SERVER_MODULES_PLACEHOLDER, `(${stringifyForCodeInjection(serverModules)})`);
}

if (ms.hasChanged()) {
return {
code: ms.toString(),
Expand Down
Loading
Loading