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
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ test.describe('server-side errors', () => {

expect(errorEventFrames?.[errorEventFrames?.length - 1]).toEqual(
expect.objectContaining({
function: 'load$1',
function: 'load',
in_app: true,
}),
);
Expand Down Expand Up @@ -42,7 +42,7 @@ test.describe('server-side errors', () => {

expect(errorEventFrames?.[errorEventFrames?.length - 1]).toEqual(
expect.objectContaining({
function: 'load$1',
function: 'load',
in_app: true,
}),
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ if (process.env.E2E_VARIANT === 'manual-upload') {
}
} else {
// Also covers the `delete-all` variant: the maps the app turned on are uploaded and removed.
const { requests, sourcemaps } = assertSourceMapUpload({
const { requests } = assertSourceMapUpload({
outputDirs: [CLIENT_OUTPUT, SERVER_OUTPUT],
// The server output keeps `sourceMappingURL` comments that point at the deleted maps. Nothing serves
// it, so only the client output must be free of them.
Expand All @@ -72,13 +72,6 @@ if (process.env.E2E_VARIANT === 'manual-upload') {
requests.some(r => r.url?.includes('/releases') && r.method === 'POST'),
'Expected a POST to create the release',
);

// The auto-instrument plugin loads wrapped modules under this suffix. It must be stripped before
// upload, or the uploaded sources don't match the frames Sentry receives.
const wrappedSources = sourcemaps
.flatMap(map => map.sourcemap.sources ?? [])
.filter(source => source.includes('?sentry-auto-wrap'));
assert.deepEqual(wrappedSources, [], 'Expected no uploaded source to carry the auto-wrap query suffix');
}

console.log('All sourcemap assertions passed!');
Expand Down
2 changes: 0 additions & 2 deletions packages/sveltekit/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -79,8 +79,6 @@
"@sentry/server-utils": "11.19.0",
"@sentry/svelte": "11.19.0",
"@sentry/bundler-plugins": "11.19.0",
"@sveltejs/acorn-typescript": "^1.0.13",
"acorn": "^8.14.0",
"magic-string": "~0.30.0",
"sorcery": "1.0.0"
},
Expand Down
2 changes: 0 additions & 2 deletions packages/sveltekit/src/common/utils.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
import type { HttpError, Redirect } from '@sveltejs/kit';
import { isObjectLike } from '@sentry/core';

export const WRAPPED_MODULE_SUFFIX = '?sentry-auto-wrap';

export type SentryWrappedFlag = {
/**
* If this flag is set, we know that the load event was already wrapped once
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ import {
join,
rewriteFramesIntegration as originalRewriteFramesIntegration,
} from '@sentry/core';
import { WRAPPED_MODULE_SUFFIX } from '../../common/utils';
import type { GlobalWithSentryValues } from '../../vite/injectGlobalValues';

type StackFrameIteratee = (frame: StackFrame) => StackFrame;
Expand Down Expand Up @@ -79,12 +78,6 @@ export function rewriteFramesIteratee(frame: StackFrame): StackFrame {

delete frame.module;

// In dev-mode, the WRAPPED_MODULE_SUFFIX is still present in the frame's file name.
// We need to remove it to make sure that the frame's filename matches the actual file
if (frame.filename.endsWith(WRAPPED_MODULE_SUFFIX)) {
frame.filename = frame.filename.slice(0, -WRAPPED_MODULE_SUFFIX.length);
}

return frame;
}

Expand Down
199 changes: 81 additions & 118 deletions packages/sveltekit/src/vite/autoInstrument.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,20 @@
import { tsPlugin } from '@sveltejs/acorn-typescript';
import * as acorn from 'acorn';
import * as fs from 'fs';
import * as path from 'path';
import {
addImport,
collectDeclaringStatements,
collectManuallyWrappedLocals,
createCallSiteRewriter,
exportedName,
findNamedExports,
type RewriteRule,
type RuleContext,
wrapForeignExport,
wrapInlineExport,
wrapLocalBinding,
wrapSpecifierExports,
} from '@sentry/bundler-plugins/rewriter';
import type { Plugin } from 'vite';
import { WRAPPED_MODULE_SUFFIX } from '../common/utils';
import type { ResolvedKitConfig } from './kitConfig';
import { isNativeServerTracingEnabled } from './kitConfig';
import { stringifyForCodeInjection } from '@sentry/core';

const AcornParser = acorn.Parser.extend(tsPlugin());

export type AutoInstrumentSelection = {
/**
Expand All @@ -34,6 +40,10 @@ type AutoInstrumentPluginOptions = AutoInstrumentSelection & {
getKitConfig: () => Promise<ResolvedKitConfig>;
};

type LoadWrapper = 'wrapLoadWithSentry' | 'wrapServerLoadWithSentry';

const LOAD_WRAPPERS: readonly LoadWrapper[] = ['wrapLoadWithSentry', 'wrapServerLoadWithSentry'];

/**
* Creates a Vite plugin that automatically instruments the parts of the app
* specified in @param options. This includes
Expand All @@ -54,6 +64,15 @@ export function makeAutoInstrumentationPlugin(options: AutoInstrumentPluginOptio
const shouldOnlyInstrumentClient = (): Promise<boolean> =>
(onlyInstrumentClientPromise ??= getKitConfig().then(isNativeServerTracingEnabled));

const universalRules = wrapLoadEnabled
? [loadRule(/^\+(page|layout)\.(js|ts|mjs|mts)$/, 'wrapLoadWithSentry', debug)]
: [];
const serverRules = wrapServerLoadEnabled
? [loadRule(/^\+(page|layout)\.server\.(js|ts|mjs|mts)$/, 'wrapServerLoadWithSentry', debug)]
Comment on lines +68 to +71

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Route loads with Vite’s ?v= query are not auto-wrapped

When Vite passes a route module id such as +page.ts?v=123, the basename rules do not match, so the route’s load function is left unwrapped and its Sentry load span is missed. Preserve the intentional exclusion of special imports such as ?raw when handling query-bearing ids.

Evidence
  • Auto-instrumentation is enabled by default, and transform passes the id directly to the rewriter without normalizing its query.
  • The rules use end-anchored basename patterns; the rewriter tests them against basename(id), so +page.ts?v=123 does not match +page.ts.
  • makeEntryFileMatcher documents that Vite appends queries like ?v=123 to module ids and strips the query; its test confirms a query-bearing SvelteKit entry id is accepted.
  • The auto-instrumentation test only checks that +page.ts?raw is excluded; it does not cover a version-query route id.

Identified by Warden · code-review · AC2-U3Q

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fix attempt detected (commit 479d9d1)

The auto-instrumentation logic was directly rewritten, but the rewriter still tests end-anchored basename rules against basename(id) without stripping query strings, so +page.ts?v=123 remains unwrapped.

The original issue appears unresolved. Please review and try again.

Evaluated by Warden

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The load hook on develop tests the same end-anchored regex against basename(id), so query ids were not wrapped before either; we can add that in a follow-up.

: [];
const universalRewriter = createCallSiteRewriter(universalRules);
const rewriter = createCallSiteRewriter([...universalRules, ...serverRules]);

return {
name: 'sentry-auto-instrumentation',
// This plugin needs to run as early as possible, before the SvelteKit plugin virtualizes all paths and ids
Expand All @@ -67,142 +86,86 @@ export function makeAutoInstrumentationPlugin(options: AutoInstrumentPluginOptio
isServerBuild = !!config.build.ssr;
},

async load(id) {
async transform(code, id) {
// On Vite 6+ `config.build.ssr` captured in `configResolved` no longer reliably reflects the per-environment build.
// Prefer the environment of the current build (`this.environment.name === 'ssr'`) and fall back to
// `isServerBuild` for older Vite versions that don't expose environments.
const environmentName = (this as { environment?: { name?: string } }).environment?.name;
const isServerEnvironment = environmentName != null ? environmentName === 'ssr' : !!isServerBuild;

if (isServerEnvironment && (await shouldOnlyInstrumentClient())) {
return null;
}

const applyUniversalLoadWrapper =
wrapLoadEnabled &&
/^\+(page|layout)\.(js|ts|mjs|mts)$/.test(path.basename(id)) &&
(await canWrapLoad(id, debug));

if (applyUniversalLoadWrapper) {
// eslint-disable-next-line no-console
debug && console.log(`Wrapping ${id} with Sentry load wrapper`);
return getWrapperCode('wrapLoadWithSentry', `${id}${WRAPPED_MODULE_SUFFIX}`);
}

if (await shouldOnlyInstrumentClient()) {
// Now that we've checked universal files, we can early return and avoid further
// regexp checks below for server-only files.
const onlyInstrumentClient = await shouldOnlyInstrumentClient();
if (isServerEnvironment && onlyInstrumentClient) {
return null;
}

const applyServerLoadWrapper =
wrapServerLoadEnabled &&
/^\+(page|layout)\.server\.(js|ts|mjs|mts)$/.test(path.basename(id)) &&
(await canWrapLoad(id, debug));
return (onlyInstrumentClient ? universalRewriter : rewriter).transform(code, id, this);
},
};
}

if (applyServerLoadWrapper) {
function loadRule(basename: RegExp, wrapper: LoadWrapper, debug: boolean): RewriteRule {
return {
name: wrapper,
include: { basename, contains: ['load'] },
apply: ctx => {
if (wrapLoadExport(ctx, wrapper)) {
// eslint-disable-next-line no-console
debug && console.log(`Wrapping ${id} with Sentry load wrapper`);
return getWrapperCode('wrapServerLoadWithSentry', `${id}${WRAPPED_MODULE_SUFFIX}`);
debug && console.log(`Wrapping ${ctx.id} with Sentry load wrapper`);
}

return null;
},
};
}

/**
* We only want to apply our wrapper to files that
* Wraps the module's `load` export in place, in any export form, unless the
* user already wrapped it.
*
* - Have no Sentry code yet in them. This is to avoid double-wrapping or interfering with custom
* Sentry calls.
* - Actually declare a `load` function. The second check of course is not 100% accurate, but it's good enough.
* Injecting our wrapper into files that don't declare a `load` function would result in a build-time warning
* because vite/rollup warns if we reference an export from the user's file in our wrapping code that
* doesn't exist.
*
* Exported for testing
*
* @returns `true` if we can wrap the given file, `false` otherwise
* @returns whether the export was wrapped
*/
export async function canWrapLoad(id: string, debug: boolean): Promise<boolean> {
// Some 3rd party plugins add ids to the build that actually don't exist.
// We need to check for that here, otherwise users get get a build errors.
if (!fs.existsSync(id)) {
debug &&
// eslint-disable-next-line no-console
console.log(
`Skipping wrapping ${id} because it doesn't exist. A 3rd party plugin might have added this as a virtual file to the build`,
);
return false;
}

const code = (await fs.promises.readFile(id, 'utf8')).toString();

let program: acorn.Program;
try {
program = AcornParser.parse(code, {
sourceType: 'module',
ecmaVersion: 'latest',
locations: true,
});
} catch {
// eslint-disable-next-line no-console
debug && console.log(`Skipping wrapping ${id} because it doesn't contain valid JavaScript or TypeScript`);
return false;
}

const hasLoadDeclaration = program.body
.filter((statement): statement is acorn.ExportNamedDeclaration => statement.type === 'ExportNamedDeclaration')
.find(exportDecl => {
// find `export const load = ...`
if (exportDecl.declaration?.type === 'VariableDeclaration') {
const variableDeclarations = exportDecl.declaration.declarations;
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved
return variableDeclarations.find(
decl => decl.type === 'VariableDeclarator' && decl.id.type === 'Identifier' && decl.id.name === 'load',
);
function wrapLoadExport({ ast, state }: RuleContext, wrapper: LoadWrapper): boolean {
const handWrapped = collectManuallyWrappedLocals(ast, LOAD_WRAPPERS);
const declaringStatements = collectDeclaringStatements(ast);
// The wrapper runs while the module loads, so `load` may still be unset.
const wrap = (target: string): string => `typeof ${target} === 'function' ? ${wrapper}(${target}) : ${target}`;
let wrapped = false;

for (const node of findNamedExports(ast, 'load')) {
if (node.declaration) {
if (handWrapped.has('load')) {
state.report.alreadyWrapped.push('load');
} else if (wrapInlineExport(state, node, 'load', wrap)) {
wrapped = true;
}
continue;
}

// find `export function load = ...`
if (exportDecl.declaration?.type === 'FunctionDeclaration') {
const functionId = exportDecl.declaration.id;
return functionId?.name === 'load';
wrapSpecifierExports(state, node, (specifier, sourceLiteral, prelude) => {
const local = specifier.local?.type === 'Identifier' ? specifier.local.name : undefined;
if (exportedName(specifier.exported) !== 'load' || !local) return undefined;

if (sourceLiteral) {
wrapped = true;
return wrapForeignExport(state, local, 'load', sourceLiteral, prelude, wrap);
}

// find `export { load, somethingElse as load, somethingElse as "load" }`
if (exportDecl.specifiers) {
return exportDecl.specifiers.find(specifier => {
return (
(specifier.exported.type === 'Identifier' && specifier.exported.name === 'load') ||
// ESTree/acorn represents `export { x as "load" }` with a Literal node (not Babel's StringLiteral)
(specifier.exported.type === 'Literal' && specifier.exported.value === 'load')
);
});
const declaringStatement = declaringStatements.get(local);
if (handWrapped.has(local)) {
state.report.alreadyWrapped.push('load');
return undefined;
}
if (!declaringStatement) return undefined;
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved

return false;
wrapped = true;
return `${wrapLocalBinding(state, local, declaringStatement, wrap)} as load`;
});

if (!hasLoadDeclaration) {
// eslint-disable-next-line no-console
debug && console.log(`Skipping wrapping ${id} because it doesn't declare a \`load\` function`);
return false;
}

return true;
}

/**
* Return wrapper code fo the given module id and wrapping function
*/
function getWrapperCode(
wrapperFunction: 'wrapLoadWithSentry' | 'wrapServerLoadWithSentry',
idWithSuffix: string,
): string {
return (
`import { ${wrapperFunction} } from "@sentry/sveltekit";` +
`import * as userModule from ${stringifyForCodeInjection(idWithSuffix)};` +
`export const load = userModule.load ? ${wrapperFunction}(userModule.load) : undefined;` +
`export * from ${stringifyForCodeInjection(idWithSuffix)};`
);
if (wrapped) {
state.report.wrapped.push('load');
// The module may already bind the wrapper, e.g. through a re-export.
if (!declaringStatements.has(wrapper)) {
addImport(state, ast, `import { ${wrapper} } from '@sentry/sveltekit';`);
}
}
return wrapped;
}
23 changes: 1 addition & 22 deletions packages/sveltekit/src/vite/sourceMaps.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,4 @@
import {
escapeStringForRegex,
resolveSourceMapsFeatures,
uuid4,
warnOnConflictingSourceMapOptions,
} from '@sentry/core';
import { resolveSourceMapsFeatures, uuid4, warnOnConflictingSourceMapOptions } from '@sentry/core';
import { getSentryRelease } from '@sentry/node';
import { addDebugIdToEmittedArtifacts, hasSourceMapUploadCredentials } from '@sentry/bundler-plugins/core';
import type { SentryVitePluginOptions } from '@sentry/bundler-plugins/vite';
Expand All @@ -12,7 +7,6 @@ import * as child_process from 'child_process';
import * as fs from 'fs';
import * as path from 'path';
import type { Plugin, UserConfig } from 'vite';
import { WRAPPED_MODULE_SUFFIX } from '../common/utils';
import { makeReleaseInjectionPlugin } from './injectRelease';
import type { ResolvedKitConfig } from './kitConfig';
import type { CustomSentryVitePluginOptions } from './types';
Expand Down Expand Up @@ -249,21 +243,6 @@ export async function makeCustomSentryVitePlugins(
console.error('[Source Maps Plugin] error while flattening', file, e);
}
}

// We need to remove the query string from the source map files that our auto-instrument plugin added
// to proxy the load functions during building.
const mapFile = `${file}.map`;
try {
const mapContent = (await fs.promises.readFile(mapFile, 'utf-8')).toString();
const cleanedMapContent = mapContent.replace(
// oxlint-disable-next-line sdk/no-regexp-constructor -- no user input + escaped anyway
new RegExp(escapeStringForRegex(WRAPPED_MODULE_SUFFIX), 'gm'),
'',
);
await fs.promises.writeFile(mapFile, cleanedMapContent);
} catch {
// Map file doesn't exist, nothing to clean
}
}

if (sourceMapsFeatures.injectDebugIds && !sourceMapsFeatures.upload) {
Expand Down
Loading
Loading