From c4326d62f3bbf481da8b624e6e6c9f8970234507 Mon Sep 17 00:00:00 2001 From: Tim Fish Date: Thu, 22 Oct 2026 02:06:07 +0100 Subject: [PATCH 1/3] ref(sveltekit): Wrap load functions in place with the rewriter core The `load` hook served a proxy module that re-exported the route file under a `?sentry-auto-wrap` query. That doubled the module count per route, leaked the query into stack frames and source maps, and could not wrap `export { load } from './shared'`. The transform now wraps the `load` export in the route file itself, so the query and the code that stripped it again are gone. It reads the code Vite hands over instead of a second copy from disk, so acorn is no longer needed. --- packages/sveltekit/package.json | 2 - packages/sveltekit/src/common/utils.ts | 2 - .../integrations/rewriteFramesIntegration.ts | 7 - packages/sveltekit/src/vite/autoInstrument.ts | 198 +++++------ packages/sveltekit/src/vite/sourceMaps.ts | 18 +- .../test/vite/autoInstrument.test.ts | 330 +++++++++++------- pnpm-lock.yaml | 6 - 7 files changed, 290 insertions(+), 273 deletions(-) diff --git a/packages/sveltekit/package.json b/packages/sveltekit/package.json index c1deb7cb00b8..64627dc35fee 100644 --- a/packages/sveltekit/package.json +++ b/packages/sveltekit/package.json @@ -79,8 +79,6 @@ "@sentry/server-utils": "11.16.0", "@sentry/svelte": "11.16.0", "@sentry/bundler-plugins": "11.16.0", - "@sveltejs/acorn-typescript": "^1.0.13", - "acorn": "^8.14.0", "magic-string": "~0.30.0", "sorcery": "1.0.0" }, diff --git a/packages/sveltekit/src/common/utils.ts b/packages/sveltekit/src/common/utils.ts index 73326f81e146..3283034c9780 100644 --- a/packages/sveltekit/src/common/utils.ts +++ b/packages/sveltekit/src/common/utils.ts @@ -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 diff --git a/packages/sveltekit/src/server-common/integrations/rewriteFramesIntegration.ts b/packages/sveltekit/src/server-common/integrations/rewriteFramesIntegration.ts index f9f6873d2933..a995ba4790dc 100644 --- a/packages/sveltekit/src/server-common/integrations/rewriteFramesIntegration.ts +++ b/packages/sveltekit/src/server-common/integrations/rewriteFramesIntegration.ts @@ -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; @@ -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; } diff --git a/packages/sveltekit/src/vite/autoInstrument.ts b/packages/sveltekit/src/vite/autoInstrument.ts index acfe24e05c01..3c16cf8b1001 100644 --- a/packages/sveltekit/src/vite/autoInstrument.ts +++ b/packages/sveltekit/src/vite/autoInstrument.ts @@ -1,14 +1,21 @@ -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, + hasImport, + 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 = { /** @@ -34,6 +41,10 @@ type AutoInstrumentPluginOptions = AutoInstrumentSelection & { getKitConfig: () => Promise; }; +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 @@ -54,6 +65,15 @@ export function makeAutoInstrumentationPlugin(options: AutoInstrumentPluginOptio const shouldOnlyInstrumentClient = (): Promise => (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)] + : []; + 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 @@ -67,142 +87,84 @@ 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 { - // 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; - 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); + const wrap = (target: string): string => `${wrapper}(${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; - 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'); + if (!hasImport(ast, '@sentry/sveltekit', wrapper)) { + addImport(state, ast, `import { ${wrapper} } from '@sentry/sveltekit';`); + } + } + return wrapped; } diff --git a/packages/sveltekit/src/vite/sourceMaps.ts b/packages/sveltekit/src/vite/sourceMaps.ts index 65ee6b13e797..2e3c4faad775 100644 --- a/packages/sveltekit/src/vite/sourceMaps.ts +++ b/packages/sveltekit/src/vite/sourceMaps.ts @@ -1,4 +1,4 @@ -import { escapeStringForRegex, resolveSourceMapsFeatures, uuid4 } from '@sentry/core'; +import { resolveSourceMapsFeatures, uuid4 } from '@sentry/core'; import { getSentryRelease } from '@sentry/node'; import { addDebugIdToEmittedArtifacts } from '@sentry/bundler-plugins/core'; import type { SentryVitePluginOptions } from '@sentry/bundler-plugins/vite'; @@ -7,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'; @@ -243,21 +242,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) { diff --git a/packages/sveltekit/test/vite/autoInstrument.test.ts b/packages/sveltekit/test/vite/autoInstrument.test.ts index 67e3b5ed56db..e6d725fddce2 100644 --- a/packages/sveltekit/test/vite/autoInstrument.test.ts +++ b/packages/sveltekit/test/vite/autoInstrument.test.ts @@ -1,5 +1,7 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { canWrapLoad, makeAutoInstrumentationPlugin } from '../../src/vite/autoInstrument'; +import { parseModule } from '@sentry/bundler-plugins/rewriter'; +import { parseSync, type Plugin } from 'vite'; +import { describe, expect, it, vi } from 'vitest'; +import { makeAutoInstrumentationPlugin } from '../../src/vite/autoInstrument'; import type { ResolvedKitConfig } from '../../src/vite/kitConfig'; const DEFAULT_CONTENT = ` @@ -7,40 +9,61 @@ const DEFAULT_CONTENT = ` export const prerender = true; `; -let fileContent: string | undefined; - -vi.mock('fs', async () => { - const actual = await vi.importActual('fs'); - return { - ...actual, - promises: { - // @ts-expect-error this also exists, I promise! - ...actual.promises, - readFile: vi.fn().mockImplementation(() => { - return fileContent || DEFAULT_CONTENT; - }), - }, - existsSync: vi.fn().mockImplementation(id => { - if (id === '+page.virtual.ts') { - return false; - } - return true; - }), - }; -}); - -vi.mock('rollup', () => { - return { - rollup: vi.fn().mockReturnValue({ generate: vi.fn().mockReturnValue({ output: ['transformed'] }) }), - }; -}); +type TransformResult = { code: string; map: unknown } | null; + +function transform( + plugin: Plugin, + id: string, + code = DEFAULT_CONTENT, + context: Record = {}, +): Promise { + // @ts-expect-error this exists and is callable + return plugin.transform.call(context, code, id); +} + +interface Node { + type: string; + [key: string]: any; +} + +/** + * Asserts that `result` parses, imports `wrapper` from `@sentry/sveltekit`, and exports as `load` + * a binding initialised with a call to `wrapper`. + * + * @returns the argument passed to `wrapper` + */ +function expectWrappedLoad(result: TransformResult, id: string, wrapper: string): string { + expect(result).not.toBeNull(); + const program = parseModule(result!.code, id) as unknown as { body: Node[] }; + + const imports = program.body.filter( + node => node.type === 'ImportDeclaration' && node.source.value === '@sentry/sveltekit', + ); + expect(imports.flatMap(node => node.specifiers.map((specifier: Node) => specifier.imported.name))).toEqual([wrapper]); + + const loadExports = program.body + .filter(node => node.type === 'ExportNamedDeclaration') + .flatMap(node => [ + ...(node.specifiers ?? []).filter( + (specifier: Node) => (specifier.exported.name ?? specifier.exported.value) === 'load', + ), + ...(node.declaration?.declarations ?? []).filter((declarator: Node) => declarator.id.name === 'load'), + ...(node.declaration?.id?.name === 'load' ? [node.declaration] : []), + ]); + expect(loadExports).toHaveLength(1); + const local = loadExports[0].local.name; + + const declarator = program.body + .filter(node => node.type === 'VariableDeclaration') + .flatMap(node => node.declarations) + .find((declarator: Node) => declarator.id.name === local); + expect(declarator.init.type).toBe('CallExpression'); + expect(declarator.init.callee.name).toBe(wrapper); + expect(declarator.init.arguments).toHaveLength(1); + return declarator.init.arguments[0].name; +} describe('makeAutoInstrumentationPlugin()', () => { - beforeEach(() => { - vi.clearAllMocks(); - fileContent = undefined; - }); - it('returns the auto instrumentation plugin', async () => { const plugin = makeAutoInstrumentationPlugin({ debug: true, @@ -50,7 +73,7 @@ describe('makeAutoInstrumentationPlugin()', () => { }); expect(plugin.name).toEqual('sentry-auto-instrumentation'); expect(plugin.enforce).toEqual('pre'); - expect(plugin.load).toEqual(expect.any(Function)); + expect(plugin.transform).toEqual(expect.any(Function)); }); describe.each([ @@ -70,14 +93,10 @@ describe('makeAutoInstrumentationPlugin()', () => { serverLoad: true, getKitConfig: async () => ({}), }); - // @ts-expect-error this exists - const loadResult = await plugin.load(path); - expect(loadResult).toEqual( - 'import { wrapLoadWithSentry } from "@sentry/sveltekit";' + - `import * as userModule from "${path}?sentry-auto-wrap";` + - 'export const load = userModule.load ? wrapLoadWithSentry(userModule.load) : undefined;' + - `export * from "${path}?sentry-auto-wrap";`, - ); + const result = await transform(plugin, path); + expect(expectWrappedLoad(result, path, 'wrapLoadWithSentry')).toBe('load'); + expect(result!.code).toContain('const load = () => {};'); + expect(result!.map).toBeDefined(); }); it("doesn't wrap universal load if `load` option is `false`", async () => { @@ -87,9 +106,7 @@ describe('makeAutoInstrumentationPlugin()', () => { serverLoad: false, getKitConfig: async () => ({}), }); - // @ts-expect-error this exists - const loadResult = await plugin.load(path); - expect(loadResult).toEqual(null); + expect(await transform(plugin, path)).toEqual(null); }); }); @@ -103,36 +120,69 @@ describe('makeAutoInstrumentationPlugin()', () => { 'path/to/+layout.server.mts', 'path/to/+layout.server.mjs', ])('transform %s files', (path: string) => { - it('wraps universal load if `load` option is `true`', async () => { + it('wraps server load if `serverLoad` option is `true`', async () => { const plugin = makeAutoInstrumentationPlugin({ debug: false, load: false, serverLoad: true, getKitConfig: async () => ({}), }); - // @ts-expect-error this exists - const loadResult = await plugin.load(path); - expect(loadResult).toEqual( - 'import { wrapServerLoadWithSentry } from "@sentry/sveltekit";' + - `import * as userModule from "${path}?sentry-auto-wrap";` + - 'export const load = userModule.load ? wrapServerLoadWithSentry(userModule.load) : undefined;' + - `export * from "${path}?sentry-auto-wrap";`, - ); + expect(expectWrappedLoad(await transform(plugin, path), path, 'wrapServerLoadWithSentry')).toBe('load'); }); - it("doesn't wrap universal load if `load` option is `false`", async () => { + it("doesn't wrap server load if `serverLoad` option is `false`", async () => { const plugin = makeAutoInstrumentationPlugin({ debug: false, load: false, serverLoad: false, getKitConfig: async () => ({}), }); - // @ts-expect-error this exists - const loadResult = await plugin.load(path); - expect(loadResult).toEqual(null); + expect(await transform(plugin, path)).toEqual(null); }); }); + it.each(['path/to/+page.svelte', 'path/to/page.ts', 'path/to/+server.ts', 'path/to/+page.ts?raw'])( + "doesn't transform %s", + async (path: string) => { + const plugin = makeAutoInstrumentationPlugin({ + debug: false, + load: true, + serverLoad: true, + getKitConfig: async () => ({}), + }); + expect(await transform(plugin, path)).toEqual(null); + }, + ); + + it("parses with Rolldown's `this.parse` in Vite 8", async () => { + const plugin = makeAutoInstrumentationPlugin({ + debug: false, + load: true, + serverLoad: true, + getKitConfig: async () => ({}), + }); + const parse = vi.fn((input: string, options: object) => parseSync('module', input, options).program); + const path = 'path/to/+page.ts'; + const code = 'export const load: PageLoad = async () => ({});'; + + const result = await transform(plugin, path, code, { meta: { rolldownVersion: '1.2.11' }, parse }); + expect(parse).toHaveBeenCalledWith(code, { lang: 'ts', preserveParens: false }); + expectWrappedLoad(result, path, 'wrapLoadWithSentry'); + }); + + it('logs the wrapped file in debug mode', async () => { + const consoleLogSpy = vi.spyOn(console, 'log').mockImplementation(() => {}); + const plugin = makeAutoInstrumentationPlugin({ + debug: true, + load: true, + serverLoad: true, + getKitConfig: async () => ({}), + }); + await transform(plugin, 'path/to/+page.ts'); + expect(consoleLogSpy).toHaveBeenCalledWith('Wrapping path/to/+page.ts with Sentry load wrapper'); + consoleLogSpy.mockRestore(); + }); + describe('when SvelteKit native server tracing is enabled (client-only instrumentation)', () => { it.each([ // server-only files @@ -156,10 +206,7 @@ describe('makeAutoInstrumentationPlugin()', () => { }, }); - // @ts-expect-error this exists - const loadResult = await plugin.load(path); - - expect(loadResult).toEqual(null); + expect(await transform(plugin, path)).toEqual(null); }); it.each(['path/to/+page.ts', 'path/to/+layout.js'])( @@ -179,21 +226,13 @@ describe('makeAutoInstrumentationPlugin()', () => { }, }); - // @ts-expect-error this exists and is callable - const loadResult = await plugin.load(path); - - expect(loadResult).toBe( - 'import { wrapLoadWithSentry } from "@sentry/sveltekit";' + - `import * as userModule from "${path}?sentry-auto-wrap";` + - 'export const load = userModule.load ? wrapLoadWithSentry(userModule.load) : undefined;' + - `export * from "${path}?sentry-auto-wrap";`, - ); + expectWrappedLoad(await transform(plugin, path), path, 'wrapLoadWithSentry'); }, ); /** * This is a bit of a constructed case because in a client build, server-only files - * shouldn't even be passed into the load hook. But just to be extra careful, let's + * shouldn't even be passed into the transform hook. But just to be extra careful, let's * make sure we don't wrap server-only files in a client build. */ it.each(['path/to/+page.server.ts', 'path/to/+layout.server.js'])( @@ -213,10 +252,7 @@ describe('makeAutoInstrumentationPlugin()', () => { }, }); - // @ts-expect-error this exists and is callable - const loadResult = await plugin.load(path); - - expect(loadResult).toBe(null); + expect(await transform(plugin, path)).toBe(null); }, ); }); @@ -244,10 +280,7 @@ describe('makeAutoInstrumentationPlugin()', () => { // @ts-expect-error this exists and is callable plugin.configResolved({ build: { ssr: true } }); - // @ts-expect-error this exists and is callable - const loadResult = await plugin.load(path); - - expect(loadResult).toEqual(null); + expect(await transform(plugin, path)).toEqual(null); }, ); @@ -263,15 +296,7 @@ describe('makeAutoInstrumentationPlugin()', () => { plugin.configResolved({ build: { ssr: true } }); const path = 'path/to/+page.server.ts'; - // @ts-expect-error this exists and is callable - const loadResult = await plugin.load(path); - - expect(loadResult).toBe( - 'import { wrapServerLoadWithSentry } from "@sentry/sveltekit";' + - `import * as userModule from "${path}?sentry-auto-wrap";` + - 'export const load = userModule.load ? wrapServerLoadWithSentry(userModule.load) : undefined;' + - `export * from "${path}?sentry-auto-wrap";`, - ); + expectWrappedLoad(await transform(plugin, path), path, 'wrapServerLoadWithSentry'); }); }); }); @@ -293,10 +318,7 @@ describe('makeAutoInstrumentationPlugin()', () => { }); // `configResolved` is intentionally not called - `isServerBuild` stays `undefined` - // @ts-expect-error this exists and is callable; bind `this.environment` like Vite does - const loadResult = await plugin.load.call({ environment: { name: 'ssr' } }, path); - - expect(loadResult).toEqual(null); + expect(await transform(plugin, path, DEFAULT_CONTENT, { environment: { name: 'ssr' } })).toEqual(null); }, ); @@ -309,41 +331,48 @@ describe('makeAutoInstrumentationPlugin()', () => { }); const path = 'path/to/+page.ts'; - // @ts-expect-error this exists and is callable; bind `this.environment` like Vite does - const loadResult = await plugin.load.call({ environment: { name: 'client' } }, path); - - expect(loadResult).toBe( - 'import { wrapLoadWithSentry } from "@sentry/sveltekit";' + - `import * as userModule from "${path}?sentry-auto-wrap";` + - 'export const load = userModule.load ? wrapLoadWithSentry(userModule.load) : undefined;' + - `export * from "${path}?sentry-auto-wrap";`, - ); + const result = await transform(plugin, path, DEFAULT_CONTENT, { environment: { name: 'client' } }); + expectWrappedLoad(result, path, 'wrapLoadWithSentry'); }); }); }); -describe('canWrapLoad', () => { - afterEach(() => { - fileContent = undefined; - }); +describe('load export forms', () => { + const PATH = 'path/to/+page.ts'; + + function transformPage(code: string): Promise { + const plugin = makeAutoInstrumentationPlugin({ + debug: false, + load: true, + serverLoad: true, + getKitConfig: async () => ({}), + }); + return transform(plugin, PATH, code); + } it.each([ - ['export variable declaration - function pointer', 'export const load= loadPageData'], - ['export variable declaration - factory function call', 'export const load =loadPageData()'], - ['export variable declaration - inline function', 'export const load = () => { return { props: { msg: "hi" } } }'], - ['export variable declaration - inline function let', 'export let load = () => {}'], + ['export variable declaration - function pointer', 'export const load= loadPageData', 'load'], + ['export variable declaration - factory function call', 'export const load =loadPageData()', 'load'], + [ + 'export variable declaration - inline function', + 'export const load = () => { return { props: { msg: "hi" } } }', + 'load', + ], + ['export variable declaration - inline function let', 'export let load = () => {}', 'load'], [ 'export variable declaration - inline async function', 'export const load = async () => { return { props: { msg: "hi" } } }', + 'load', ], - ['export function declaration', 'export function load ( ){ return { props: { msg: "hi" } } }'], + ['export function declaration', 'export function load ( ){ return { props: { msg: "hi" } } }', 'load'], [ 'export function declaration - with params', `export async function load({fetch}){ const res = await fetch('https://example.com'); return { props: { msg: res.toString() } } }`, + 'load', ], [ 'export function declaration - with angle bracket type assertion', @@ -353,6 +382,7 @@ describe('canWrapLoad', () => { msg: x, }; }`, + 'load', ], [ 'variable declaration (let)', @@ -360,6 +390,7 @@ describe('canWrapLoad', () => { let load = async () => {}; export const prerender = true; export { load}`, + 'load', ], [ 'variable declaration (var)', @@ -367,6 +398,7 @@ describe('canWrapLoad', () => { var load=async () => {}; export const prerender = true; export { load}`, + 'load', ], [ @@ -374,6 +406,7 @@ describe('canWrapLoad', () => { `import {something} from 'somewhere'; async function load(){}; export { load }`, + 'load', ], [ 'function declaration, sentry commented out', @@ -381,6 +414,7 @@ describe('canWrapLoad', () => { // import * as Sentry from '@sentry/sveltekit'; async function load(){}; export { load }`, + 'load', ], [ 'function declaration, sentry commented out', @@ -388,27 +422,81 @@ describe('canWrapLoad', () => { /* import * as Sentry from '@sentry/sveltekit'; */ async function load(){}; export { load }`, + 'load', ], [ 'function declaration with different name', `import { foo } from 'somewhere'; async function somethingElse(){}; export { somethingElse as load, foo }`, + 'somethingElse', ], [ 'function declaration with different string literal name', `import { foo } from 'somewhere'; async function somethingElse(){}; export { somethingElse as "load", foo }`, + 'somethingElse', ], [ 'export variable declaration - inline function with assigned type', `import type { LayoutLoad } from './$types'; export const load : LayoutLoad = async () => { return { props: { msg: "hi" } } }`, + 'load', + ], + ['re-export from another module', "export { load } from './shared';", '__SENTRY_REEXPORT_load__'], + [ + 'aliased re-export from another module', + "export { sharedLoad as load, other } from './shared';", + '__SENTRY_REEXPORT_load__', + ], + ['imported binding exported again', "import { load } from './shared';\nexport { load };", 'load'], + ])('wraps a load declaration (%s)', async (_, code, target) => { + expect(expectWrappedLoad(await transformPage(code), PATH, 'wrapLoadWithSentry')).toBe(target); + }); + + it('keeps the other exports of the rewritten statements', async () => { + const code = [ + "import { foo } from 'somewhere';", + 'async function somethingElse(){};', + 'export const load = () => {}, prerender = true;', + "export { foo } from './shared';", + 'export { somethingElse as other };', + ].join('\n'); + const result = await transformPage(code); + expectWrappedLoad(result, PATH, 'wrapLoadWithSentry'); + expect(result!.code).toContain('export { __SENTRY_WRAPPED_load__ as load, prerender };'); + expect(result!.code).toContain("export { foo } from './shared';"); + expect(result!.code).toContain('export { somethingElse as other };'); + }); + + it("inserts the import after a 'use strict' directive", async () => { + const result = await transformPage("'use strict';\nexport const load = () => {};"); + expect(result!.code).toMatch(/^'use strict';\nimport \{ wrapLoadWithSentry \} from '@sentry\/sveltekit';/); + }); + + it('does not add a second import of the wrapper', async () => { + const result = await transformPage( + "import { wrapLoadWithSentry } from '@sentry/sveltekit';\nexport const load = () => {};", + ); + expectWrappedLoad(result, PATH, 'wrapLoadWithSentry'); + }); + + it.each([ + [ + 'inline', + "import { wrapLoadWithSentry } from '@sentry/sveltekit';\nexport const load = wrapLoadWithSentry(() => {});", + ], + [ + 'through a namespace', + "import * as Sentry from '@sentry/sveltekit';\nexport const load = Sentry.wrapLoadWithSentry(() => {});", + ], + [ + 'by specifier', + "import { wrapServerLoadWithSentry } from '@sentry/sveltekit';\nconst wrapped = wrapServerLoadWithSentry(() => {});\nexport { wrapped as load };", ], - ])('returns `true` if a load declaration (%s) exists', async (_, code) => { - fileContent = code; - expect(await canWrapLoad('+page.ts', false)).toEqual(true); + ])('leaves a load the user wrapped by hand alone (%s)', async (_, code) => { + expect(await transformPage(code)).toBeNull(); }); it.each([ @@ -423,13 +511,13 @@ describe('canWrapLoad', () => { '// const load = () => {}', '/* export const load = () => {} */ export const prerender = true;', '/* export const notLoad = () => { const a = getSomething() as load; } */ export const prerender = true;', - ])('returns `false` if no load declaration exists', async code => { - fileContent = code; - expect(await canWrapLoad('+page.ts', false)).toEqual(false); + 'const load = () => {}; export { load as other };', + "export type { load } from './types';", + ])('does not transform a module without a load export: %s', async code => { + expect(await transformPage(code)).toBeNull(); }); - it("returns `false` if the passed file id doesn't exist", async () => { - fileContent = DEFAULT_CONTENT; - expect(await canWrapLoad('+page.virtual.ts', false)).toEqual(false); + it('does not transform a module that does not parse', async () => { + expect(await transformPage('export const load = (')).toBeNull(); }); }); diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index ac2997feb994..4001975ee91d 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -2389,12 +2389,6 @@ importers: '@sentry/svelte': specifier: 11.16.0 version: link:../svelte - '@sveltejs/acorn-typescript': - specifier: ^1.0.13 - version: 1.0.13(acorn@8.18.0) - acorn: - specifier: ^8.14.0 - version: 8.18.0 magic-string: specifier: ~0.30.0 version: 0.30.21 From d79a0b904332ed7e8061cacc51198d840e8aa561 Mon Sep 17 00:00:00 2001 From: Tim Fish Date: Wed, 4 Nov 2026 14:19:58 +0000 Subject: [PATCH 2/3] test(sveltekit): Expect the load frame under its own name The proxy module renamed the route `load` to `load$1` in the bundle. In-place wrapping keeps the name. --- .../test-applications/sveltekit-2/tests/errors.server.test.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/dev-packages/e2e-tests/test-applications/sveltekit-2/tests/errors.server.test.ts b/dev-packages/e2e-tests/test-applications/sveltekit-2/tests/errors.server.test.ts index 38522e6de6f1..7c0bd607e5ec 100644 --- a/dev-packages/e2e-tests/test-applications/sveltekit-2/tests/errors.server.test.ts +++ b/dev-packages/e2e-tests/test-applications/sveltekit-2/tests/errors.server.test.ts @@ -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, }), ); @@ -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, }), ); From 1f3c7dbb90e8ba8380e9ecb6d2b4d0ed0f40decd Mon Sep 17 00:00:00 2001 From: Tim Fish Date: Mon, 23 Nov 2026 15:25:36 +0000 Subject: [PATCH 3/3] test(sveltekit): Drop the auto-wrap suffix check from the source maps app Load functions are wrapped in the route file itself, so no module carries the `?sentry-auto-wrap` query. --- .../sveltekit-3-sourcemaps/assert-build.ts | 9 +-------- 1 file changed, 1 insertion(+), 8 deletions(-) diff --git a/dev-packages/e2e-tests/test-applications/sveltekit-3-sourcemaps/assert-build.ts b/dev-packages/e2e-tests/test-applications/sveltekit-3-sourcemaps/assert-build.ts index 0db412f72fce..9b2249dfc67e 100644 --- a/dev-packages/e2e-tests/test-applications/sveltekit-3-sourcemaps/assert-build.ts +++ b/dev-packages/e2e-tests/test-applications/sveltekit-3-sourcemaps/assert-build.ts @@ -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. @@ -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!');