Skip to content
Merged
5 changes: 5 additions & 0 deletions packages/bundler-plugins/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,11 @@
"import": "./build/esm/babel-plugin/index.js",
"require": "./build/cjs/babel-plugin/index.js"
},
"./rewriter": {
"types": "./build/types/rewriter/index.d.ts",
"import": "./build/esm/rewriter/index.js",
"require": "./build/cjs/rewriter/index.js"
},

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Rewriter export missing runtime-entries coverage

Low Severity

This was flagged because it is called out in the review rules file: a new ./rewriter export that can load on Node, while @sentry/bundler-plugins has no entry in CASES or BUILD_TIME_CASES in dev-packages/bundler-tests/tests/runtime-entries.test.ts. That test is what keeps server runtime entries from pulling in build-time tooling.

Fix in Cursor Fix in Web

Triggered by project rule: PR Review Guidelines for Cursor Bot

Reviewed by Cursor Bugbot for commit 8b2355d. Configure here.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

./rewriter is build-time code that only the SDK Vite plugins import, and BUILD_TIME_PATTERNS already fails any runtime entry that pulls in @sentry/bundler-plugins.

"./sentry-release-injection-file": {
"import": "./sentry-release-injection-file.js",
"require": "./sentry-release-injection-file.js"
Expand Down
1 change: 1 addition & 0 deletions packages/bundler-plugins/rollup.npm.config.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ export default makeNPMConfigVariants(
'src/webpack/index.ts',
'src/webpack/component-annotation-transform.ts',
'src/babel-plugin/index.ts',
'src/rewriter/index.ts',
],
packageSpecificConfig: {
// This package only ever runs in Node, at build time. Without pinning the platform, rolldown
Expand Down
31 changes: 31 additions & 0 deletions packages/bundler-plugins/src/rewriter/arrays.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import type { ArrayExpressionNode, BaseNode, IdentifierNode } from './ast';
import type { RewriteState } from './rewriter';

/**
* Replace an array literal of identifiers with `build(names)`, where `names`
* holds each identifier once, in source order. An empty array is left alone.
* An array holding anything other than plain identifiers is left alone and
* recorded as skipped under `label`.
*
* @returns whether the array was replaced
*/
export function wrapArrayLiteral(
state: RewriteState,
arrayNode: BaseNode,
label: string,
build: (names: string[]) => string,
): boolean {
const elements = (arrayNode as ArrayExpressionNode).elements ?? [];
if (elements.length === 0) return false;

if (!elements.every(element => element?.type === 'Identifier')) {
state.report.skipped.push(label);
return false;
}

const names = [...new Set(elements.map(element => (element as IdentifierNode).name))];
state.ms.overwrite(arrayNode.start, arrayNode.end, build(names));
state.needsImport = true;
state.report.wrapped.push(label);
return true;
}
215 changes: 215 additions & 0 deletions packages/bundler-plugins/src/rewriter/ast.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,215 @@
// Minimal ESTree node shapes. Any parser that puts `start`/`end` offsets on
// every node fits (oxc, acorn, Rollup's `this.parse`).

export interface BaseNode {
type: string;
start: number;
end: number;
}

export interface ProgramBody {
body: BaseNode[];
hashbang?: BaseNode | null;
}

export interface IdentifierNode extends BaseNode {
name: string;
}

/** An `Identifier` or, for `export { x as "name" }`, a string `Literal`. */
export interface NameNode {
type: string;
name?: string;
value?: unknown;
}

export interface CallExpressionNode extends BaseNode {
callee?: { type: string; name?: string; property?: { type: string; name?: string } };
arguments?: BaseNode[];
}

export interface MemberExpressionNode extends BaseNode {
object?: { type: string; name?: string };
property?: { type: string; name?: string };
}

export interface ClassDeclarationNode extends BaseNode {
id?: IdentifierNode | null;
superClass?: BaseNode | null;
decorators?: BaseNode[] | null;
}

export interface ExportDefaultNode extends BaseNode {
declaration: BaseNode;
}

export interface ExportSpecifierNode extends BaseNode {
local?: NameNode;
exported?: NameNode;
exportKind?: string;
}

export interface ExportNamedNode extends BaseNode {
declaration?: BaseNode | null;
source?: (BaseNode & { value?: unknown }) | null;
specifiers?: ExportSpecifierNode[];
exportKind?: string;
}

export interface ExportAllNode extends BaseNode {
source?: { value?: unknown };
exported?: NameNode | null;
exportKind?: string;
}

export interface VariableDeclaratorNode {
id?: BaseNode | null;
init?: BaseNode | null;
}

export interface VariableDeclarationNode extends BaseNode {
declarations?: VariableDeclaratorNode[];
}

export interface ImportSpecifierNode {
type: string;
imported?: NameNode;
local?: NameNode;
importKind?: string;
}

export interface ImportDeclarationNode extends BaseNode {
source?: { value?: unknown };
specifiers?: ImportSpecifierNode[];
importKind?: string;
}

export interface ArrayExpressionNode extends BaseNode {
elements?: Array<BaseNode | null>;
}

export interface PropertyNode extends BaseNode {
key?: NameNode;
value?: BaseNode;
computed?: boolean;
}

/** The declaration a top-level statement makes, looking through `export` (`export const x = ...`). */
export function declarationOf(node: BaseNode): BaseNode | null | undefined {
return node.type === 'ExportNamedDeclaration' ? (node as ExportNamedNode).declaration : node;
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Default-exported classes are not found

Medium Severity

declarationOf only unwraps ExportNamedDeclaration, so findClassesExtending, collectTopLevelClasses, and collectDeclaringStatements never see export default class Foo {} or export default function foo() {}. shapeFromAst already records those named default classes, so the collectors disagree on the same module. A default-exported WorkerEntrypoint subclass is a common Cloudflare form and would not be found.

Additional Locations (2)
Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 65ef1b6. Configure here.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

The Cloudflare class scans on develop also skip export default class, so this is not new in this PR.


/** Whether `node` calls `methodName`, either bare (`fn()`) or as a member (`ns.fn()`). */
export 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
);
}

export 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;
}

