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
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import * as assert from 'assert/strict';
import * as fs from 'fs';
import * as path from 'path';
import { chromium } from '@playwright/test';
import {
assertSourceMapUpload,
findDebugIdsWithConflictingSourcemaps,
Expand Down Expand Up @@ -41,6 +42,9 @@ const SERVER_OUTPUT = outputDirs.server;
const CLIENT_MARKER = 'SOURCEMAP_MARKER_CLIENT';
const SERVER_MARKER = 'SOURCEMAP_MARKER_SERVER';

/** Set as `release.name` in `nuxt.config.ts`. */
const RELEASE = 'test-release';

const UUID_REGEX = /^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/i;

/** Some presets write the server into the client output, e.g. Cloudflare Pages. */
Expand Down Expand Up @@ -77,6 +81,36 @@ function debugIdsOfChunksWithoutSourceMap(dir: string): Set<string> {
return debugIds;
}

type NuxtRootContainer = HTMLElement & { __vue_app__?: { $nuxt?: { isHydrating?: boolean } } };

const ENVELOPE_URL = /\/api\/1337\/envelope\//;
const EVENT_ITEM_HEADER = '"type":"event"';

/** Opens the page, throws the client error, and resolves with the error event the browser SDK sends. */
async function captureClientErrorEvent(url: string): Promise<{ release?: string }> {
const browser = await chromium.launch();

try {
const page = await browser.newPage();
await page.route(ENVELOPE_URL, route => route.fulfill({ status: 200, body: '{}' }));
const eventRequest = page.waitForRequest(
request => ENVELOPE_URL.test(request.url()) && (request.postData() ?? '').includes(EVENT_ITEM_HEADER),
);

await page.goto(url);
// Server-rendered elements are clickable before Vue hydration attaches their event handlers.
await page.waitForFunction(
() => (document.getElementById('__nuxt') as NuxtRootContainer | null)?.__vue_app__?.$nuxt?.isHydrating === false,
);
await page.locator('#throw-error').click();

const lines = ((await eventRequest).postData() ?? '').split('\n');
return JSON.parse(lines[lines.findIndex(line => line.includes(EVENT_ITEM_HEADER)) + 1] as string);
} finally {
await browser.close();
}
}

console.log(
`Variant: ${isStaticBuild ? 'nuxt generate' : 'nuxt build'}, Nitro preset ${nitroPreset}, ` +
`client source maps ${keepClientSourceMaps ? 'kept' : 'deleted'}\n`,
Expand Down Expand Up @@ -107,7 +141,7 @@ for (const request of releaseCreates) {
const body = request.jsonBody as { version?: string; projects?: string[] } | undefined;
assert.equal(
body?.version,
'test-release',
RELEASE,
`Expected the release create body to carry the version, got ${JSON.stringify(body)}`,
);
assert.deepEqual(
Expand Down Expand Up @@ -198,6 +232,13 @@ if (keepClientSourceMaps) {
console.log(` ${CLIENT_OUTPUT} is free of source maps, sourceMappingURL comments and original source\n`);
}

// The release changes on every commit, so a client chunk that contains it gets a new file name on every release.
const clientChunksWithRelease = filesContaining(CLIENT_OUTPUT, RELEASE).filter(
file => isClientFile(file) && file.endsWith('.js'),
);
assert.deepEqual(clientChunksWithRelease, [], `Expected no client chunk in ${CLIENT_OUTPUT} to contain the release`);
console.log(` No client chunk in ${CLIENT_OUTPUT} contains the release\n`);

// --- What the build leaves behind in the server output ---

// Nuxt enables the server maps by default, so they are the user's and Sentry must keep them.
Expand Down Expand Up @@ -247,6 +288,10 @@ if (!isStaticBuild && nitroPreset === 'node-server') {
);

console.log(` The server answers all ${clientChunkUrls.length} client source map URL(s) as expected\n`);

const clientErrorEvent = await captureClientErrorEvent(server.baseUrl);
assert.equal(clientErrorEvent.release, RELEASE, 'Expected the client error event to carry the release');
console.log(` The client error event carries the release ${RELEASE}\n`);
} finally {
await server.close();
}
Expand Down
11 changes: 8 additions & 3 deletions packages/nuxt/src/module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { NUXT_TUNNEL_BASE_PATH_GLOBAL } from './common/tunnel';
import type { SentryNuxtModuleOptions } from './common/types';
import { addTunnelPlugin, setupNitroServer } from './vite/nitroServer';
import { setupOrchestrion } from './vite/orchestrion';
import { setupSourceMaps } from './vite/sourceMaps';
import { NUXT_RELEASE_RUNTIME_CONFIG_KEY, setupSourceMaps } from './vite/sourceMaps';
import { findDefaultSdkInitFile, resolveServerApi } from './vite/utils';
import { setupViteServer } from './vite/viteServer';
import { stringifyForCodeInjection } from '@sentry/core';
Expand Down Expand Up @@ -63,7 +63,12 @@ export default defineNuxtModule<ModuleOptions>({
export default defineNuxtPlugin({
name: 'sentry-client-config',
async setup() {
globalThis.${NUXT_TUNNEL_BASE_PATH_GLOBAL} = useRuntimeConfig().app.baseURL;
const runtimeConfig = useRuntimeConfig();
globalThis.${NUXT_TUNNEL_BASE_PATH_GLOBAL} = runtimeConfig.app.baseURL;
const sentryRelease = runtimeConfig.public.${NUXT_RELEASE_RUNTIME_CONFIG_KEY};
if (sentryRelease) {
globalThis.SENTRY_RELEASE = { id: sentryRelease };
}
await import("${buildDirResolver.resolve(`/${clientConfigFile}`)}")
}
});`,
Expand Down Expand Up @@ -107,7 +112,7 @@ export default defineNuxtModule<ModuleOptions>({
}

if (clientConfigFile || serverConfigFile) {
setupSourceMaps(moduleOptions, nuxt, addVitePlugin);
setupSourceMaps(moduleOptions, nuxt, addVitePlugin, !!clientConfigFile);
}

let pagesData: NuxtPageSubset[] = [];
Expand Down
38 changes: 37 additions & 1 deletion packages/nuxt/src/vite/sourceMaps.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import type { Nuxt } from '@nuxt/schema';
import { resolveReleaseName } from '@sentry/bundler-plugins/core';
import { sentryRollupPlugin, type SentryRollupPluginOptions } from '@sentry/bundler-plugins/rollup';
import { sentryVitePlugin, type SentryVitePluginOptions } from '@sentry/bundler-plugins/vite';
import { warnOnRemovedBuildOptions } from '@sentry/core';
Expand All @@ -24,13 +25,17 @@ import {
*/
export type UserSourceMapSetting = 'enabled' | 'disabled' | 'unset' | undefined;

/** The public runtime config key that gives the release to the client SDK. */
export const NUXT_RELEASE_RUNTIME_CONFIG_KEY = '_sentryRelease';

/**
* Setup source maps for Sentry inside the Nuxt module during build time (in Vite for Nuxt and Rollup for Nitro).
*/
export function setupSourceMaps(
moduleOptions: SentryNuxtModuleOptions,
nuxt: Nuxt,
addVitePlugin: (plugin: Plugin[], options?: { dev?: boolean; build?: boolean; server?: boolean }) => void,
hasClientConfigFile = false,
): void {
// Warn here rather than in `getPluginOptions`, which runs once per bundler (Vite and Nitro's
// Rollup) and would emit the same warning twice.
Expand Down Expand Up @@ -87,8 +92,16 @@ export function setupSourceMaps(
build: true,
});

const clientPluginOptions = getPluginOptions(moduleOptions, shouldDeleteFilesFallback);
addVitePlugin(
sentryVitePlugin(withoutSourceMapDeletion(getPluginOptions(moduleOptions, shouldDeleteFilesFallback))),
sentryVitePlugin(
withoutSourceMapDeletion(
// Only the generated client config plugin reads the release from the runtime config.
hasClientConfigFile
? moveClientReleaseToRuntimeConfig(nuxt, moduleOptions, clientPluginOptions)
: clientPluginOptions,
),
),
// Nitro bundles the SSR output again, so debug IDs from the SSR build would point to the wrong maps.
{ dev: false, build: true, server: false },
);
Expand Down Expand Up @@ -149,6 +162,29 @@ export function setupSourceMaps(
});
}

/**
* The release usually changes on every commit. Injected into the client's startup chunks, it gives them, and every
* chunk that imports them, new content hashes on every release. Nuxt serializes the public runtime config into the
* page instead, from where the client config plugin hands it to the SDK.
*/
function moveClientReleaseToRuntimeConfig(
nuxt: Nuxt,
moduleOptions: SentryNuxtModuleOptions,
pluginOptions: SentryVitePluginOptions,
): SentryVitePluginOptions {
if (moduleOptions.release?.inject === false) {
return pluginOptions;
}

const release = resolveReleaseName(moduleOptions.release?.name);
if (release) {
nuxt.options.runtimeConfig.public[NUXT_RELEASE_RUNTIME_CONFIG_KEY] = release;
}

// Pass the resolved name on so the plugin uploads under the same release the client reports.
return { ...pluginOptions, release: { ...pluginOptions.release, ...(release && { name: release }), inject: false } };
}

/**
* Normalizes the beginning of a path from e.g. ../../../ to ./
*/
Expand Down
80 changes: 79 additions & 1 deletion packages/nuxt/test/vite/sourceMaps-nuxtHooks.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import * as os from 'os';
import * as path from 'path';
import type { ConfigEnv, Plugin, UserConfig } from 'vite';
import { afterAll, afterEach, beforeEach, describe, expect, it, type MockInstance, vi } from 'vitest';
import { setupSourceMaps } from '../../src/vite/sourceMaps';
import { NUXT_RELEASE_RUNTIME_CONFIG_KEY, setupSourceMaps } from '../../src/vite/sourceMaps';
import type { SourceMapSetting } from '../../src/vite/sourceMapSettings';

const { mockSentryVitePlugin, mockSentryRollupPlugin, mockDeleteArtifacts, mockCreateSentryBuildPluginManager } =
Expand Down Expand Up @@ -72,6 +72,7 @@ function createMockNuxt(options: {
_prepare: options._prepare ?? false,
dev: options.dev ?? false,
sourcemap: options.sourcemap ?? { server: undefined, client: undefined },
runtimeConfig: { public: {} as Record<string, unknown> },
},
hook: (name: string, callback: HookCallback) => {
hooks[name] = hooks[name] || [];
Expand Down Expand Up @@ -218,6 +219,83 @@ describe('setupSourceMaps hooks', () => {
});
});

describe('client release', () => {
afterEach(() => {
vi.unstubAllEnvs();
});

it('passes the configured release to the client through the public runtime config', () => {
const mockNuxt = createMockNuxt({});

setupSourceMaps({ release: { name: '1.2.3' } }, mockNuxt as unknown as Nuxt, vi.fn(), true);

expect(mockNuxt.options.runtimeConfig.public).toEqual({ [NUXT_RELEASE_RUNTIME_CONFIG_KEY]: '1.2.3' });
});

it('falls back to the `SENTRY_RELEASE` environment variable, like the bundler plugin', () => {
vi.stubEnv('SENTRY_RELEASE', 'env-release');
const mockNuxt = createMockNuxt({});

setupSourceMaps({}, mockNuxt as unknown as Nuxt, vi.fn(), true);

expect(mockNuxt.options.runtimeConfig.public).toEqual({ [NUXT_RELEASE_RUNTIME_CONFIG_KEY]: 'env-release' });
});

it('passes the resolved release name to the client plugin so the upload matches the runtime config', () => {
vi.stubEnv('SENTRY_RELEASE', 'env-release');
const mockNuxt = createMockNuxt({});

setupSourceMaps({}, mockNuxt as unknown as Nuxt, vi.fn(), true);

expect(mockSentryVitePlugin).toHaveBeenCalledWith(
expect.objectContaining({ release: { name: 'env-release', inject: false } }),
);
});

it('turns off release injection in the client build only', async () => {
const mockNuxt = createMockNuxt({});

setupSourceMaps({ release: { name: '1.2.3' } }, mockNuxt as unknown as Nuxt, vi.fn(), true);
await mockNuxt.triggerHook('nitro:config', { rollupConfig: {} });

expect(mockSentryVitePlugin).toHaveBeenCalledWith(
expect.objectContaining({ release: { name: '1.2.3', inject: false } }),
);
expect(mockSentryRollupPlugin).toHaveBeenCalledWith(expect.objectContaining({ release: { name: '1.2.3' } }));
});

it('gives the client no release when the user turned off `release.inject`', () => {
const mockNuxt = createMockNuxt({});

setupSourceMaps({ release: { name: '1.2.3', inject: false } }, mockNuxt as unknown as Nuxt, vi.fn(), true);

expect(mockNuxt.options.runtimeConfig.public).toEqual({});
expect(mockSentryVitePlugin).toHaveBeenCalledWith(
expect.objectContaining({ release: { name: '1.2.3', inject: false } }),
);
});

it('keeps release injection in the client build without a client config file', () => {
const mockNuxt = createMockNuxt({});

setupSourceMaps({ release: { name: '1.2.3' } }, mockNuxt as unknown as Nuxt, vi.fn(), false);

expect(mockNuxt.options.runtimeConfig.public).toEqual({});
expect(mockSentryVitePlugin).toHaveBeenCalledWith(expect.objectContaining({ release: { name: '1.2.3' } }));
});

it.each([
{ label: 'dev mode', nuxtOptions: { dev: true } },
{ label: 'prepare mode', nuxtOptions: { _prepare: true } },
])('gives the client no release in $label', ({ nuxtOptions }) => {
const mockNuxt = createMockNuxt(nuxtOptions);

setupSourceMaps({ release: { name: '1.2.3' } }, mockNuxt as unknown as Nuxt, vi.fn(), true);

expect(mockNuxt.options.runtimeConfig.public).toEqual({});
});
});

describe('shouldDeleteFilesFallback passed to getPluginOptions in Vite plugin', () => {
it('does not pass fallback deletion patterns to the Vite plugin', async () => {
const mockNuxt = createMockNuxt({
Expand Down
Loading