Skip to content
Merged
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
6 changes: 3 additions & 3 deletions packages/bundler-plugins/src/core/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -248,9 +248,9 @@ export interface Options {
*
* To keep these file names stable, set this to `'html'`. The plugin then adds the release to the `<head>` of each
* emitted HTML page, in an inline `<script>`, and not to any chunk. The Vite plugin supports this for builds with
* HTML entry points. A Content Security Policy must allow the inline script, for example with Vite's
* `html.cspNonce` or a hash of the script. Where the plugin cannot add the release to HTML, it warns and injects it
* into the startup chunks.
* HTML entry points, and the webpack plugin for builds that generate their HTML with `html-webpack-plugin`. A
* Content Security Policy must allow the inline script, for example with Vite's `html.cspNonce` or a hash of the
* script. Where the plugin cannot add the release to HTML, it warns and injects it into the startup chunks.
*
* You can also set this to `false` and pass `release` to `Sentry.init` at runtime, from a value that is not part of
* your bundled code. A release written into bundled code, for example with `define`, changes the content hashes in
Expand Down
76 changes: 66 additions & 10 deletions packages/bundler-plugins/src/webpack/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,34 @@ type WebpackCompilation = {
};
};

type HtmlTagObject = {
tagName: string;
voidTag: boolean;
attributes: Record<string, string | boolean>;
meta: Record<string, unknown>;
innerHTML?: string;
};

// The part of `html-webpack-plugin`'s API (v4 and later) that the plugin uses. Found among the
// configured plugins instead of imported, because it is an optional dependency of the user.
type HtmlWebpackPluginClass = {
getHooks: (compilation: WebpackCompilation) => {
alterAssetTagGroups: {
tap: (name: string, callback: <T extends { headTags: HtmlTagObject[] }>(data: T) => T) => void;
};
};
};

function findHtmlWebpackPlugin(compiler: WebpackCompiler): HtmlWebpackPluginClass | undefined {
for (const plugin of compiler.options.plugins ?? []) {
const pluginClass = (plugin as { constructor?: { name?: string; getHooks?: unknown } } | undefined)?.constructor;
if (pluginClass?.name === 'HtmlWebpackPlugin' && typeof pluginClass.getHooks === 'function') {
return pluginClass as HtmlWebpackPluginClass;
}
}
return undefined;
}

/**
* Maps webpack's `devtool` onto the plugin's source map kinds. A user who sets `devtool: false`
* and adds a `SourceMapDevToolPlugin` manages source maps themselves.
Expand Down Expand Up @@ -328,12 +356,6 @@ function createSentryWebpackPlugin(userOptions: SentryWebpackPluginInternalOptio
const releaseInjectionCode = new CodeInjection();
const chunkInjectionCode = new CodeInjection();

if (options.release.inject === 'html') {
logger.warn(
"`release.inject: 'html'` is not supported by the webpack plugin. Injecting the release into the startup chunks instead.",
);
}

if (!options.release.inject) {
logger.debug('Release injection disabled via `release.inject` option. Will not inject release.');
} else if (!options.release.name) {
Expand Down Expand Up @@ -378,8 +400,39 @@ function createSentryWebpackPlugin(userOptions: SentryWebpackPluginInternalOptio
return { kind, decision };
}

function addCodeInjection(compiler: WebpackCompiler): void {
if (releaseInjectionCode.isEmpty() && chunkInjectionCode.isEmpty() && !sourcemapsEnabled) {
/**
* Adds the release snippet to the `<head>` of every page that `html-webpack-plugin` generates.
* Returns `false` when the build has no `html-webpack-plugin`.
*/
function addReleaseToHtml(compiler: WebpackCompiler): boolean {
const HtmlWebpackPlugin = findHtmlWebpackPlugin(compiler);
if (!HtmlWebpackPlugin) {
logger.warn(
"`release.inject: 'html'` needs `html-webpack-plugin` to generate the HTML, and this build does not use it. Injecting the release into the startup chunks instead.",
);
return false;
}

const tag: HtmlTagObject = {
tagName: 'script',
voidTag: false,
attributes: {},
meta: { plugin: 'sentry-webpack-plugin' },
innerHTML: releaseInjectionCode.code(),
};

// All instances of the plugin share the hooks of a compilation, so one tap covers every page.
compiler.hooks.thisCompilation.tap('sentry-webpack-plugin', compilation => {
HtmlWebpackPlugin.getHooks(compilation).alterAssetTagGroups.tap('sentry-webpack-plugin', data => {
data.headTags.unshift(tag);
return data;
});
});
return true;
}