/** `export type { X }` or `export { type X }`, which TypeScript erases. */
export function isTypeOnlyExport(node: { exportKind?: string }): boolean {
return node.exportKind === 'type';
}

/** The name an export or import specifier refers to, for both `x` and `"x"`. */
export function exportedName(node: NameNode | undefined): string | undefined {
if (node?.type === 'Identifier') return node.name;
if (node?.type === 'Literal' && typeof node.value === 'string') return node.value;
return undefined;
}

/**
* The offset after the hashbang and the directive prologue (`'use server'`),
* where code may be inserted without changing what the module means.
*/
export function directivesEnd(ast: ProgramBody): number {
let end = ast.hashbang?.end ?? 0;
for (const node of ast.body) {
if (node.type !== 'ExpressionStatement' || typeof (node as { directive?: unknown }).directive !== 'string') break;
end = node.end;
}
return end;
}

/**
* The binding names a declaration introduces, including names inside
* destructuring patterns. `undefined` for a declaration that binds no runtime
* value (`interface`, `type`).
*/
export function declaredNames(declaration: BaseNode): string[] | undefined {
switch (declaration.type) {
case 'ClassDeclaration':
case 'FunctionDeclaration': {
const name = (declaration as ClassDeclarationNode).id?.name;
return name ? [name] : undefined;
}
case 'VariableDeclaration': {
const names: string[] = [];
for (const declarator of (declaration as VariableDeclarationNode).declarations ?? []) {
collectPatternNames(declarator.id, names);
}
return names;
}
default:
return undefined;
}
}

