From f04f3a472dc340e9b9db79aefde1c80b5f774ce6 Mon Sep 17 00:00:00 2001 From: Tim Fish Date: Thu, 22 Oct 2026 02:02:20 +0100 Subject: [PATCH 1/3] ref(cloudflare): Build the Vite auto-instrument on the rewriter core The export handling moves into the shared rewriter core, so SvelteKit and TanStack Start get the same export forms. Sibling modules are now parsed with oxc instead of a regex scanner, which reads TypeScript without guessing at its syntax. The entry falls back to oxc when `this.parse` cannot read it, where it was skipped before. --- packages/cloudflare/package.json | 2 +- packages/cloudflare/src/vite/agentClass.ts | 6 +- .../cloudflare/src/vite/autoInstrument.ts | 180 ++++--- packages/cloudflare/src/vite/moduleShape.ts | 402 +-------------- packages/cloudflare/src/vite/transform.ts | 473 ++++-------------- .../cloudflare/src/vite/workerEntrypoint.ts | 135 +---- .../cloudflare/test/vite/agentClass.test.ts | 10 +- .../test/vite/autoInstrument.test.ts | 12 +- .../cloudflare/test/vite/transform.test.ts | 10 +- pnpm-lock.yaml | 6 +- 10 files changed, 230 insertions(+), 1006 deletions(-) diff --git a/packages/cloudflare/package.json b/packages/cloudflare/package.json index e74f2cc3a0c8..625a23ef6d50 100644 --- a/packages/cloudflare/package.json +++ b/packages/cloudflare/package.json @@ -53,6 +53,7 @@ }, "dependencies": { "@opentelemetry/api": "^1.9.1", + "@sentry/bundler-plugins": "11.18.0", "@sentry/conventions": "^0.36.0", "@sentry/core": "11.19.0", "@sentry/opentelemetry": "11.19.0", @@ -79,7 +80,6 @@ "@cloudflare/workers-types": "5.20260710.1", "@sentry-internal/rollup-utils": "11.19.0", "@types/node": "^20.19.0", - "acorn": "^8.14.0", "vite": "^8.3.6", "wrangler": "4.156.0" }, diff --git a/packages/cloudflare/src/vite/agentClass.ts b/packages/cloudflare/src/vite/agentClass.ts index d335a7ad44a2..13915cf5333f 100644 --- a/packages/cloudflare/src/vite/agentClass.ts +++ b/packages/cloudflare/src/vite/agentClass.ts @@ -64,8 +64,8 @@ export async function detectAgentClasses( candidates: Iterable, resolver: ModuleResolver, ): Promise> { - // The entry's shape comes from the AST Vite already handed us (TypeScript stripped, full - // fidelity); only sibling modules fall back to source scanning. + // The entry's shape comes from the AST the plugin already parsed; sibling modules are parsed + // from their source on disk. const ctx: DetectContext = { resolver, modules: new Map([[entryId, shapeFromAst(ast)]]) }; const detected = new Set(); @@ -225,7 +225,7 @@ async function getModuleShape(ctx: DetectContext, moduleId: string): Promise { - if (!wranglerConfig || (!entryFilePath && !entrySpecifier)) return undefined; + const config = wranglerConfig; + if (!config || (!entryFilePath && !entrySpecifier)) return undefined; // The worker entry never belongs to the client (browser) environment. // Skipping it keeps a same-basename sibling (e.g. a `src/index.tsx` @@ -251,86 +253,102 @@ export function sentryCloudflareAutoInstrumentPlugin(options: { wranglerConfigPa } } - let ast: ProgramBody; - try { - ast = this.parse(code); - } catch { - // Raw TypeScript or syntax error — esbuild hasn't run yet (unlikely) - // or the file is genuinely broken. Either way, skip silently. - return undefined; - } - - const classWrappers = new Map(); - for (const { className } of wranglerConfig.durableObjects) { - classWrappers.set(className, 'durableObject'); - } - for (const { className } of wranglerConfig.workflows) { - classWrappers.set(className, 'workflow'); - } - for (const className of wranglerConfig.workerEntrypoints) { - classWrappers.set(className, 'workerEntrypoint'); - } - - // An `agents` Agent is a Durable Object, so wrangler lists it among the DO bindings and only - // its base-class chain tells the two apart. Detection walks the module graph (base classes - // usually live in their own file), so it is limited to the configured DO classes. - // - // Only `resolve` is handed over — never `load`: awaiting `load()` from inside a transform - // hook deadlocks the build, since the module can't finish loading while this transform is - // still pending. `agentClass` reads sibling modules off disk instead. - const agentCandidates = collectAgentCandidates( - ast, - [...classWrappers].filter(([, kind]) => kind === 'durableObject').map(([name]) => name), - ); - const agentClasses = - agentCandidates.size > 0 - ? await detectAgentClasses(ast, normalizedId, agentCandidates, { - parse: code => this.parse(code), - resolve: this.resolve?.bind(this), - }) - : undefined; - - // A vinext app with `@sentry/nextjs` installed gets `withSentry` of `@sentry/nextjs/cloudflare`. - const sentryModule = - isVinext && (await resolvesNextjsCloudflare(this, normalizedId)) ? NEXTJS_CLOUDFLARE_MODULE : undefined; - - const { optionsFn, importStmt: optionsImport } = instrumentFilePath - ? // A virtual module has no directory to import from relatively. - buildOptionsImport(entryPath, instrumentFilePath, { absolute: !!virtualEntry }) - : { optionsFn: ENV_FALLBACK_OPTIONS_FN, importStmt: undefined }; - - // The TanStack Start server entry shim with a release wraps the default export of the entry it re-exports - // (`export default addReleaseMetaTag(serverEntry, release)`). That entry is wrapped already, and a second - // `withSentry` would start a second trace for each request. - const reexportsEntry = reexportsAllFromSameFile(ast, normalizedId); - - // No registration import is injected here: the orchestrion plugin's - // subscribe-injection makes each bundled package self-register its channel - // subscriber on the global marker, so wrapping the entry with `withSentry` - // is all this plugin needs to do. - const result = applyAutoInstrumentTransforms(code, ast, { - classWrappers, - agentClasses, - optionsFn, - optionsImport, - sameWorkerBindings: wranglerConfig.sameWorkerBindings, - sentryModule, - workerInfo: { name: wranglerConfig.name, compatibilityDate: wranglerConfig.compatibilityDate }, - wrapDefault: !reexportsEntry, - }); - - const wrappedClasses = result?.wrappedClasses ?? new Set(); - const missing = [...classWrappers.keys()].filter(name => !wrappedClasses.has(name)); - if (missing.length > 0 && !reexportsEntry) { - this.warn?.( - `[sentry] Could not auto-instrument ${missing.join(', ')}. ` + - 'The worker entry has no export matching them. ' + - 'Star re-exports (`export * from "./do"`) are not matched. ' + - 'Export them by name or wrap them manually with corresponding `instrument*WithSentry` helpers.', - ); - } - - return result ?? undefined; + // `this.parse` fails on raw TypeScript, which oxc parses. + const parse: ModuleParser = (source, moduleId) => { + try { + return this.parse(source); + } catch { + return parseModule(source, moduleId); + } + }; + + const output = await createCallSiteRewriter( + [ + { + name: 'cloudflare-worker-entry', + include: {}, + apply: async ({ ast, state }) => { + const classWrappers = new Map(); + for (const { className } of config.durableObjects) { + classWrappers.set(className, 'durableObject'); + } + for (const { className } of config.workflows) { + classWrappers.set(className, 'workflow'); + } + for (const className of config.workerEntrypoints) { + classWrappers.set(className, 'workerEntrypoint'); + } + + // An `agents` Agent is a Durable Object, so wrangler lists it among the DO bindings and only + // its base-class chain tells the two apart. Detection walks the module graph (base classes + // usually live in their own file), so it is limited to the configured DO classes. + // + // Only `resolve` is handed over — never `load`: awaiting `load()` from inside a transform + // hook deadlocks the build, since the module can't finish loading while this transform is + // still pending. `agentClass` reads sibling modules off disk instead. + const agentCandidates = collectAgentCandidates( + ast, + [...classWrappers].filter(([, kind]) => kind === 'durableObject').map(([name]) => name), + ); + const agentClasses = + agentCandidates.size > 0 + ? await detectAgentClasses(ast, normalizedId, agentCandidates, { + parse: code => this.parse(code), + resolve: this.resolve?.bind(this), + }) + : undefined; + + // A vinext app with `@sentry/nextjs` installed gets `withSentry` of `@sentry/nextjs/cloudflare`. + const sentryModule = + isVinext && (await resolvesNextjsCloudflare(this, normalizedId)) ? NEXTJS_CLOUDFLARE_MODULE : undefined; + + const { optionsFn, importStmt: optionsImport } = instrumentFilePath + ? // A virtual module has no directory to import from relatively. + buildOptionsImport(entryPath, instrumentFilePath, { absolute: !!virtualEntry }) + : { optionsFn: ENV_FALLBACK_OPTIONS_FN, importStmt: undefined }; + + // The TanStack Start server entry shim with a release wraps the default export of the entry it re-exports + // (`export default addReleaseMetaTag(serverEntry, release)`). That entry is wrapped already, and a second + // `withSentry` would start a second trace for each request. + const reexportsEntry = reexportsAllFromSameFile(ast, normalizedId); + + // No registration import is injected here: the orchestrion plugin's + // subscribe-injection makes each bundled package self-register its channel + // subscriber on the global marker, so wrapping the entry with `withSentry` + // is all this plugin needs to do. + const result = applyAutoInstrumentTransforms( + code, + ast, + { + classWrappers, + agentClasses, + optionsFn, + optionsImport, + sameWorkerBindings: config.sameWorkerBindings, + sentryModule, + workerInfo: { name: config.name, compatibilityDate: config.compatibilityDate }, + wrapDefault: !reexportsEntry, + }, + state, + ); + + const wrappedClasses = result?.wrappedClasses ?? new Set(); + const missing = [...classWrappers.keys()].filter(name => !wrappedClasses.has(name)); + if (missing.length > 0 && !reexportsEntry) { + this.warn?.( + `[sentry] Could not auto-instrument ${missing.join(', ')}. ` + + 'The worker entry has no export matching them. ' + + 'Star re-exports (`export * from "./do"`) are not matched. ' + + 'Export them by name or wrap them manually with corresponding `instrument*WithSentry` helpers.', + ); + } + }, + }, + ], + { parse }, + ).transform(code, normalizedId); + + return output ?? undefined; }, }; } diff --git a/packages/cloudflare/src/vite/moduleShape.ts b/packages/cloudflare/src/vite/moduleShape.ts index edb1a81c0dfb..0813f316889d 100644 --- a/packages/cloudflare/src/vite/moduleShape.ts +++ b/packages/cloudflare/src/vite/moduleShape.ts @@ -1,395 +1,7 @@ -import type { BaseNode, ProgramBody } from './transform'; - -// --------------------------------------------------------------------------- -// Minimal ESTree node shapes for structural Agent detection. -// --------------------------------------------------------------------------- - -interface IdentifierNode extends BaseNode { - name: string; -} - -interface ClassNode extends BaseNode { - id?: IdentifierNode | null; - superClass?: BaseNode | null; -} - -interface MemberExpressionNode extends BaseNode { - object?: { type: string; name?: string }; - property?: { type: string; name?: string }; -} - -interface ImportSpecifierNode { - type: string; - imported?: { type: string; name?: string }; - local?: { type: string; name?: string }; -} - -interface ImportDeclarationNode extends BaseNode { - source?: { value?: unknown }; - specifiers?: ImportSpecifierNode[]; -} - -interface ExportSpecifierNode { - type: string; - local?: { type: string; name?: string }; - exported?: { type: string; name?: string }; -} - -interface ExportNamedNode extends BaseNode { - declaration?: BaseNode | null; - source?: { value?: unknown } | null; - specifiers?: ExportSpecifierNode[]; -} - -interface ExportDefaultNode extends BaseNode { - declaration: BaseNode; -} - -interface ExportAllNode extends BaseNode { - source?: { value?: unknown }; - exported?: { type: string; name?: string } | null; -} - -/** Binding name used for a module's default export. */ -export const DEFAULT_EXPORT = 'default'; - -/** A resolved superclass reference: a bare identifier or a `ns.Member` expression. */ -export type SuperRef = { kind: 'identifier'; name: string } | { kind: 'member'; object: string; property: string }; - -/** The declarations of a single module that binding resolution needs. */ -export interface ModuleShape { - /** Top-level class names → their superclass reference (absent when the class has no `extends`). */ - classes: Map; - /** Local binding name → the import it came from (`imported` is `default` for a default import). */ - imports: Map; - /** Local binding name → module specifier, for `import * as ns from '...'`. */ - namespaces: Map; - /** Exported name → the re-export it came from, for `export { x as y } from '...'`. */ - reexports: Map; - /** Exported name → local binding name, for `export { x as y }` without a source. */ - localExports: Map; - /** Module specifiers of bare `export * from '...'` declarations. */ - starExports: string[]; - /** `export default ` — the local name it refers to. */ - defaultExportName?: string; - /** True when the module's default export is a class declaration/expression. */ - defaultExportIsClass?: boolean; - /** Superclass of an anonymous `export default class extends X`. */ - defaultExportSuper?: SuperRef; -} - -function emptyShape(): ModuleShape { - return { - classes: new Map(), - imports: new Map(), - namespaces: new Map(), - reexports: new Map(), - localExports: new Map(), - starExports: [], - }; -} - -// --------------------------------------------------------------------------- -// Shape from a parsed AST (used for the entry module) -// --------------------------------------------------------------------------- - -/** Collect the shape of a module from its parsed AST — used for the already-parsed entry module. */ -export function shapeFromAst(ast: ProgramBody): ModuleShape { - const shape = emptyShape(); - - for (const node of ast.body) { - switch (node.type) { - case 'ClassDeclaration': - addAstClass(shape, node); - break; - case 'ImportDeclaration': - addAstImports(shape, node); - break; - case 'ExportNamedDeclaration': - addAstNamedExport(shape, node); - break; - case 'ExportDefaultDeclaration': { - const decl = (node as ExportDefaultNode).declaration; - if (decl.type === 'ClassDeclaration' || decl.type === 'ClassExpression') { - shape.defaultExportIsClass = true; - shape.defaultExportSuper = superRefFromNode((decl as ClassNode).superClass); - // `export default class Foo {}` also binds `Foo` locally. - addAstClass(shape, decl); - } else if (decl.type === 'Identifier') { - shape.defaultExportName = (decl as IdentifierNode).name; - } - break; - } - case 'ExportAllDeclaration': { - const starNode = node as ExportAllNode; - // `export * as ns from '...'` binds a namespace object, not the individual exports. - const source = starNode.exported ? undefined : asString(starNode.source?.value); - if (source) shape.starExports.push(source); - break; - } - } - } - - return shape; -} - -function superRefFromNode(superClass: BaseNode | null | undefined): SuperRef | undefined { - if (!superClass) return undefined; - - if (superClass.type === 'Identifier') { - return { kind: 'identifier', name: (superClass as IdentifierNode).name }; - } - - if (superClass.type === 'MemberExpression') { - const member = superClass as MemberExpressionNode; - const object = member.object?.type === 'Identifier' ? member.object.name : undefined; - const property = member.property?.name; - if (object && property) return { kind: 'member', object, property }; - } - - return undefined; -} - -function addAstClass(shape: ModuleShape, classNode: ClassNode): void { - if (classNode.id?.name) shape.classes.set(classNode.id.name, superRefFromNode(classNode.superClass)); -} - -function addAstImports(shape: ModuleShape, node: ImportDeclarationNode): void { - const source = asString(node.source?.value); - if (!source) return; - - for (const specifier of node.specifiers ?? []) { - const local = specifier.local?.name; - if (!local) continue; - - if (specifier.type === 'ImportSpecifier' && specifier.imported?.name) { - shape.imports.set(local, { source, imported: specifier.imported.name }); - } else if (specifier.type === 'ImportDefaultSpecifier') { - shape.imports.set(local, { source, imported: DEFAULT_EXPORT }); - } else if (specifier.type === 'ImportNamespaceSpecifier') { - shape.namespaces.set(local, source); - } - } -} - -function addAstNamedExport(shape: ModuleShape, node: ExportNamedNode): void { - if (node.declaration?.type === 'ClassDeclaration') { - addAstClass(shape, node.declaration); - return; - } - - const source = asString(node.source?.value); - for (const specifier of node.specifiers ?? []) { - const exported = specifier.exported?.name; - const local = specifier.local?.name; - if (!exported || !local) continue; - - if (source) { - shape.reexports.set(exported, { source, imported: local }); - } else { - shape.localExports.set(exported, local); - } - } -} - -// --------------------------------------------------------------------------- -// Shape from raw source (used for sibling modules read off disk) -// --------------------------------------------------------------------------- - -/** - * Extract the module shape from **unprocessed source**. - * - * Sibling modules are read straight from disk (the plugin context's `load()` would deadlock inside a - * transform hook), so they may still be TypeScript — which no JS parser will accept. Only - * import/export statements and `class X extends Y` headers matter here, and those are - * declaration-level syntax a scan can pick out reliably; class bodies, type annotations and generics - * are irrelevant and simply skipped. - */ -export function shapeFromSource(rawCode: string): ModuleShape { - const code = stripComments(rawCode); - const shape = emptyShape(); - - // `class X extends Y {` / `class X extends Y {`, optionally exported and/or abstract. - const CLASS_RE = /\b(?:export\s+(?:default\s+)?)?(?:abstract\s+)?class\s+([A-Za-z_$][\w$]*)([^{]*)\{/g; - for (const match of code.matchAll(CLASS_RE)) { - // oxlint-disable-next-line typescript/no-non-null-assertion -- mandatory capture group - const className = match[1]!; - const isDefault = /\bexport\s+default\b/.test(match[0]); - const superRef = superRefFromHeader(match[2] ?? ''); - - shape.classes.set(className, superRef); - if (isDefault) { - shape.defaultExportIsClass = true; - shape.defaultExportSuper = superRef; - } - } - - // `export default Identifier;` - const defaultExprMatch = /\bexport\s+default\s+([A-Za-z_$][\w$]*)\s*;/.exec(code); - if (defaultExprMatch && !shape.defaultExportIsClass) { - shape.defaultExportName = defaultExprMatch[1]; - } - - // `export * from '...'` (but not `export * as ns from '...'`). - for (const match of code.matchAll(/\bexport\s*\*\s*from\s*['"]([^'"]+)['"]/g)) { - if (match[1]) shape.starExports.push(match[1]); - } - - // `export { a, b as c } from '...'` and `export { a, b as c }`. - for (const match of code.matchAll(/\bexport\s*\{([^}]*)\}\s*(?:from\s*['"]([^'"]+)['"])?/g)) { - const source = match[2]; - for (const { imported, local } of parseSpecifierList(match[1] ?? '')) { - // In an export clause the first name is local and the alias is the exported name. - if (source) { - shape.reexports.set(local, { source, imported }); - } else { - shape.localExports.set(local, imported); - } - } - } - - // `import Default, { a as b }, * as ns from '...'` in its various shapes. - for (const match of code.matchAll(/\bimport\s+([^'";]+?)\s+from\s*['"]([^'"]+)['"]/g)) { - // oxlint-disable-next-line typescript/no-non-null-assertion -- mandatory capture group - addSourceImports(shape, match[1] ?? '', match[2]!); - } - - return shape; -} - -/** Pull the superclass out of the text between a class name and its body. */ -function superRefFromHeader(header: string): SuperRef | undefined { - // The header still carries the class's own generic parameter list (``), whose - // constraint `extends` would otherwise be mistaken for the superclass clause. Strip a leading - // balanced `<...>` first, then read the (possibly dotted) base name. Trailing generic args on the - // base (`extends Agent`) stop the match naturally. - const withoutParams = stripLeadingGenerics(header); - const match = /\bextends\s+([A-Za-z_$][\w$]*)\s*(?:\.\s*([A-Za-z_$][\w$]*))?/.exec(withoutParams); - if (!match) return undefined; - - // oxlint-disable-next-line typescript/no-non-null-assertion -- mandatory capture group - return match[2] ? { kind: 'member', object: match[1]!, property: match[2] } : { kind: 'identifier', name: match[1]! }; -} - -/** - * Remove a leading `<...>` generic parameter list, honoring nesting (`>`). - * Anything after the balanced close — the superclass clause — is returned unchanged. When the - * header doesn't start with `<` (no generics), it is returned as-is. - */ -function stripLeadingGenerics(header: string): string { - const start = header.indexOf('<'); - // Only treat it as a parameter list when `<` is the first meaningful token — a `<` appearing - // later is part of the superclass's own generic args and must be left alone. - if (start === -1 || header.slice(0, start).trim() !== '') return header; - - let depth = 0; - for (let i = start; i < header.length; i++) { - const char = header[i]; - if (char === '<') depth++; - else if (char === '>') { - depth--; - if (depth === 0) return header.slice(i + 1); - } - } - // Unbalanced `<` — fall back to the untouched header rather than dropping the superclass. - return header; -} - -/** Parse `a, b as c` into `{ imported: 'b', local: 'c' }` pairs (type-only specifiers dropped). */ -function parseSpecifierList(clause: string): Array<{ imported: string; local: string }> { - const specifiers: Array<{ imported: string; local: string }> = []; - - for (const rawPart of clause.split(',')) { - const part = rawPart.trim().replace(/^type\s+/, ''); - if (!part) continue; - - const aliased = /^([A-Za-z_$][\w$]*)\s+as\s+([A-Za-z_$][\w$]*)$/.exec(part); - if (aliased) { - // oxlint-disable-next-line typescript/no-non-null-assertion -- mandatory capture groups - specifiers.push({ imported: aliased[1]!, local: aliased[2]! }); - } else if (/^[A-Za-z_$][\w$]*$/.test(part)) { - specifiers.push({ imported: part, local: part }); - } - } - - return specifiers; -} - -function addSourceImports(shape: ModuleShape, clause: string, source: string): void { - // Type-only imports never contribute a runtime base class. - if (/^type\s/.test(clause.trim())) return; - - const namespaceMatch = /\*\s*as\s+([A-Za-z_$][\w$]*)/.exec(clause); - if (namespaceMatch) { - // oxlint-disable-next-line typescript/no-non-null-assertion -- mandatory capture group - shape.namespaces.set(namespaceMatch[1]!, source); - } - - const bracesMatch = /\{([^}]*)\}/.exec(clause); - if (bracesMatch) { - for (const { imported, local } of parseSpecifierList(bracesMatch[1] ?? '')) { - shape.imports.set(local, { source, imported }); - } - } - - // A leading bare identifier (before any brace/star) is the default import. - const defaultMatch = /^\s*([A-Za-z_$][\w$]*)\s*(?:,|$)/.exec(clause); - if (defaultMatch) { - // oxlint-disable-next-line typescript/no-non-null-assertion -- mandatory capture group - shape.imports.set(defaultMatch[1]!, { source, imported: DEFAULT_EXPORT }); - } -} - -/** Remove line and block comments, leaving string literals (module specifiers) intact. */ -function stripComments(code: string): string { - let result = ''; - let index = 0; - - while (index < code.length) { - const char = code.charAt(index); - const next = code[index + 1]; - - if (char === '/' && next === '/') { - while (index < code.length && code[index] !== '\n') index++; - continue; - } - - if (char === '/' && next === '*') { - index += 2; - while (index < code.length && !(code[index] === '*' && code[index + 1] === '/')) index++; - index += 2; - // Keep a separator so `*/class` doesn't fuse into one token. - result += ' '; - continue; - } - - if (char === '"' || char === "'" || char === '`') { - const quote = char; - result += char; - index++; - while (index < code.length) { - const inner = code.charAt(index); - result += inner; - index++; - if (inner === '\\') { - if (index < code.length) { - result += code.charAt(index); - index++; - } - continue; - } - if (inner === quote) break; - } - continue; - } - - result += char; - index++; - } - - return result; -} - -function asString(value: unknown): string | undefined { - return typeof value === 'string' && value ? value : undefined; -} +export { + DEFAULT_EXPORT, + type ModuleShape, + shapeFromAst, + shapeFromSource, + type SuperRef, +} from '@sentry/bundler-plugins/rewriter'; diff --git a/packages/cloudflare/src/vite/transform.ts b/packages/cloudflare/src/vite/transform.ts index 50df26a4b5a9..181e29f3d9ee 100644 --- a/packages/cloudflare/src/vite/transform.ts +++ b/packages/cloudflare/src/vite/transform.ts @@ -1,84 +1,38 @@ -/* eslint-disable max-lines */ -import MagicString from 'magic-string'; +import { + type BaseNode, + type ClassDeclarationNode, + collectDeclaringStatements, + collectManuallyWrappedLocals, + collectTopLevelClasses, + createRewriteState, + type ExportDefaultNode, + type ExportNamedNode, + type ExportSpecifierNode, + isCallToMethod, + type ProgramBody, + type RewriteState, + type VariableDeclarationNode, + wrapDefaultExport, + wrapDefaultReexport, + wrapDefaultSpecifier, + wrapForeignExport, + wrapInlineExport, + wrapLocalBinding, + wrapSpecifierExports, + type WrapExpression, +} from '@sentry/bundler-plugins/rewriter'; +import type MagicString from 'magic-string'; import { DEFAULT_EXPORT, type ExportName, type SameWorkerBinding } from './wranglerConfig'; import { detectWorkerEntrypointClasses } from './workerEntrypoint'; import { stringifyForCodeInjection } from '@sentry/core'; +export type { BaseNode, ProgramBody }; + const MERGED_OPTIONS_IDENTIFIER = '__SENTRY_OPTIONS__'; // Read by `CloudflareClient` for the default `serverName` and the runtime version. const WORKER_INFO_GLOBAL = '__SENTRY_CLOUDFLARE_WORKER__'; -// --------------------------------------------------------------------------- -// Minimal ESTree node types for the AST nodes we inspect. -// --------------------------------------------------------------------------- - -export interface BaseNode { - type: string; - start: number; - end: number; -} - -export interface ProgramBody { - body: BaseNode[]; -} - -interface IdentifierNode extends BaseNode { - name: string; -} - -interface CalleeNode { - type: string; - name?: string; - property?: { type: string; name?: string }; -} - -interface CallExpressionNode extends BaseNode { - callee?: CalleeNode; -} - -interface ClassDeclarationNode extends BaseNode { - id?: IdentifierNode | null; -} - -interface ExportDefaultNode extends BaseNode { - declaration: BaseNode; -} - -interface ExportSpecifierNode extends BaseNode { - local?: { type: string; name?: string }; - exported?: { type: string; name?: string }; -} - -interface ExportNamedNode extends BaseNode { - declaration?: BaseNode | null; - source?: BaseNode | null; - specifiers?: ExportSpecifierNode[]; -} - -interface VariableDeclaratorNode { - id?: { type: string; name?: string }; - init?: BaseNode | null; -} - -interface VariableDeclarationNode extends BaseNode { - declarations?: VariableDeclaratorNode[]; -} - -interface ImportDeclarationNode extends BaseNode { - specifiers?: Array<{ local?: { type: string; name?: string } }>; -} - -function isCallToMethod(node: BaseNode, methodName: string): boolean { - if (node.type !== 'CallExpression') return false; - const callee = (node as CallExpressionNode).callee; - if (!callee) return false; - if (callee.type === 'Identifier' && callee.name === methodName) return true; - return ( - callee.type === 'MemberExpression' && callee.property?.type === 'Identifier' && callee.property.name === methodName - ); -} - /** * The kind of Sentry wrapper to apply to an exported class. * @@ -173,23 +127,21 @@ export function applyAutoInstrumentTransforms( code: string, ast: ProgramBody, ctx: TransformContext, + rewrite: RewriteState = createRewriteState(code), ): TransformResult | undefined { - const ms = new MagicString(code); - const topLevelClasses = collectTopLevelClasses(ast); + const { ms } = rewrite; const sameWorkerBindings = ctx.sameWorkerBindings ?? []; const state: TransformState = { - ms, - needsImport: false, + rewrite, wrappedClasses: new Set(), - topLevelClasses, - wrappedLocals: new Map(), + topLevelClasses: collectTopLevelClasses(ast), classWrappers: ctx.classWrappers, agentClasses: ctx.agentClasses ?? new Set(), workerEntrypointClasses: detectWorkerEntrypointClasses(ast), // The identifier must be chosen before wrapping, which bindings survive is only known after. optionsFn: sameWorkerBindings.length > 0 ? MERGED_OPTIONS_IDENTIFIER : ctx.optionsFn, autoWrapped: new Set(), - manuallyWrappedLocals: collectManuallyWrappedLocals(ast), + manuallyWrappedLocals: collectManuallyWrappedLocals(ast, Object.values(WRAPPER_METHODS)), declaringStatements: collectDeclaringStatements(ast), }; const { wrappedClasses } = state; @@ -206,12 +158,12 @@ export function applyAutoInstrumentTransforms( if (ctx.wrapDefault !== false) { for (const node of ast.body) { if (node.type === 'ExportDefaultDeclaration') { - wrapDefaultExport(node as ExportDefaultNode, ctx, state); + handleDefaultExport(node as ExportDefaultNode, state); } } } - if (state.needsImport) { + if (rewrite.needsImport) { // `prepend` inserts before earlier prepends, yielding: Sentry import, options import, declaration. if (sameWorkerBindings.length > 0) { ms.prepend(buildMergedOptionsDeclaration(sameWorkerBindings, ctx.optionsFn, state)); @@ -222,7 +174,7 @@ export function applyAutoInstrumentTransforms( if (ctx.workerInfo?.name || ctx.workerInfo?.compatibilityDate) { ms.prepend(`globalThis.${WORKER_INFO_GLOBAL} = ${JSON.stringify(ctx.workerInfo)};\n`); - } else if (!state.needsImport && wrappedClasses.size === 0) { + } else if (!rewrite.needsImport && wrappedClasses.size === 0) { // Nothing was rewritten. Classes found already wrapped manually are still // reported (via `wrappedClasses`) so the caller doesn't warn about them. return undefined; @@ -236,19 +188,13 @@ export function applyAutoInstrumentTransforms( } interface TransformState { - ms: MagicString; - needsImport: boolean; + rewrite: RewriteState; wrappedClasses: Set; /** * Top-level class declarations, exported or not, so specifier exports like * `export { MyDO }` can locate the class they refer to. */ topLevelClasses: Map; - /** - * Local class name → the binding holding its wrapper, so two exports of the same class share one - * wrapper and a default export of it can be re-pointed. - */ - wrappedLocals: Map; /** Class name → wrapper kind, keyed by the *exported* name (from config). */ classWrappers: Map; /** Local class names detected as `agents` Agents (see {@link TransformContext.agentClasses}). */ @@ -338,145 +284,29 @@ function resolveWrapperKind( return undefined; } -/** - * Top-level `const X = instrument*WithSentry(...)` bindings — a hand-wrapped class that is exported - * separately (`export { X }`) rather than inline. - */ -function collectManuallyWrappedLocals(ast: ProgramBody): Set { - const wrapperMethods = Object.values(WRAPPER_METHODS); - const locals = new Set(); - - for (const node of ast.body) { - const declaration = declarationOf(node); - if (declaration?.type !== 'VariableDeclaration') continue; - for (const declarator of (declaration as VariableDeclarationNode).declarations ?? []) { - const name = declarator.id?.type === 'Identifier' ? declarator.id.name : undefined; - const init = declarator.init; - if (name && init && wrapperMethods.some(method => isCallToMethod(init, method))) { - locals.add(name); - } - } - } - - return locals; -} - -function collectDeclaringStatements(ast: ProgramBody): Map { - const statements = new Map(); - for (const node of ast.body) { - const declaration = declarationOf(node); - if (!declaration) continue; - const ids = - declaration.type === 'VariableDeclaration' - ? ((declaration as VariableDeclarationNode).declarations ?? []).map(declarator => declarator.id) - : declaration.type === 'ImportDeclaration' - ? ((declaration as ImportDeclarationNode).specifiers ?? []).map(specifier => specifier.local) - : [(declaration as ClassDeclarationNode).id]; - for (const id of ids) { - if (id?.type === 'Identifier' && id.name) statements.set(id.name, node); - } - } - return statements; -} - -function collectTopLevelClasses(ast: ProgramBody): Map { - const classes = new Map(); - for (const node of ast.body) { - const declaration = declarationOf(node); - if (declaration?.type !== 'ClassDeclaration') continue; - const classNode = declaration as ClassDeclarationNode; - if (classNode.id?.name) classes.set(classNode.id.name, classNode); - } - return classes; +/** The `__SENTRY__.(options, target)` call for a wrapper kind. */ +function wrapWith(kind: ClassWrapperKind, state: TransformState): WrapExpression { + return target => `__SENTRY__.${WRAPPER_METHODS[kind]}(${state.optionsFn}, ${target})`; } -/** The declaration a top-level statement makes, looking through `export` (`export const x = ...`). */ -function declarationOf(node: BaseNode): BaseNode | null | undefined { - return node.type === 'ExportNamedDeclaration' ? (node as ExportNamedNode).declaration : node; +/** + * Like {@link wrapWith}, for a target from another module. The target may already be wrapped in its + * own module, which this transform cannot see, so the emitted guard returns such a target as-is + * instead of nesting a second wrapper around it. + */ +function guardedWrapWith(kind: ClassWrapperKind, state: TransformState): WrapExpression { + return target => + `__SENTRY__._INTERNAL_wrapUnlessInstrumented(__SENTRY__.${WRAPPER_METHODS[kind]}, ${state.optionsFn}, ${target})`; } -function wrapDefaultExport(node: ExportDefaultNode, ctx: TransformContext, state: TransformState): void { - const decl = node.declaration; - +function handleDefaultExport(node: ExportDefaultNode, state: TransformState): void { // Already wrapped — leave it alone - if (isCallToMethod(decl, 'withSentry')) return; - - // `export default Foo` where `Foo` is a local class already wrapped by a named - // export (e.g. a self-bound WorkerEntrypoint also used as the default handler). - // Wrapping again would produce `withSentry(withSentry(...))`, so the default - // export is re-pointed at the wrapper binding the named export created. - if (decl.type === 'Identifier') { - const wrappedName = state.wrappedLocals.get((decl as IdentifierNode).name); - if (wrappedName) { - state.ms.overwrite(decl.start, decl.end, wrappedName); - state.autoWrapped.add(DEFAULT_EXPORT); - return; - } - } - - // MagicString positions are always relative to the original source. Only the `export default` - // keywords are replaced, so parentheses around the expression stay. - const source = state.ms.original; - const keywordsEnd = exportDefaultKeywordsEnd(source, node.start); - const declaredName = - decl.type === 'ClassDeclaration' || decl.type === 'FunctionDeclaration' - ? (decl as ClassDeclarationNode).id?.name - : undefined; + if (isCallToMethod(node.declaration, 'withSentry')) return; - // As with `export { handler as default }`, the export is set in two steps: bound as-is where the - // original statement set it, then rebound at the end of the module to the wrapper, which sees - // methods added in between. See `wrapDefaultSpecifier`. - let wrapped = '__SENTRY_DEFAULT_EXPORT__'; - if (declaredName) { - // `export default class Handler {}`: the declaration stays, so `Handler` stays bound in the module. - state.ms.remove(node.start, decl.start); - state.ms.appendLeft(node.end, `\nvar __SENTRY_DEFAULT_EXPORT__ = ${declaredName};`); - wrapped = declaredName; - } else if (isAnonymousFunctionOrClass(decl)) { - // As a property value, the class or function gets the name `default`, as `export default` gives it. - const hasSemicolon = source[node.end - 1] === ';'; - state.ms.overwrite(node.start, keywordsEnd, 'var __SENTRY_DEFAULT_EXPORT__ = { default:'); - state.ms.appendLeft(hasSemicolon ? node.end - 1 : node.end, hasSemicolon ? ' }.default' : ' }.default;'); - } else { - state.ms.overwrite(node.start, keywordsEnd, 'var __SENTRY_DEFAULT_EXPORT__ ='); - } - state.ms.appendLeft(node.end, '\nexport { __SENTRY_DEFAULT_EXPORT__ as default };'); - state.ms.append(`\n__SENTRY_DEFAULT_EXPORT__ = __SENTRY__.withSentry(${state.optionsFn}, ${wrapped});`); - state.needsImport = true; + wrapDefaultExport(state.rewrite, node, wrapWith('workerEntrypoint', state)); state.autoWrapped.add(DEFAULT_EXPORT); } -/** - * Offset just past the `default` keyword of the `export default` statement at `start`. Comments can - * sit between `export`, `default` and the expression, and may themselves contain the word `default`. - */ -function exportDefaultKeywordsEnd(source: string, start: number): number { - let index = start + 'export'.length; - while (index < source.length && !source.startsWith('default', index)) { - if (source.startsWith('//', index)) { - const lineEnd = source.indexOf('\n', index); - index = lineEnd === -1 ? source.length : lineEnd; - } else if (source.startsWith('/*', index)) { - const commentEnd = source.indexOf('*/', index + 2); - index = commentEnd === -1 ? source.length : commentEnd + 2; - } else { - index++; - } - } - return index + 'default'.length; -} - -function isAnonymousFunctionOrClass(node: BaseNode): boolean { - if (node.type === 'ArrowFunctionExpression') return true; - const isFunctionOrClass = [ - 'FunctionExpression', - 'FunctionDeclaration', - 'ClassExpression', - 'ClassDeclaration', - ].includes(node.type); - return isFunctionOrClass && !(node as ClassDeclarationNode).id; -} - function handleNamedExport(node: ExportNamedNode, ctx: TransformContext, state: TransformState): void { const decl = node.declaration; @@ -490,12 +320,14 @@ function handleNamedExport(node: ExportNamedNode, ctx: TransformContext, state: // ---- Named class export matching a configured binding ---- if (decl?.type === 'ClassDeclaration') { - wrapInlineClassExport(node, decl, ctx, state); + wrapInlineClassExport(node, decl, state); return; } // ---- Specifier export (`export { Foo as MyDO }`, `export { MyDO } from './do'`) ---- - wrapSpecifierExports(node, ctx, state); + wrapSpecifierExports(state.rewrite, node, (specifier, sourceLiteral, prelude) => + wrapSpecifier(specifier, sourceLiteral, state, prelude), + ); } function collectManuallyWrappedClassExports( @@ -504,7 +336,7 @@ function collectManuallyWrappedClassExports( state: TransformState, ): void { for (const declarator of varDecl.declarations ?? []) { - const name = declarator.id?.type === 'Identifier' ? declarator.id.name : undefined; + const name = declarator.id?.type === 'Identifier' ? (declarator.id as { name?: string }).name : undefined; const kind = name ? ctx.classWrappers.get(name) : undefined; if (!name || !kind || !declarator.init) continue; @@ -519,10 +351,17 @@ function collectManuallyWrappedClassExports( } } +/** + * The class declaration is never renamed (`class __SENTRY_ORIGINAL_MyAgent__`), because that would + * also rename what the class reports as `Function.prototype.name`, which libraries read to identify + * the user's class: `@cloudflare/think` hands `this.constructor.name` to the AI SDK as the telemetry + * `functionId`, and that surfaced as a `gen_ai.invoke_agent __SENTRY_ORIGINAL_MyAgent__` span. + * The wrapper gets its own binding instead, the same shape as the documented manual + * `instrument*WithSentry` pattern. + */ function wrapInlineClassExport( exportNode: ExportNamedNode, classDecl: ClassDeclarationNode, - ctx: TransformContext, state: TransformState, ): void { const classId = classDecl.id; @@ -531,144 +370,12 @@ function wrapInlineClassExport( if (!classId || !kind) return; const className = classId.name; - - // Strip the `export ` keyword - state.ms.overwrite(exportNode.start, classDecl.start, ''); - - const wrappedName = wrapLocalClass(className, classDecl, kind, state); - state.ms.appendLeft(exportNode.end, `export { ${wrappedName} as ${className} };\n`); + wrapInlineExport(state.rewrite, exportNode, className, wrapWith(kind, state)); state.wrappedClasses.add(className); state.autoWrapped.add(className); } -/** - * Wrap a class declared in this module and return the binding that holds the wrapper. - * - * The declaration is left exactly as written. Only the *export* has to become the wrapper, so the - * wrapper gets its own binding and the export is aliased to it, the same shape as the documented - * manual `instrument*WithSentry` pattern and the cross-module re-export path below. Renaming the - * declaration instead (`class __SENTRY_ORIGINAL_MyAgent__`) would also rename what the class reports - * as `Function.prototype.name`, which libraries read to identify the user's class: `@cloudflare/think` - * hands `this.constructor.name` to the AI SDK as the telemetry `functionId`, and that surfaced as a - * `gen_ai.invoke_agent __SENTRY_ORIGINAL_MyAgent__` span. - */ -function wrapLocalClass( - localName: string, - localClass: ClassDeclarationNode, - kind: ClassWrapperKind, - state: TransformState, -): string { - const existing = state.wrappedLocals.get(localName); - if (existing) return existing; - - const wrappedName = `__SENTRY_WRAPPED_${localName}__`; - state.wrappedLocals.set(localName, wrappedName); - state.ms.appendLeft( - localClass.end, - `\nconst ${wrappedName} = __SENTRY__.${WRAPPER_METHODS[kind]}(${state.optionsFn}, ${localName});\n`, - ); - state.needsImport = true; - return wrappedName; -} - -/** - * Wrap the configured classes an `export { ... }` statement names. - * - * Each such specifier is re-pointed at a binding holding the wrapper, which means rebuilding the - * statement; specifiers this plugin has no business touching are carried over verbatim. For a class - * declared in this module the wrapper binding follows the declaration (see {@link wrapLocalClass}). - * A class that lives in **another** module — imported and re-exported, or re-exported directly — is - * first bound under a private name, since an import binding cannot be reassigned and the `from` form - * has no local binding at all. - */ -function wrapSpecifierExports(node: ExportNamedNode, ctx: TransformContext, state: TransformState): void { - const specifiers = node.specifiers ?? []; - if (specifiers.length === 0) return; - - const sourceLiteral = node.source ? state.ms.original.slice(node.source.start, node.source.end) : undefined; - - const prelude: string[] = []; - const wrappedPairs: string[] = []; - const kept: string[] = []; - - for (const specifier of specifiers) { - const pair = wrapSpecifier(specifier, sourceLiteral, ctx, state, prelude); - if (pair) { - wrappedPairs.push(pair); - } else { - kept.push(state.ms.original.slice(specifier.start, specifier.end)); - } - } - - if (wrappedPairs.length === 0) return; - - const statements = [...prelude, `export { ${wrappedPairs.join(', ')} };`]; - if (kept.length > 0) { - const clause = `export { ${kept.join(', ')} }`; - statements.push(sourceLiteral ? `${clause} from ${sourceLiteral};` : `${clause};`); - } - state.ms.overwrite(node.start, node.end, statements.join('\n')); -} - -/** - * `export { handler as default }`, the form bundlers emit for a default export. The export is set - * in two steps. Right after `handler` is declared, it is bound to `handler` as-is, so a circular - * import that reads it during module evaluation gets the handler, as before the transform. At the - * end of the module, it is rebound to the wrapper, so a handler assigned or given methods later is - * wrapped as it ends up. The binding is a `var`: a read before `handler` is declared gets - * `undefined`, as it would from the bundler's own `var`, where a `const` would throw and stop the - * Worker from starting. - */ -function wrapDefaultSpecifier(localName: string, state: TransformState): string | undefined { - if (state.manuallyWrappedLocals.has(localName)) return undefined; - - // Same as `export default Foo`: re-point at the wrapper a named export already made. - const wrappedName = state.wrappedLocals.get(localName); - if (wrappedName) { - state.autoWrapped.add(DEFAULT_EXPORT); - return `${wrappedName} as default`; - } - - const declaringStatement = state.declaringStatements.get(localName); - if (declaringStatement) { - state.ms.appendLeft(declaringStatement.end, `\nvar __SENTRY_DEFAULT_EXPORT__ = ${localName};`); - } - state.ms.append( - `\n${declaringStatement ? '' : 'var '}__SENTRY_DEFAULT_EXPORT__ = __SENTRY__.withSentry(${state.optionsFn}, ${localName});`, - ); - state.needsImport = true; - state.autoWrapped.add(DEFAULT_EXPORT); - return '__SENTRY_DEFAULT_EXPORT__ as default'; -} - -/** - * `export { default } from './handler'`. The handler may already be wrapped in its own module, - * which this transform cannot see, so the emitted guard returns such a handler as-is. - * - * The original re-export is a live binding to the handler module's export, but the wrapper is not - * set until this module's body runs. A circular import that reads the default export before then - * gets `undefined` instead of the handler. The binding is a `var` so that the read does not throw, - * as a `const` would, and stop the Worker from starting. See `wrapDefaultSpecifier`. - */ -function wrapDefaultReexport( - localName: string, - sourceLiteral: string, - state: TransformState, - prelude: string[], -): string { - const target = '__SENTRY_REEXPORT_default__'; - prelude.push( - localName === DEFAULT_IMPORT - ? `import ${target} from ${sourceLiteral};` - : `import { ${localName} as ${target} } from ${sourceLiteral};`, - `var __SENTRY_DEFAULT_EXPORT__ = __SENTRY__._INTERNAL_wrapUnlessInstrumented(__SENTRY__.withSentry, ${state.optionsFn}, ${target});`, - ); - state.needsImport = true; - state.autoWrapped.add(DEFAULT_EXPORT); - return '__SENTRY_DEFAULT_EXPORT__ as default'; -} - /** * Handle one export specifier, returning the `Wrapped as Exported` pair to emit for a class that * gets wrapped. The import/wrapper statements a cross-module pair depends on are pushed onto @@ -680,7 +387,6 @@ function wrapDefaultReexport( function wrapSpecifier( specifier: ExportSpecifierNode, sourceLiteral: string | undefined, - ctx: TransformContext, state: TransformState, prelude: string[], ): string | undefined { @@ -697,9 +403,26 @@ function wrapSpecifier( if (!exportedName || !localName) return undefined; if (!kind) { if (exportedName !== DEFAULT_IMPORT) return undefined; - return sourceLiteral - ? wrapDefaultReexport(localName, sourceLiteral, state, prelude) - : wrapDefaultSpecifier(localName, state); + if (sourceLiteral) { + const pair = wrapDefaultReexport( + state.rewrite, + localName, + sourceLiteral, + prelude, + guardedWrapWith('workerEntrypoint', state), + ); + state.autoWrapped.add(DEFAULT_EXPORT); + return pair; + } + if (state.manuallyWrappedLocals.has(localName)) return undefined; + const pair = wrapDefaultSpecifier( + state.rewrite, + localName, + state.declaringStatements.get(localName), + wrapWith('workerEntrypoint', state), + ); + state.autoWrapped.add(DEFAULT_EXPORT); + return pair; } // Without a `from` clause the specifier points at a module-local binding. @@ -707,7 +430,7 @@ function wrapSpecifier( const localClass = state.topLevelClasses.get(localName); if (localClass?.id) { - const wrappedName = wrapLocalClass(localName, localClass, kind, state); + const wrappedName = wrapLocalBinding(state.rewrite, localName, localClass, wrapWith(kind, state)); state.wrappedClasses.add(exportedName); return `${wrappedName} as ${exportedName}`; } @@ -720,27 +443,15 @@ function wrapSpecifier( // The class comes from another module: bind it under a private name (for the `from` form, which // has no local binding at all), wrap that, and export the wrapper under the configured name. - let target = localName; - - if (sourceLiteral) { - target = `__SENTRY_REEXPORT_${exportedName}__`; - prelude.push( - localName === DEFAULT_IMPORT - ? `import ${target} from ${sourceLiteral};` - : `import { ${localName} as ${target} } from ${sourceLiteral};`, - ); - } - - const wrappedName = `__SENTRY_WRAPPED_${exportedName}__`; - - // The class may already be hand-wrapped in its own module, which this transform cannot see. The - // emitted guard returns such a class as-is instead of nesting a second wrapper around it. - prelude.push( - `const ${wrappedName} = __SENTRY__._INTERNAL_wrapUnlessInstrumented(__SENTRY__.${WRAPPER_METHODS[kind]}, ${state.optionsFn}, ${target});`, + const pair = wrapForeignExport( + state.rewrite, + localName, + exportedName, + sourceLiteral, + prelude, + guardedWrapWith(kind, state), ); state.wrappedClasses.add(exportedName); state.autoWrapped.add(exportedName); - state.needsImport = true; - - return `${wrappedName} as ${exportedName}`; + return pair; } diff --git a/packages/cloudflare/src/vite/workerEntrypoint.ts b/packages/cloudflare/src/vite/workerEntrypoint.ts index 35433f46b46d..47ccb4eff423 100644 --- a/packages/cloudflare/src/vite/workerEntrypoint.ts +++ b/packages/cloudflare/src/vite/workerEntrypoint.ts @@ -1,141 +1,12 @@ -import type { BaseNode, ProgramBody } from './transform'; - -// --------------------------------------------------------------------------- -// Minimal ESTree node shapes for structural WorkerEntrypoint detection. -// --------------------------------------------------------------------------- - -interface IdentifierNode extends BaseNode { - name: string; -} - -interface MemberExpressionNode extends BaseNode { - object?: { type: string; name?: string }; - property?: { type: string; name?: string }; -} - -interface ClassDeclarationNode extends BaseNode { - id?: IdentifierNode | null; - superClass?: BaseNode | null; -} - -interface ExportNamedDeclNode extends BaseNode { - declaration?: BaseNode | null; -} - -interface ImportSpecifierNode { - type: string; - imported?: { type: string; name?: string }; - local?: { type: string; name?: string }; -} - -interface ImportDeclarationNode extends BaseNode { - source?: { value?: unknown }; - specifiers?: ImportSpecifierNode[]; -} - -interface WorkerEntrypointBases { - /** Local identifiers bound to the named `WorkerEntrypoint` import. */ - named: Set; - /** Local identifiers bound to a `* as ns` import of `cloudflare:workers`. */ - namespaces: Set; -} +import { findClassesExtending, type ProgramBody } from '@sentry/bundler-plugins/rewriter'; /** * Find top-level classes that (transitively, within this module) extend - * `WorkerEntrypoint` imported from `cloudflare:workers`. esbuild has already - * stripped TypeScript by transform time, so a superclass is a plain identifier - * (`extends WorkerEntrypoint`) or member access (`extends cf.WorkerEntrypoint`). + * `WorkerEntrypoint` imported from `cloudflare:workers`. * * Only same-file base chains are resolvable here; a base class imported from * another module is invisible and relies on the config self-binding fallback. */ export function detectWorkerEntrypointClasses(ast: ProgramBody): Set { - const bases = collectWorkerEntrypointImports(ast); - if (bases.named.size === 0 && bases.namespaces.size === 0) { - return new Set(); - } - - // Every top-level class, including the `export class Foo {}` form (where the - // class is nested inside an ExportNamedDeclaration) so directly-exported - // entrypoints are seen too. - const classes = new Map(); - for (const node of ast.body) { - const classNode = asClassDeclaration(node); - if (classNode?.id?.name) classes.set(classNode.id.name, classNode); - } - - const entrypoints = new Set(); - // Iterate to a fixed point so an indirect chain (A extends B extends WE) is - // fully resolved regardless of declaration order. - let changed = true; - while (changed) { - changed = false; - for (const [name, classNode] of classes) { - if (entrypoints.has(name)) continue; - if (extendsWorkerEntrypoint(classNode.superClass, bases, entrypoints)) { - entrypoints.add(name); - changed = true; - } - } - } - return entrypoints; -} - -/** Unwrap `export class Foo {}` to its ClassDeclaration; pass bare classes through. */ -function asClassDeclaration(node: BaseNode): ClassDeclarationNode | undefined { - if (node.type === 'ClassDeclaration') return node; - if (node.type === 'ExportNamedDeclaration') { - const decl = (node as ExportNamedDeclNode).declaration; - if (decl?.type === 'ClassDeclaration') return decl; - } - return undefined; -} - -function collectWorkerEntrypointImports(ast: ProgramBody): WorkerEntrypointBases { - const named = new Set(); - const namespaces = new Set(); - for (const node of ast.body) { - if (node.type !== 'ImportDeclaration') continue; - const importNode = node as ImportDeclarationNode; - if (importNode.source?.value !== 'cloudflare:workers') continue; - for (const specifier of importNode.specifiers ?? []) { - if ( - specifier.type === 'ImportSpecifier' && - specifier.imported?.name === 'WorkerEntrypoint' && - specifier.local?.name - ) { - named.add(specifier.local.name); - } else if (specifier.type === 'ImportNamespaceSpecifier' && specifier.local?.name) { - namespaces.add(specifier.local.name); - } - } - } - return { named, namespaces }; -} - -/** - * Whether a superclass expression resolves to `WorkerEntrypoint` — either a bare - * identifier from the named import (or an already-detected local subclass), or a - * `ns.WorkerEntrypoint` member access off a namespace import. - */ -function extendsWorkerEntrypoint( - superClass: BaseNode | null | undefined, - bases: WorkerEntrypointBases, - detected: Set, -): boolean { - if (!superClass) return false; - if (superClass.type === 'Identifier') { - const name = (superClass as IdentifierNode).name; - return bases.named.has(name) || detected.has(name); - } - if (superClass.type === 'MemberExpression') { - const member = superClass as MemberExpressionNode; - return ( - member.object?.type === 'Identifier' && - !!member.object.name && - bases.namespaces.has(member.object.name) && - member.property?.name === 'WorkerEntrypoint' - ); - } - return false; + return findClassesExtending(ast, { module: 'cloudflare:workers', name: 'WorkerEntrypoint' }); } diff --git a/packages/cloudflare/test/vite/agentClass.test.ts b/packages/cloudflare/test/vite/agentClass.test.ts index 90fbea795d90..1c7fecbee32d 100644 --- a/packages/cloudflare/test/vite/agentClass.test.ts +++ b/packages/cloudflare/test/vite/agentClass.test.ts @@ -1,11 +1,15 @@ -import { parse } from 'acorn'; -import { describe, expect, it } from 'vitest'; +import { loadParser, parseModule } from '@sentry/bundler-plugins/rewriter'; +import { beforeAll, describe, expect, it } from 'vitest'; import { collectAgentCandidates, detectAgentClasses, type ModuleResolver } from '../../src/vite/agentClass'; function parseJS(code: string) { - return parse(code, { ecmaVersion: 'latest', sourceType: 'module' }) as unknown as { body: any[] }; + return parseModule(code, 'module.js') as unknown as { body: any[] }; } +beforeAll(async () => { + await loadParser(); +}); + const ENTRY = '/app/src/index.js'; /** diff --git a/packages/cloudflare/test/vite/autoInstrument.test.ts b/packages/cloudflare/test/vite/autoInstrument.test.ts index 0ad992104d10..d92dbbea75f8 100644 --- a/packages/cloudflare/test/vite/autoInstrument.test.ts +++ b/packages/cloudflare/test/vite/autoInstrument.test.ts @@ -1,17 +1,21 @@ import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; -import { parse } from 'acorn'; -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { loadParser, parseModule } from '@sentry/bundler-plugins/rewriter'; +import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'; import { sentryCloudflareAutoInstrumentPlugin } from '../../src/vite/autoInstrument'; const { idResolver } = vi.hoisted(() => ({ idResolver: vi.fn() })); vi.mock('vite', () => ({ createIdResolver: () => idResolver })); function parseJS(code: string) { - return parse(code, { ecmaVersion: 'latest', sourceType: 'module' }) as unknown as { body: any[] }; + return parseModule(code, 'module.js') as unknown as { body: any[] }; } +beforeAll(async () => { + await loadParser(); +}); + const tempDirs: string[] = []; afterEach(() => { @@ -42,7 +46,7 @@ describe('sentryCloudflareAutoInstrumentPlugin', () => { const mainMatch = wranglerToml.match(/main\s*=\s*"([^"]+)"/); const entryPath = join(dir, mainMatch?.[1] ?? 'src/index.ts'); - // Bind a mock `this.parse` that delegates to acorn. + // Bind a mock `this.parse` that delegates to oxc. const boundTransform = (code: string, id: string) => plugin.transform.call({ parse: (c: string) => parseJS(c) }, code, id); diff --git a/packages/cloudflare/test/vite/transform.test.ts b/packages/cloudflare/test/vite/transform.test.ts index bc99d7133f5b..e29cb2fab382 100644 --- a/packages/cloudflare/test/vite/transform.test.ts +++ b/packages/cloudflare/test/vite/transform.test.ts @@ -2,15 +2,19 @@ import { execFileSync } from 'node:child_process'; import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; -import { parse } from 'acorn'; -import { describe, expect, it } from 'vitest'; +import { loadParser, parseModule } from '@sentry/bundler-plugins/rewriter'; +import { beforeAll, describe, expect, it } from 'vitest'; import { applyAutoInstrumentTransforms, type ClassWrapperKind, type TransformContext } from '../../src/vite/transform'; import { DEFAULT_EXPORT } from '../../src/vite/wranglerConfig'; function parseJS(code: string) { - return parse(code, { ecmaVersion: 'latest', sourceType: 'module' }) as unknown as { body: any[] }; + return parseModule(code, 'module.js') as unknown as { body: any[] }; } +beforeAll(async () => { + await loadParser(); +}); + /** Build a `classWrappers` map with every given class name marked as a DO. */ function doWrappers(...names: string[]): Map { return new Map(names.map(name => [name, 'durableObject'])); diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index f09b4d224b21..f4d9bc2312d7 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -1231,6 +1231,9 @@ importers: '@opentelemetry/api': specifier: ^1.9.1 version: 1.10.0 + '@sentry/bundler-plugins': + specifier: 11.18.0 + version: link:../bundler-plugins '@sentry/conventions': specifier: ^0.36.0 version: 0.36.0 @@ -1256,9 +1259,6 @@ importers: '@types/node': specifier: ^20.19.0 version: 20.19.43 - acorn: - specifier: ^8.14.0 - version: 8.18.0 vite: specifier: ^8.3.6 version: 8.3.6(@types/node@20.19.43)(esbuild@0.28.1)(jiti@2.7.0)(less@4.2.0(supports-color@10.0.0))(sass@1.72.0)(stylus@0.59.0(supports-color@10.0.0))(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0) From 44870394cf4ebfab86c1294b01546072ac2ed207 Mon Sep 17 00:00:00 2001 From: Tim Fish Date: Wed, 25 Nov 2026 21:53:51 +0000 Subject: [PATCH 2/3] test(cloudflare): Expect the export clause before the wrapped class --- packages/cloudflare/test/vite/autoInstrument.test.ts | 2 +- packages/cloudflare/test/vite/transform.test.ts | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/packages/cloudflare/test/vite/autoInstrument.test.ts b/packages/cloudflare/test/vite/autoInstrument.test.ts index d92dbbea75f8..b5d75937ffcf 100644 --- a/packages/cloudflare/test/vite/autoInstrument.test.ts +++ b/packages/cloudflare/test/vite/autoInstrument.test.ts @@ -255,11 +255,11 @@ describe('sentryCloudflareAutoInstrumentPlugin', () => { [ "import * as __SENTRY__ from '@sentry/cloudflare';", "import { WorkerEntrypoint } from 'cloudflare:workers';", + 'export { __SENTRY_WRAPPED_AdminEntry__ as AdminEntry };', 'class AdminEntry extends WorkerEntrypoint {', ' fetch() { return new Response("admin"); }', '}', 'const __SENTRY_WRAPPED_AdminEntry__ = __SENTRY__.withSentry(() => undefined, AdminEntry);', - 'export { __SENTRY_WRAPPED_AdminEntry__ as AdminEntry };', '', ].join('\n'), ); diff --git a/packages/cloudflare/test/vite/transform.test.ts b/packages/cloudflare/test/vite/transform.test.ts index e29cb2fab382..44b91397edda 100644 --- a/packages/cloudflare/test/vite/transform.test.ts +++ b/packages/cloudflare/test/vite/transform.test.ts @@ -1066,17 +1066,17 @@ describe('agent class wrapping', () => { "import { Agent } from 'agents';", "import { AIChatAgent } from '@cloudflare/ai-chat';", "import { DurableObject } from 'cloudflare:workers';", + 'export { __SENTRY_WRAPPED_MyAgent__ as MyAgent };', 'class MyAgent extends Agent {}', 'const __SENTRY_WRAPPED_MyAgent__ = __SENTRY__.instrumentAgentWithSentry((env) => ({ dsn: env.SENTRY_DSN }), MyAgent);', - 'export { __SENTRY_WRAPPED_MyAgent__ as MyAgent };', '', + 'export { __SENTRY_WRAPPED_MyChat__ as MyChat };', 'class MyChat extends AIChatAgent {}', 'const __SENTRY_WRAPPED_MyChat__ = __SENTRY__.instrumentAgentWithSentry((env) => ({ dsn: env.SENTRY_DSN }), MyChat);', - 'export { __SENTRY_WRAPPED_MyChat__ as MyChat };', '', + 'export { __SENTRY_WRAPPED_MyDO__ as MyDO };', 'class MyDO extends DurableObject {}', 'const __SENTRY_WRAPPED_MyDO__ = __SENTRY__.instrumentDurableObjectWithSentry((env) => ({ dsn: env.SENTRY_DSN }), MyDO);', - 'export { __SENTRY_WRAPPED_MyDO__ as MyDO };', '', 'var __SENTRY_DEFAULT_EXPORT__ = { fetch() {} };', 'export { __SENTRY_DEFAULT_EXPORT__ as default };', From 2c10a7098d5a4944cedb1eee0e5a65a9d397457d Mon Sep 17 00:00:00 2001 From: Tim Fish Date: Thu, 26 Nov 2026 14:38:55 +0000 Subject: [PATCH 3/3] chore(cloudflare): Depend on @sentry/bundler-plugins 11.19.0 --- packages/cloudflare/package.json | 2 +- pnpm-lock.yaml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/cloudflare/package.json b/packages/cloudflare/package.json index 625a23ef6d50..99c98c88c7c2 100644 --- a/packages/cloudflare/package.json +++ b/packages/cloudflare/package.json @@ -53,7 +53,7 @@ }, "dependencies": { "@opentelemetry/api": "^1.9.1", - "@sentry/bundler-plugins": "11.18.0", + "@sentry/bundler-plugins": "11.19.0", "@sentry/conventions": "^0.36.0", "@sentry/core": "11.19.0", "@sentry/opentelemetry": "11.19.0", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index f4d9bc2312d7..faad5100b91b 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -1232,7 +1232,7 @@ importers: specifier: ^1.9.1 version: 1.10.0 '@sentry/bundler-plugins': - specifier: 11.18.0 + specifier: 11.19.0 version: link:../bundler-plugins '@sentry/conventions': specifier: ^0.36.0