function addCodeInjection(compiler: WebpackCompiler, injectRelease: boolean): void {
if ((!injectRelease || releaseInjectionCode.isEmpty()) && chunkInjectionCode.isEmpty() && !sourcemapsEnabled) {
return;
}

Expand Down Expand Up @@ -417,7 +470,7 @@ function createSentryWebpackPlugin(userOptions: SentryWebpackPluginInternalOptio
const sourceContents = source.source();
const code = typeof sourceContents === 'string' ? sourceContents : Buffer.from(sourceContents).toString();
const codeToInject = new CodeInjection();
if (chunk.canBeInitial?.() ?? true) {
if (injectRelease && (chunk.canBeInitial?.() ?? true)) {
codeToInject.append(releaseInjectionCode);
}
codeToInject.append(chunkInjectionCode);
Expand Down Expand Up @@ -497,8 +550,11 @@ function createSentryWebpackPlugin(userOptions: SentryWebpackPluginInternalOptio
compiler.hooks.failed?.tap('sentry-webpack-plugin', settlePendingStagings);
}

const releaseInHtml =
options.release.inject === 'html' && !releaseInjectionCode.isEmpty() && addReleaseToHtml(compiler);

// BannerPlugin prepends executable code before directive prologues.
addCodeInjection(compiler);
addCodeInjection(compiler, !releaseInHtml);

// The upload routine (which stamps debug IDs into temp copies of the artifacts) is skipped
// with `disable-upload`, so the emitted artifacts get stamped in the asset pipeline instead.
Expand Down
147 changes: 144 additions & 3 deletions packages/bundler-plugins/test/webpack/release-injection.test.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,65 @@
import * as fs from 'fs';
import * as os from 'os';
import * as path from 'path';
import { webpack } from 'webpack';
import type { Configuration, Stats } from 'webpack';
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import { runInNewContext } from 'node:vm';
import { Compilation, sources, webpack } from 'webpack';
import type { Compiler, Configuration, Stats } from 'webpack';
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
import { sentryWebpackPlugin } from '../../src/webpack/index';

const RELEASE_SNIPPET = /SENTRY_RELEASE\s*=\s*\{\s*id:\s*"1\.2\.3"\s*\}/;
const DEBUG_ID_MARKER = /sentry-dbid-[0-9a-f-]{36}/;
const INLINE_SCRIPT = /<script>(?<code>[^<]*SENTRY_RELEASE[^<]*)<\/script>/;

type TagObject = { tagName: string; attributes: Record<string, string | boolean>; innerHTML?: string };
type TagGroups = { headTags: TagObject[]; bodyTags: TagObject[] };
type TagGroupsCallback = (data: TagGroups) => TagGroups;

/**
* Stands in for `html-webpack-plugin`, which is not a dependency of this package. Mirrors the
* parts of its API the Sentry plugin uses: the static `getHooks(compilation)` with an
* `alterAssetTagGroups` waterfall hook, called before the page is rendered.
*/
class HtmlWebpackPlugin {
private static readonly _hooks = new WeakMap<Compilation, { alterAssetTagGroups: { taps: TagGroupsCallback[] } }>();

public static getHooks(compilation: Compilation): {
alterAssetTagGroups: { tap: (name: string, cb: TagGroupsCallback) => void };
} {
let hooks = HtmlWebpackPlugin._hooks.get(compilation);
if (!hooks) {
hooks = { alterAssetTagGroups: { taps: [] } };
HtmlWebpackPlugin._hooks.set(compilation, hooks);
}
const { taps } = hooks.alterAssetTagGroups;
return { alterAssetTagGroups: { tap: (_name, cb) => taps.push(cb) } };
}

public apply(compiler: Compiler): void {
compiler.hooks.thisCompilation.tap('HtmlWebpackPlugin', compilation => {
compilation.hooks.processAssets.tap(
{ name: 'HtmlWebpackPlugin', stage: Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE_INLINE },
() => {
const scripts = [...(compilation.entrypoints.get('main')?.getFiles() ?? [])];
let groups: TagGroups = {
headTags: scripts.map(src => ({ tagName: 'script', attributes: { defer: true, src } })),
bodyTags: [],
};
for (const tap of HtmlWebpackPlugin._hooks.get(compilation)?.alterAssetTagGroups.taps ?? []) {
groups = tap(groups);
}
const head = groups.headTags.map(
tag =>
`<${tag.tagName}${Object.entries(tag.attributes)
.map(([name, value]) => (value === true ? ` ${name}` : ` ${name}="${value}"`))
.join('')}>${tag.innerHTML ?? ''}</${tag.tagName}>`,
);
compilation.emitAsset('index.html', new sources.RawSource(`<html><head>${head.join('')}</head></html>`));
},
);
});
}
}

function build(config: Configuration): Promise<Stats> {
return new Promise((resolve, reject) => {
Expand Down Expand Up @@ -40,6 +92,7 @@ describe('release injection', () => {
});

afterEach(() => {
vi.restoreAllMocks();
fs.rmSync(tmpDir, { recursive: true, force: true });
});

Expand All @@ -63,4 +116,92 @@ describe('release injection', () => {
expect(mainChunk).toMatch(DEBUG_ID_MARKER);
expect(routeChunk).toMatch(DEBUG_ID_MARKER);
});

describe("with `inject: 'html'`", () => {
function buildApp(release: string, options: { html?: boolean; inject?: 'html' } = {}): Promise<Stats> {
return build({
mode: 'production',
context: tmpDir,
entry: './entry.js',
output: {
path: path.join(tmpDir, 'dist'),
filename: '[name].[contenthash].js',
chunkFilename: '[name].[contenthash].js',
clean: true,
},
plugins: [
...(options.html === false ? [] : [new HtmlWebpackPlugin()]),
sentryWebpackPlugin({ telemetry: false, release: { name: release, create: false, inject: options.inject } }),
],
});
}

function readOutput(): { html: string; chunks: Record<string, string> } {
const outDir = path.join(tmpDir, 'dist');
const chunks: Record<string, string> = {};
for (const file of fs.readdirSync(outDir).filter(file => file.endsWith('.js'))) {
chunks[file] = fs.readFileSync(path.join(outDir, file), 'utf8');
}
const htmlPath = path.join(outDir, 'index.html');
return { html: fs.existsSync(htmlPath) ? fs.readFileSync(htmlPath, 'utf8') : '', chunks };
}

it(
'injects the release into the HTML head before the app scripts, and not into any chunk',
{ timeout: 15_000 },
async () => {
await buildApp('1.2.3', { inject: 'html' });

const { html, chunks } = readOutput();
const script = html.match(INLINE_SCRIPT);
expect(script).not.toBeNull();
expect(script?.index).toBeLessThan(html.indexOf('<script defer'));
const context: { SENTRY_RELEASE?: unknown } = {};
runInNewContext(script?.groups?.code ?? '', context);
expect(context.SENTRY_RELEASE).toEqual({ id: '1.2.3' });

expect(Object.keys(chunks)).toHaveLength(2);
for (const chunk of Object.values(chunks)) {
expect(chunk).not.toContain('SENTRY_RELEASE');
expect(chunk).toMatch(DEBUG_ID_MARKER);
}
},
);

it('keeps JS file names the same when only the release changes', { timeout: 15_000 }, async () => {
await buildApp('release-a', { inject: 'html' });
const firstNames = Object.keys(readOutput().chunks).sort();
await buildApp('release-b', { inject: 'html' });

expect(Object.keys(readOutput().chunks).sort()).toEqual(firstNames);
});

it('changes JS file names with the release when injecting into chunks', { timeout: 15_000 }, async () => {
await buildApp('release-a');
const firstNames = Object.keys(readOutput().chunks).sort();
await buildApp('release-b');

expect(Object.keys(readOutput().chunks).sort()).not.toEqual(firstNames);
expect(readOutput().html).not.toContain('SENTRY_RELEASE');
});

it(
'warns and injects the release into the startup chunk without html-webpack-plugin',
{ timeout: 15_000 },
async () => {
const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined);

await buildApp('1.2.3', { inject: 'html', html: false });

expect(warn).toHaveBeenCalledWith(
expect.stringContaining("`release.inject: 'html'` needs `html-webpack-plugin`"),
);
const { chunks } = readOutput();
const mainChunk = Object.entries(chunks).find(([file]) => file.startsWith('main.'))?.[1];
const routeChunk = Object.entries(chunks).find(([file]) => file.startsWith('route.'))?.[1];
expect(mainChunk).toMatch(RELEASE_SNIPPET);
expect(routeChunk).not.toMatch(RELEASE_SNIPPET);
},
);
});
});
Loading