function collectPatternNames(pattern: BaseNode | null | undefined, names: string[]): void {
if (!pattern) return;
const node = pattern as BaseNode & {
name?: string;
properties?: Array<BaseNode & { value?: BaseNode; argument?: BaseNode }>;
elements?: Array<BaseNode | null>;
left?: BaseNode;
argument?: BaseNode;
};
switch (node.type) {
case 'Identifier':
if (node.name) names.push(node.name);
break;
case 'ObjectPattern':
for (const property of node.properties ?? []) {
collectPatternNames(property.type === 'RestElement' ? property.argument : property.value, names);
}
break;
case 'ArrayPattern':
for (const element of node.elements ?? []) collectPatternNames(element, names);
break;
case 'AssignmentPattern':
collectPatternNames(node.left, names);
break;
case 'RestElement':
collectPatternNames(node.argument, names);
break;
}
}

/** Visit `node` and every node below it, parents first. */
export function walk(node: unknown, visit: (node: BaseNode) => void): void {
if (Array.isArray(node)) {
for (const child of node) walk(child, visit);
return;
}
if (!node || typeof node !== 'object' || typeof (node as BaseNode).type !== 'string') return;

visit(node as BaseNode);
for (const value of Object.values(node)) {
if (value && typeof value === 'object') walk(value, visit);
}
}
104 changes: 104 additions & 0 deletions packages/bundler-plugins/src/rewriter/class-extends.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
import type {
BaseNode,
ClassDeclarationNode,
IdentifierNode,
ImportDeclarationNode,
MemberExpressionNode,
ProgramBody,
} from './ast';
import { declarationOf } from './ast';

/** A base class, named by the module it is imported from and its export name. */
export interface BaseClassRef {
module: string;
name: string;
}

interface BaseBindings {
/** Local identifiers bound to the named import of the base class. */
named: Set<string>;
/** Local identifiers bound to a `* as ns` import of the base module. */
namespaces: Set<string>;
}

/**
* Find top-level classes that (transitively, within this module) extend the
* given base class. A superclass must be a plain identifier (`extends Base`)
* or member access (`extends ns.Base`).
*
* Only same-file base chains are resolvable here; a base class imported from
* another module under a different name is invisible.
*/
export function findClassesExtending(ast: ProgramBody, base: BaseClassRef): Set<string> {
const bases = collectBaseImports(ast, base);
if (bases.named.size === 0 && bases.namespaces.size === 0) {
return new Set<string>();
}

// Every top-level class, including the `export class Foo {}` form.
const classes = new Map<string, ClassDeclarationNode>();
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);
}
Comment thread
sentry-warden[bot] marked this conversation as resolved.
Resolved

const found = new Set<string>();
// Iterate to a fixed point so an indirect chain (A extends B extends Base) is
// fully resolved regardless of declaration order.
let changed = true;
while (changed) {
changed = false;
for (const [name, classNode] of classes) {
if (found.has(name)) continue;
if (extendsBase(classNode.superClass, base, bases, found)) {
found.add(name);
changed = true;
}
}
}
return found;
}

function collectBaseImports(ast: ProgramBody, base: BaseClassRef): BaseBindings {
const named = new Set<string>();
const namespaces = new Set<string>();
for (const node of ast.body) {
if (node.type !== 'ImportDeclaration') continue;
const importNode = node as ImportDeclarationNode;
if (importNode.source?.value !== base.module || importNode.importKind === 'type') continue;
for (const specifier of importNode.specifiers ?? []) {
if (specifier.importKind === 'type') continue;
if (specifier.type === 'ImportSpecifier' && specifier.imported?.name === base.name && specifier.local?.name) {
named.add(specifier.local.name);
} else if (specifier.type === 'ImportNamespaceSpecifier' && specifier.local?.name) {
namespaces.add(specifier.local.name);
}
}
}
return { named, namespaces };
}
Comment thread
sentry-warden[bot] marked this conversation as resolved.
Resolved

function extendsBase(
superClass: BaseNode | null | undefined,
base: BaseClassRef,
bases: BaseBindings,
detected: Set<string>,
): 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 === base.name
);
}
return false;
}
Loading
Loading