diff --git a/packages/bundler-plugins/package.json b/packages/bundler-plugins/package.json index 0380ff16fc0e..a4f75f2f2cf5 100644 --- a/packages/bundler-plugins/package.json +++ b/packages/bundler-plugins/package.json @@ -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" + }, "./sentry-release-injection-file": { "import": "./sentry-release-injection-file.js", "require": "./sentry-release-injection-file.js" diff --git a/packages/bundler-plugins/rollup.npm.config.mjs b/packages/bundler-plugins/rollup.npm.config.mjs index 14a01bf06c1e..8db6b8b9bd47 100644 --- a/packages/bundler-plugins/rollup.npm.config.mjs +++ b/packages/bundler-plugins/rollup.npm.config.mjs @@ -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 diff --git a/packages/bundler-plugins/src/rewriter/arrays.ts b/packages/bundler-plugins/src/rewriter/arrays.ts new file mode 100644 index 000000000000..d2db7c3aa5f5 --- /dev/null +++ b/packages/bundler-plugins/src/rewriter/arrays.ts @@ -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; +} diff --git a/packages/bundler-plugins/src/rewriter/ast.ts b/packages/bundler-plugins/src/rewriter/ast.ts new file mode 100644 index 000000000000..49bd57b584e0 --- /dev/null +++ b/packages/bundler-plugins/src/rewriter/ast.ts @@ -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; +} + +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; +} + +/** 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; + elements?: Array; + 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); + } +} diff --git a/packages/bundler-plugins/src/rewriter/class-extends.ts b/packages/bundler-plugins/src/rewriter/class-extends.ts new file mode 100644 index 000000000000..4afce1447aee --- /dev/null +++ b/packages/bundler-plugins/src/rewriter/class-extends.ts @@ -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; + /** Local identifiers bound to a `* as ns` import of the base module. */ + namespaces: Set; +} + +/** + * 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 { + const bases = collectBaseImports(ast, base); + if (bases.named.size === 0 && bases.namespaces.size === 0) { + return new Set(); + } + + // Every top-level class, including the `export class Foo {}` form. + 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); + } + + const found = new Set(); + // 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(); + const namespaces = new Set(); + 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 }; +} + +function extendsBase( + superClass: BaseNode | null | undefined, + base: BaseClassRef, + bases: BaseBindings, + 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 === base.name + ); + } + return false; +} diff --git a/packages/bundler-plugins/src/rewriter/exports.ts b/packages/bundler-plugins/src/rewriter/exports.ts new file mode 100644 index 000000000000..d8c651027861 --- /dev/null +++ b/packages/bundler-plugins/src/rewriter/exports.ts @@ -0,0 +1,361 @@ +import type { + BaseNode, + ClassDeclarationNode, + ExportDefaultNode, + ExportNamedNode, + ExportSpecifierNode, + IdentifierNode, + ImportDeclarationNode, + ProgramBody, + VariableDeclarationNode, +} from './ast'; +import { + declarationOf, + declaredNames, + exportedName, + isAnonymousFunctionOrClass, + isCallToMethod, + isTypeOnlyExport, +} from './ast'; +import type { RewriteState } from './rewriter'; + +/** Builds the expression that wraps `target`, e.g. `target => \`wrap(${target})\``. */ +export type WrapExpression = (target: string) => string; + +/** + * Handles one export specifier of a statement passed to {@link wrapSpecifierExports}. + * Returns the `Wrapped as Exported` pair to emit in its place, or `undefined` + * to keep the specifier as written. Statements the pair depends on go onto + * `prelude`, which is emitted before the rebuilt export. + */ +export type SpecifierWrapper = ( + specifier: ExportSpecifierNode, + sourceLiteral: string | undefined, + prelude: string[], +) => string | undefined; + +/** Specifier name a `export { default as X } from '...'` re-export uses for the source's default. */ +const DEFAULT_IMPORT = 'default'; + +/** Top-level class declarations, exported or not, by name. */ +export 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; +} + +/** Top-level value binding name → the statement that declares it. */ +export function collectDeclaringStatements(ast: ProgramBody): Map { + const statements = new Map(); + for (const node of ast.body) { + const declaration = declarationOf(node); + if (!declaration) continue; + const names = + declaration.type === 'ImportDeclaration' ? valueImportNames(declaration) : (declaredNames(declaration) ?? []); + for (const name of names) { + if (name) statements.set(name, node); + } + } + return statements; +} + +function valueImportNames(node: ImportDeclarationNode): (string | undefined)[] { + if (node.importKind === 'type') return []; + return (node.specifiers ?? []) + .filter(specifier => specifier.importKind !== 'type') + .map(specifier => specifier.local?.name); +} + +/** + * Top-level bindings already assigned the result of one of `wrapperNames` + * (`const X = wrap(...)`), so exporting one must not wrap it a second time. + */ +export function collectManuallyWrappedLocals(ast: ProgramBody, wrapperNames: readonly string[]): Set { + 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 as IdentifierNode).name : undefined; + const init = declarator.init; + if (name && init && wrapperNames.some(wrapper => isCallToMethod(init, wrapper))) { + locals.add(name); + } + } + } + + return locals; +} + +/** The value export statements (`export const`, `export { }`) that export `name`. */ +export function findNamedExports(ast: ProgramBody, name: string): ExportNamedNode[] { + const found: ExportNamedNode[] = []; + for (const node of ast.body) { + if (node.type !== 'ExportNamedDeclaration' || isTypeOnlyExport(node as ExportNamedNode)) continue; + const exportNode = node as ExportNamedNode; + const exportsName = exportNode.declaration + ? !!declaredNames(exportNode.declaration)?.includes(name) + : (exportNode.specifiers ?? []).some( + specifier => !isTypeOnlyExport(specifier) && exportedName(specifier.exported) === name, + ); + if (exportsName) found.push(exportNode); + } + return found; +} + +/** + * Wrap a binding declared in this module and return the binding that holds the wrapper. + * + * The declaration is left exactly as written, so a class or function keeps its + * `Function.prototype.name`. Only the *export* has to become the wrapper, so the wrapper gets its + * own binding and the export is aliased to it. + */ +export function wrapLocalBinding( + state: RewriteState, + localName: string, + declaringNode: BaseNode, + wrap: WrapExpression, +): string { + const existing = state.wrappedLocals.get(localName); + if (existing) return existing; + + const wrappedName = `__SENTRY_WRAPPED_${localName}__`; + state.wrappedLocals.set(localName, wrappedName); + state.ms.appendLeft(declaringNode.end, `\nconst ${wrappedName} = ${wrap(localName)};\n`); + state.needsImport = true; + return wrappedName; +} + +/** + * Wrap `localName` where an inline export declares it (`export class X {}`, + * `export const x = ...`, `export function x() {}`). The `export` keyword is + * replaced by an export clause that aliases the name to the wrapper. Other + * names the same declaration exports are exported again, through their + * wrapper when a later call wraps them too. + * + * @returns whether the declaration exports `localName` + */ +export function wrapInlineExport( + state: RewriteState, + exportNode: ExportNamedNode, + localName: string, + wrap: WrapExpression, +): boolean { + const declaration = exportNode.declaration; + const names = declaration ? declaredNames(declaration) : undefined; + if (!declaration || !names?.includes(localName)) return false; + + wrapLocalBinding(state, localName, declaration, wrap); + const specifiers = names.map(name => { + const wrappedName = state.wrappedLocals.get(name); + return wrappedName ? `${wrappedName} as ${name}` : name; + }); + // In `@dec export class A {}` the decorators come before `export`, so the + // clause has to go before them. + const decoratorStart = (declaration as ClassDeclarationNode).decorators?.[0]?.start ?? exportNode.start; + const start = Math.min(decoratorStart, exportNode.start); + const decorators = state.ms.original.slice(start, exportNode.start); + // A second call for another name of this declaration overwrites the same range again. + state.ms.overwrite(start, declaration.start, `export { ${specifiers.join(', ')} };\n${decorators}`); + return true; +} + +/** + * Wrap the specifiers of an `export { ... }` statement that `wrapSpecifier` picks. + * + * Each such specifier is re-pointed at a binding holding the wrapper, which means rebuilding the + * statement; the other specifiers are carried over verbatim. A binding that lives in **another** + * module is first bound under a private name (see {@link wrapForeignExport}), since an import + * binding cannot be reassigned and the `from` form has no local binding at all. + */ +export function wrapSpecifierExports( + state: RewriteState, + node: ExportNamedNode, + wrapSpecifier: SpecifierWrapper, +): void { + const specifiers = node.specifiers ?? []; + if (specifiers.length === 0 || isTypeOnlyExport(node)) 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 = isTypeOnlyExport(specifier) ? undefined : wrapSpecifier(specifier, sourceLiteral, 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')); +} + +/** + * Wrap a binding that comes from another module: imported and re-exported + * (`sourceLiteral` undefined), or re-exported directly (`export { x } from`). + * Pushes the statements that bind the wrapper onto `prelude` and returns the + * pair to export. + */ +export function wrapForeignExport( + state: RewriteState, + localName: string, + exportedAs: string, + sourceLiteral: string | undefined, + prelude: string[], + wrap: WrapExpression, +): string { + let target = localName; + + if (sourceLiteral) { + target = `__SENTRY_REEXPORT_${exportedAs}__`; + prelude.push(importAs(localName, target, sourceLiteral)); + } + + const wrappedName = `__SENTRY_WRAPPED_${exportedAs}__`; + prelude.push(`const ${wrappedName} = ${wrap(target)};`); + state.needsImport = true; + return `${wrappedName} as ${exportedAs}`; +} + +/** + * Wrap `export default `. + * + * `export default Foo`, where `Foo` already has a wrapper binding (a class + * also exported by name), is re-pointed at that binding instead of wrapping + * twice. + */ +export function wrapDefaultExport(state: RewriteState, node: ExportDefaultNode, wrap: WrapExpression): void { + const decl = node.declaration; + + if (decl.type === 'Identifier') { + const wrappedName = state.wrappedLocals.get((decl as IdentifierNode).name); + if (wrappedName) { + state.ms.overwrite(decl.start, decl.end, wrappedName); + return; + } + } + + // 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; + + // 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__ = ${wrap(wrapped)};`); + state.needsImport = true; +} + +/** + * 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; +} + +/** + * `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. + * + * @returns the pair to export in place of the specifier + */ +export function wrapDefaultSpecifier( + state: RewriteState, + localName: string, + declaringStatement: BaseNode | undefined, + wrap: WrapExpression, +): string { + // Same as `export default Foo`: re-point at the wrapper a named export already made. + const wrappedName = state.wrappedLocals.get(localName); + if (wrappedName) return `${wrappedName} as default`; + + if (declaringStatement) { + state.ms.appendLeft(declaringStatement.end, `\nvar __SENTRY_DEFAULT_EXPORT__ = ${localName};`); + } + state.ms.append(`\n${declaringStatement ? '' : 'var '}__SENTRY_DEFAULT_EXPORT__ = ${wrap(localName)};`); + state.needsImport = true; + return '__SENTRY_DEFAULT_EXPORT__ as default'; +} + +/** + * `export { default } from './handler'` and `export { x as default } from './handler'`. + * + * 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`. + * + * @returns the pair to export in place of the specifier + */ +export function wrapDefaultReexport( + state: RewriteState, + localName: string, + sourceLiteral: string, + prelude: string[], + wrap: WrapExpression, +): string { + const target = '__SENTRY_REEXPORT_default__'; + prelude.push(importAs(localName, target, sourceLiteral), `var __SENTRY_DEFAULT_EXPORT__ = ${wrap(target)};`); + state.needsImport = true; + return '__SENTRY_DEFAULT_EXPORT__ as default'; +} + +function importAs(importedName: string, localName: string, sourceLiteral: string): string { + return importedName === DEFAULT_IMPORT + ? `import ${localName} from ${sourceLiteral};` + : `import { ${importedName} as ${localName} } from ${sourceLiteral};`; +} diff --git a/packages/bundler-plugins/src/rewriter/imports.ts b/packages/bundler-plugins/src/rewriter/imports.ts new file mode 100644 index 000000000000..3d3a7de86743 --- /dev/null +++ b/packages/bundler-plugins/src/rewriter/imports.ts @@ -0,0 +1,28 @@ +import type { ImportDeclarationNode, ProgramBody } from './ast'; +import { directivesEnd, exportedName } from './ast'; +import type { RewriteState } from './rewriter'; + +/** Whether the module already binds `name` to the export of the same name from `module`. */ +export function hasImport(ast: ProgramBody, module: string, name: string): boolean { + return ast.body.some(node => { + if (node.type !== 'ImportDeclaration') return false; + const importNode = node as ImportDeclarationNode; + if (importNode.source?.value !== module || importNode.importKind === 'type') return false; + return (importNode.specifiers ?? []).some( + specifier => + specifier.type === 'ImportSpecifier' && + specifier.importKind !== 'type' && + exportedName(specifier.imported) === name && + specifier.local?.name === name, + ); + }); +} + +/** Adds an import statement after the hashbang and directives, once per module. */ +export function addImport(state: RewriteState, ast: ProgramBody, statement: string): void { + if (state.imports.has(statement)) return; + state.imports.add(statement); + + const position = directivesEnd(ast); + state.ms.appendLeft(position, position === 0 ? `${statement}\n` : `\n${statement}`); +} diff --git a/packages/bundler-plugins/src/rewriter/index.ts b/packages/bundler-plugins/src/rewriter/index.ts new file mode 100644 index 000000000000..ed44fbb9dd47 --- /dev/null +++ b/packages/bundler-plugins/src/rewriter/index.ts @@ -0,0 +1,9 @@ +export * from './ast'; +export * from './arrays'; +export * from './class-extends'; +export * from './exports'; +export * from './imports'; +export * from './module-shape'; +export * from './parse'; +export * from './report'; +export * from './rewriter'; diff --git a/packages/bundler-plugins/src/rewriter/module-shape.ts b/packages/bundler-plugins/src/rewriter/module-shape.ts new file mode 100644 index 000000000000..2b16b0f7ab77 --- /dev/null +++ b/packages/bundler-plugins/src/rewriter/module-shape.ts @@ -0,0 +1,176 @@ +import type { + BaseNode, + ClassDeclarationNode, + ExportAllNode, + ExportDefaultNode, + ExportNamedNode, + IdentifierNode, + ImportDeclarationNode, + MemberExpressionNode, + ProgramBody, +} from './ast'; +import { exportedName, isTypeOnlyExport } from './ast'; +import { langFromId, parseModule } from './parse'; + +/** 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: [], + }; +} + +/** Collect the shape of a module from its parsed AST. */ +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 ClassDeclarationNode).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 || isTypeOnlyExport(starNode) ? undefined : asString(starNode.source?.value); + if (source) shape.starExports.push(source); + break; + } + } + } + + return shape; +} + +/** + * Extract the module shape from unprocessed source, such as a sibling module + * read off disk. Returns `undefined` when the source does not parse. + */ +export function shapeFromSource(code: string, id: string): ModuleShape | undefined { + const lang = langFromId(id); + // A module read off disk may hold TypeScript or JSX whatever its id says, + // and `tsx` reads everything the other dialects do. + for (const candidate of lang === 'tsx' ? [lang] : [lang, 'tsx' as const]) { + try { + return shapeFromAst(parseModule(code, id, candidate)); + } catch { + // Try the next dialect. + } + } + return undefined; +} + +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: ClassDeclarationNode): 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); + // Type-only imports never contribute a runtime base class. + if (!source || node.importKind === 'type') return; + + for (const specifier of node.specifiers ?? []) { + const local = specifier.local?.name; + if (!local || specifier.importKind === 'type') continue; + + const imported = exportedName(specifier.imported); + if (specifier.type === 'ImportSpecifier' && imported) { + shape.imports.set(local, { source, imported }); + } 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; + } + if (isTypeOnlyExport(node)) return; + + const source = asString(node.source?.value); + for (const specifier of node.specifiers ?? []) { + const exported = exportedName(specifier.exported); + const local = exportedName(specifier.local); + if (!exported || !local || isTypeOnlyExport(specifier)) continue; + + if (source) { + shape.reexports.set(exported, { source, imported: local }); + } else { + shape.localExports.set(exported, local); + } + } +} + +function asString(value: unknown): string | undefined { + return typeof value === 'string' && value ? value : undefined; +} diff --git a/packages/bundler-plugins/src/rewriter/parse.ts b/packages/bundler-plugins/src/rewriter/parse.ts new file mode 100644 index 000000000000..1a83cf2e748f --- /dev/null +++ b/packages/bundler-plugins/src/rewriter/parse.ts @@ -0,0 +1,83 @@ +import { stripUrlQueryAndFragment } from '@sentry/core'; +import type * as OxcParser from 'oxc-parser'; +import type { ProgramBody } from './ast'; + +export type ModuleLang = 'js' | 'jsx' | 'ts' | 'tsx'; + +/** Parses a module into an ESTree program. Throws when the code does not parse. */ +export type ModuleParser = (code: string, id: string) => ProgramBody; + +/** The part of a bundler's plugin context that can parse code. */ +export interface ParserContext { + meta?: { rolldownVersion?: string }; + parse?(input: string, options?: object | null): unknown; +} + +const PARSER_UNAVAILABLE_MESSAGE = + '[@sentry/bundler-plugins] Could not load `oxc-parser` for this platform. ' + + 'Modules that need it will not be auto-instrumented.'; + +// `undefined` while loading, `null` when it failed to load. +let oxc: typeof OxcParser | null | undefined; +let warnedParserUnavailable = false; + +// The import is dynamic so that a platform without an `oxc-parser` native +// binary gets a warning instead of a failed build. +const oxcLoaded: Promise = import('oxc-parser').then( + module => { + oxc = module; + return true; + }, + () => { + oxc = null; + return false; + }, +); + +/** Resolves once `oxc-parser` has loaded or failed to load, with whether it is available. */ +export function loadParser(): Promise { + return oxcLoaded; +} + +export function isParserLoading(): boolean { + return oxc === undefined; +} + +/** The source dialect a module id names by its extension. */ +export function langFromId(id: string): ModuleLang { + const extension = /\.([cm]?[jt]sx?)$/.exec(stripUrlQueryAndFragment(id))?.[1] ?? 'js'; + if (extension === 'tsx') return 'tsx'; + if (extension === 'jsx') return 'jsx'; + return extension.endsWith('ts') ? 'ts' : 'js'; +} + +/** + * The default {@link ModuleParser}, over `oxc-parser`. Throws when `oxc-parser` + * has not loaded; see {@link loadParser}. + */ +export function parseModule(code: string, id: string, lang: ModuleLang = langFromId(id)): ProgramBody { + if (!oxc) { + if (oxc === null && !warnedParserUnavailable) { + warnedParserUnavailable = true; + // eslint-disable-next-line no-console + console.warn(PARSER_UNAVAILABLE_MESSAGE); + } + throw new Error(oxc === null ? PARSER_UNAVAILABLE_MESSAGE : '`oxc-parser` has not loaded yet'); + } + + // `preserveParens: false` matches the AST Vite produces. + const { program, errors } = oxc.parseSync(id, code, { lang, sourceType: 'module', preserveParens: false }); + if (errors.length > 0) { + throw new Error(errors[0]?.message); + } + return program; +} + +/** + * A parser over Rolldown's own `this.parse`, which reads TypeScript when told + * the dialect. Rollup's `this.parse` cannot, so it is not used. + */ +export function bundlerParser(context: ParserContext | undefined): ModuleParser | undefined { + if (!context?.meta?.rolldownVersion || typeof context.parse !== 'function') return undefined; + return (code, id) => context.parse?.(code, { lang: langFromId(id), preserveParens: false }) as ProgramBody; +} diff --git a/packages/bundler-plugins/src/rewriter/report.ts b/packages/bundler-plugins/src/rewriter/report.ts new file mode 100644 index 000000000000..a190474ac257 --- /dev/null +++ b/packages/bundler-plugins/src/rewriter/report.ts @@ -0,0 +1,18 @@ +/** What a rewrite did with the sites it found, by site label. */ +export interface RewriteReport { + wrapped: string[]; + /** Sites the rewrite could not wrap, for the user to wrap by hand. */ + skipped: string[]; + /** Sites the user already wrapped. */ + alreadyWrapped: string[]; +} + +export function createReport(): RewriteReport { + return { wrapped: [], skipped: [], alreadyWrapped: [] }; +} + +/** The warning for the skipped sites of a module, or `undefined` when none were skipped. */ +export function formatReport(report: RewriteReport, id: string): string | undefined { + if (report.skipped.length === 0) return undefined; + return `[Sentry] Could not auto-instrument ${report.skipped.join(' and ')} in ${id}.`; +} diff --git a/packages/bundler-plugins/src/rewriter/rewriter.ts b/packages/bundler-plugins/src/rewriter/rewriter.ts new file mode 100644 index 000000000000..47d29b1e62cf --- /dev/null +++ b/packages/bundler-plugins/src/rewriter/rewriter.ts @@ -0,0 +1,145 @@ +import { basename } from 'node:path'; +import MagicString, { type SourceMap } from 'magic-string'; +import type { ProgramBody } from './ast'; +import { + bundlerParser, + isParserLoading, + loadParser, + type ModuleParser, + parseModule, + type ParserContext, +} from './parse'; +import { createReport, formatReport, type RewriteReport } from './report'; + +/** The edits a rewrite makes to one module, shared by every rule that runs on it. */ +export interface RewriteState { + /** Positions are always relative to the original source. */ + ms: MagicString; + /** Set once the rewritten code references a binding the caller must import. */ + needsImport: boolean; + /** Local binding name → the binding that holds its wrapper. */ + wrappedLocals: Map; + /** Import statements already added to this module. */ + imports: Set; + report: RewriteReport; +} + +export function createRewriteState(code: string): RewriteState { + return { + ms: new MagicString(code), + needsImport: false, + wrappedLocals: new Map(), + imports: new Set(), + report: createReport(), + }; +} + +/** Which modules a rule runs on. Every given condition must hold. */ +export interface RuleInclude { + /** Tested against the full module id. */ + id?: RegExp; + /** Tested against the last path segment of the module id. */ + basename?: RegExp; + /** Substrings the source must contain, checked before parsing. */ + contains?: string[]; +} + +export interface RuleContext { + ast: ProgramBody; + code: string; + id: string; + state: RewriteState; +} + +export interface RewriteRule { + name: string; + include: RuleInclude; + apply(ctx: RuleContext): void | Promise; +} + +export interface RewriterOptions { + /** + * Defaults to Rolldown's `this.parse` when the transform gets a Rolldown + * plugin context, and to {@link parseModule} otherwise. + */ + parse?: ModuleParser; + /** Receives the warning for sites a rule could not wrap. */ + logger?: { warn(message: string): void }; +} + +export interface RewriteOutput { + code: string; + map: SourceMap; +} + +export interface CallSiteRewriter { + /** + * Runs every matching rule on one module. Returns `null` when nothing + * changed. The result is a promise only while `oxc-parser` is still + * loading, or when a rule's `apply` returns one. + * + * @param context the bundler's plugin context, for its parser + */ + transform(code: string, id: string, context?: ParserContext): RewriteOutput | null | Promise; +} + +export function createCallSiteRewriter(rules: RewriteRule[], options: RewriterOptions = {}): CallSiteRewriter { + const rewrite = ( + matching: RewriteRule[], + code: string, + id: string, + parse: ModuleParser, + ): RewriteOutput | null | Promise => { + let ast: ProgramBody; + try { + ast = parse(code, id); + } catch { + return null; + } + + const state = createRewriteState(code); + const ctx: RuleContext = { ast, code, id, state }; + const finish = (): RewriteOutput | null => { + const warning = formatReport(state.report, id); + if (warning) options.logger?.warn(warning); + if (!state.ms.hasChanged()) return null; + return { code: state.ms.toString(), map: state.ms.generateMap({ hires: true }) }; + }; + + const pending = applyRules(matching, ctx, 0); + return pending ? pending.then(finish) : finish(); + }; + + return { + transform(code, id, context) { + const matching = rules.filter(rule => matches(rule.include, code, id)); + if (matching.length === 0) return null; + + const parse = options.parse ?? bundlerParser(context) ?? parseModule; + // Rules may parse other modules with `parseModule`, so it has to be ready + // whichever parser reads this one. + if (isParserLoading()) { + return loadParser().then(() => rewrite(matching, code, id, parse)); + } + return rewrite(matching, code, id, parse); + }, + }; +} + +function matches(include: RuleInclude, code: string, id: string): boolean { + if (include.id && !include.id.test(id)) return false; + if (include.basename && !include.basename.test(basename(id))) return false; + if (include.contains && !include.contains.every(substring => code.includes(substring))) return false; + return true; +} + +/** Applies the rules in order, staying synchronous until a rule returns a promise. */ +function applyRules(rules: RewriteRule[], ctx: RuleContext, from: number): Promise | undefined { + for (let index = from; index < rules.length; index++) { + const pending = rules[index]?.apply(ctx); + if (pending instanceof Promise) { + return pending.then(() => applyRules(rules, ctx, index + 1)); + } + } + return undefined; +} diff --git a/packages/bundler-plugins/test/rewriter/arrays.test.ts b/packages/bundler-plugins/test/rewriter/arrays.test.ts new file mode 100644 index 000000000000..b73736994dcc --- /dev/null +++ b/packages/bundler-plugins/test/rewriter/arrays.test.ts @@ -0,0 +1,68 @@ +import { beforeAll, describe, expect, it } from 'vitest'; +import { type BaseNode, walk } from '../../src/rewriter/ast'; +import { wrapArrayLiteral } from '../../src/rewriter/arrays'; +import { loadParser, parseModule } from '../../src/rewriter/parse'; +import { createRewriteState, type RewriteState } from '../../src/rewriter/rewriter'; + +beforeAll(async () => { + await loadParser(); +}); + +const build = (names: string[]): string => `wrap({ ${names.join(', ')} })`; + +/** Wraps the outermost array literal in `code`. */ +function wrapFirstArray(code: string): { output: string; result: boolean; state: RewriteState } { + const ast = parseModule(code, 'module.ts'); + let array: BaseNode | undefined; + walk(ast, node => { + if (!array && node.type === 'ArrayExpression') array = node; + }); + const state = createRewriteState(code); + const result = wrapArrayLiteral(state, array!, 'middleware', build); + const output = state.ms.toString(); + expect(() => parseModule(output, 'module.ts')).not.toThrow(); + return { output, result, state }; +} + +describe('wrapArrayLiteral', () => { + it('replaces an array of identifiers', () => { + const { output, result, state } = wrapFirstArray('f({ middleware: [a, b] });'); + expect(result).toBe(true); + expect(output).toBe('f({ middleware: wrap({ a, b }) });'); + expect(state.needsImport).toBe(true); + expect(state.report.wrapped).toEqual(['middleware']); + }); + + it('removes duplicates and a trailing comma', () => { + expect(wrapFirstArray('f([a, b, a,]);').output).toBe('f(wrap({ a, b }));'); + }); + + it('spans lines and comments', () => { + expect(wrapFirstArray('f([\n a, // first\n /* second */ b,\n]);').output).toBe('f(wrap({ a, b }));'); + }); + + it('leaves an empty array alone without a skip', () => { + const { output, result, state } = wrapFirstArray('f([]);'); + expect(result).toBe(false); + expect(output).toBe('f([]);'); + expect(state.report.skipped).toEqual([]); + }); + + it.each([ + ['a call', 'f([getMiddleware()]);'], + ['a nested array', 'f([a, [b]]);'], + ['a spread', 'f([...middlewares]);'], + ['a hole', 'f([a, , b]);'], + ['a member expression', 'f([ns.a]);'], + ])('skips an array holding %s', (_, code) => { + const { output, result, state } = wrapFirstArray(code); + expect(result).toBe(false); + expect(output).toBe(code); + expect(state.report.skipped).toEqual(['middleware']); + expect(state.needsImport).toBe(false); + }); + + it('is not confused by a `]` inside a string elsewhere', () => { + expect(wrapFirstArray("f([a], ']');").output).toBe("f(wrap({ a }), ']');"); + }); +}); diff --git a/packages/bundler-plugins/test/rewriter/ast.test.ts b/packages/bundler-plugins/test/rewriter/ast.test.ts new file mode 100644 index 000000000000..561c1522f925 --- /dev/null +++ b/packages/bundler-plugins/test/rewriter/ast.test.ts @@ -0,0 +1,124 @@ +import { beforeAll, describe, expect, it } from 'vitest'; +import { + type BaseNode, + declaredNames, + directivesEnd, + exportedName, + type ExportNamedNode, + isAnonymousFunctionOrClass, + isCallToMethod, + isTypeOnlyExport, + walk, +} from '../../src/rewriter/ast'; +import { loadParser, parseModule } from '../../src/rewriter/parse'; + +beforeAll(async () => { + await loadParser(); +}); + +function firstStatement(code: string, id = 'module.ts'): BaseNode { + return parseModule(code, id).body[0]!; +} + +function expressionOf(code: string): BaseNode { + return (firstStatement(code) as BaseNode & { expression: BaseNode }).expression; +} + +describe('isCallToMethod', () => { + it('matches a bare call', () => { + expect(isCallToMethod(expressionOf('wrap(x);'), 'wrap')).toBe(true); + }); + + it('matches a member call', () => { + expect(isCallToMethod(expressionOf('Sentry.wrap(x);'), 'wrap')).toBe(true); + }); + + it('does not match another function or a non-call', () => { + expect(isCallToMethod(expressionOf('other(x);'), 'wrap')).toBe(false); + expect(isCallToMethod(expressionOf('wrap;'), 'wrap')).toBe(false); + }); +}); + +describe('isAnonymousFunctionOrClass', () => { + it.each([ + ['() => {}', true], + ['(function () {})', true], + ['(class {})', true], + ['(function named() {})', false], + ['(class Named {})', false], + ['({})', false], + ])('%s → %s', (code, expected) => { + expect(isAnonymousFunctionOrClass(expressionOf(`${code};`))).toBe(expected); + }); +}); + +describe('isTypeOnlyExport', () => { + it('detects `export type { X }`', () => { + expect(isTypeOnlyExport(firstStatement("export type { X } from './x';") as ExportNamedNode)).toBe(true); + }); + + it('detects an inline `type` specifier', () => { + const node = firstStatement("export { type X, Y } from './x';") as ExportNamedNode; + expect(isTypeOnlyExport(node)).toBe(false); + expect(node.specifiers!.map(isTypeOnlyExport)).toEqual([true, false]); + }); +}); + +describe('exportedName', () => { + it('reads identifier and string literal names', () => { + const node = firstStatement('export { a as b, c as "load" } from \'./x\';') as ExportNamedNode; + expect(node.specifiers!.map(specifier => exportedName(specifier.exported))).toEqual(['b', 'load']); + }); +}); + +describe('directivesEnd', () => { + it('is 0 without directives', () => { + expect(directivesEnd(parseModule('const a = 1;', 'module.js'))).toBe(0); + }); + + it('ends after the last directive', () => { + const code = '\'use strict\';\n"use server";\nconst a = 1;'; + expect(code.slice(0, directivesEnd(parseModule(code, 'module.js')))).toBe('\'use strict\';\n"use server";'); + }); + + it('ends after a hashbang', () => { + const code = '#!/usr/bin/env node\nconst a = 1;'; + expect(code.slice(0, directivesEnd(parseModule(code, 'module.js')))).toBe('#!/usr/bin/env node'); + }); + + it('ignores a string statement after other code', () => { + const code = "const a = 1;\n'use server';"; + expect(directivesEnd(parseModule(code, 'module.js'))).toBe(0); + }); +}); + +describe('declaredNames', () => { + it.each([ + ['export class A {}', ['A']], + ['export function a() {}', ['a']], + ['export const a = 1, b = 2;', ['a', 'b']], + ['export const { a, b: c, ...d } = x;', ['a', 'c', 'd']], + ['export const [a, [b], c = 1, ...d] = x;', ['a', 'b', 'c', 'd']], + ])('%s → %j', (code, expected) => { + expect(declaredNames((firstStatement(code) as ExportNamedNode).declaration!)).toEqual(expected); + }); + + it('is undefined for a declaration without a runtime binding', () => { + expect(declaredNames((firstStatement('export interface A {}') as ExportNamedNode).declaration!)).toBeUndefined(); + }); +}); + +describe('walk', () => { + it('visits nested nodes, parents first', () => { + const types: string[] = []; + walk(parseModule('f([a]);', 'module.js'), node => types.push(node.type)); + expect(types).toEqual([ + 'Program', + 'ExpressionStatement', + 'CallExpression', + 'Identifier', + 'ArrayExpression', + 'Identifier', + ]); + }); +}); diff --git a/packages/bundler-plugins/test/rewriter/class-extends.test.ts b/packages/bundler-plugins/test/rewriter/class-extends.test.ts new file mode 100644 index 000000000000..a9774c65ac46 --- /dev/null +++ b/packages/bundler-plugins/test/rewriter/class-extends.test.ts @@ -0,0 +1,70 @@ +import { beforeAll, describe, expect, it } from 'vitest'; +import { findClassesExtending } from '../../src/rewriter/class-extends'; +import { loadParser, parseModule } from '../../src/rewriter/parse'; + +beforeAll(async () => { + await loadParser(); +}); + +const BASE = { module: 'cloudflare:workers', name: 'WorkerEntrypoint' }; + +function find(code: string): Set { + return findClassesExtending(parseModule(code, 'module.js'), BASE); +} + +describe('findClassesExtending', () => { + it('finds a class extending the named import', () => { + const code = [ + "import { WorkerEntrypoint } from 'cloudflare:workers';", + 'export class A extends WorkerEntrypoint {}', + ]; + expect(find(code.join('\n'))).toEqual(new Set(['A'])); + }); + + it('follows an aliased import', () => { + const code = ["import { WorkerEntrypoint as WE } from 'cloudflare:workers';", 'class A extends WE {}']; + expect(find(code.join('\n'))).toEqual(new Set(['A'])); + }); + + it('finds a class extending a namespace member', () => { + const code = [ + "import * as cf from 'cloudflare:workers';", + 'class A extends cf.WorkerEntrypoint {}', + 'class B extends cf.Other {}', + ]; + expect(find(code.join('\n'))).toEqual(new Set(['A'])); + }); + + it('resolves an indirect chain declared out of order', () => { + const code = [ + "import { WorkerEntrypoint } from 'cloudflare:workers';", + 'class C extends B {}', + 'class B extends A {}', + 'class A extends WorkerEntrypoint {}', + ]; + expect(find(code.join('\n'))).toEqual(new Set(['A', 'B', 'C'])); + }); + + it('ignores the same name imported from another module', () => { + const code = ["import { WorkerEntrypoint } from 'elsewhere';", 'class A extends WorkerEntrypoint {}']; + expect(find(code.join('\n'))).toEqual(new Set()); + }); + + it.each([ + "import type { WorkerEntrypoint as WE } from 'cloudflare:workers';", + "import { type WorkerEntrypoint as WE } from 'cloudflare:workers';", + "import type * as WE from 'cloudflare:workers';", + ])('ignores the type-only import `%s`', typeImport => { + const code = [ + typeImport, + 'const WE = class {};', + 'class A extends WE {}', + 'class B extends WE.WorkerEntrypoint {}', + ]; + expect(findClassesExtending(parseModule(code.join('\n'), 'module.ts'), BASE)).toEqual(new Set()); + }); + + it('ignores classes without the base import', () => { + expect(find('class A extends B {}')).toEqual(new Set()); + }); +}); diff --git a/packages/bundler-plugins/test/rewriter/exports.test.ts b/packages/bundler-plugins/test/rewriter/exports.test.ts new file mode 100644 index 000000000000..545a0437a3d5 --- /dev/null +++ b/packages/bundler-plugins/test/rewriter/exports.test.ts @@ -0,0 +1,408 @@ +import { beforeAll, describe, expect, it } from 'vitest'; +import type { ExportDefaultNode, ExportNamedNode, ProgramBody } from '../../src/rewriter/ast'; +import { exportedName } from '../../src/rewriter/ast'; +import { + collectDeclaringStatements, + collectManuallyWrappedLocals, + collectTopLevelClasses, + findNamedExports, + wrapDefaultExport, + wrapDefaultReexport, + wrapDefaultSpecifier, + wrapForeignExport, + wrapInlineExport, + wrapLocalBinding, + wrapSpecifierExports, +} from '../../src/rewriter/exports'; +import { loadParser, parseModule } from '../../src/rewriter/parse'; +import { createRewriteState, type RewriteState } from '../../src/rewriter/rewriter'; + +beforeAll(async () => { + await loadParser(); +}); + +const wrap = (target: string): string => `wrap(${target})`; + +/** Runs `edit` on `code` and returns the result, which must still parse. */ +function rewrite(code: string, edit: (state: RewriteState, ast: ProgramBody) => void, id = 'module.ts'): string { + const ast = parseModule(code, id); + const state = createRewriteState(code); + edit(state, ast); + const output = state.ms.toString(); + expect(() => parseModule(output, id)).not.toThrow(); + return output; +} + +function defaultExportOf(ast: ProgramBody): ExportDefaultNode { + return ast.body.find(node => node.type === 'ExportDefaultDeclaration') as ExportDefaultNode; +} + +function namedExportsOf(ast: ProgramBody): ExportNamedNode[] { + return ast.body.filter(node => node.type === 'ExportNamedDeclaration') as ExportNamedNode[]; +} + +describe('collectors', () => { + const ast = parseModule( + [ + "import { imported } from './a';", + 'class Local {}', + 'export class Exported {}', + 'const handWrapped = wrap(Local);', + 'export const alsoHandWrapped = ns.wrap(Local), plain = 1;', + 'function fn() {}', + ].join('\n'), + 'module.js', + ); + + it('collects top-level classes, exported or not', () => { + expect([...collectTopLevelClasses(ast).keys()]).toEqual(['Local', 'Exported']); + }); + + it('maps each top-level binding to its declaring statement', () => { + const statements = collectDeclaringStatements(ast); + expect([...statements.keys()]).toEqual([ + 'imported', + 'Local', + 'Exported', + 'handWrapped', + 'alsoHandWrapped', + 'plain', + 'fn', + ]); + expect(statements.get('plain')).toBe(ast.body[4]); + }); + + it('maps destructured bindings to their declaring statement', () => { + const destructured = parseModule('const { a, b: [c, ...d] } = shared;', 'module.js'); + const statements = collectDeclaringStatements(destructured); + expect([...statements.keys()]).toEqual(['a', 'c', 'd']); + expect(statements.get('c')).toBe(destructured.body[0]); + }); + + it('skips type-only imports', () => { + const imports = parseModule("import type { a } from 'x';\nimport { type b, c } from 'y';", 'module.ts'); + expect([...collectDeclaringStatements(imports).keys()]).toEqual(['c']); + }); + + it('collects bindings assigned a call to a wrapper', () => { + expect(collectManuallyWrappedLocals(ast, ['wrap'])).toEqual(new Set(['handWrapped', 'alsoHandWrapped'])); + expect(collectManuallyWrappedLocals(ast, ['other'])).toEqual(new Set()); + }); +}); + +describe('findNamedExports', () => { + function find(code: string): string[] { + return findNamedExports(parseModule(code, 'module.ts'), 'load').map(node => code.slice(node.start, node.end)); + } + + it.each([ + 'export const load = () => {};', + 'export async function load() {}', + 'export let { load } = obj;', + 'export { load };', + 'export { other as load };', + 'export { other as "load" };', + "export { load } from './shared';", + ])('finds %s', code => { + expect(find(code)).toEqual([code]); + }); + + it.each([ + 'export const loader = () => {};', + 'export type { load };', + 'export { type load };', + 'export interface load {}', + 'const load = 1;', + 'export { load as other };', + ])('does not find %s', code => { + expect(find(code)).toEqual([]); + }); +}); + +describe('wrapLocalBinding', () => { + it('binds the wrapper after the declaration and reuses it', () => { + const output = rewrite('class A {}\nexport { A };', (state, ast) => { + expect(wrapLocalBinding(state, 'A', ast.body[0]!, wrap)).toBe('__SENTRY_WRAPPED_A__'); + expect(wrapLocalBinding(state, 'A', ast.body[0]!, wrap)).toBe('__SENTRY_WRAPPED_A__'); + expect(state.needsImport).toBe(true); + }); + expect(output).toBe('class A {}\nconst __SENTRY_WRAPPED_A__ = wrap(A);\n\nexport { A };'); + }); +}); + +describe('wrapInlineExport', () => { + it('wraps an exported class without renaming it', () => { + const output = rewrite('export class A {}', (state, ast) => { + expect(wrapInlineExport(state, namedExportsOf(ast)[0]!, 'A', wrap)).toBe(true); + }); + expect(output).toBe('export { __SENTRY_WRAPPED_A__ as A };\nclass A {}\nconst __SENTRY_WRAPPED_A__ = wrap(A);\n'); + }); + + it.each([ + ['@dec export class A {}', 'export { __SENTRY_WRAPPED_A__ as A };\n@dec class A {}'], + ['export @dec class A {}', 'export { __SENTRY_WRAPPED_A__ as A };\n@dec class A {}'], + ['export abstract class A {}', 'export { __SENTRY_WRAPPED_A__ as A };\nabstract class A {}'], + ])('keeps the class modifiers of `%s`', (code, expected) => { + const output = rewrite(code, (state, ast) => { + expect(wrapInlineExport(state, namedExportsOf(ast)[0]!, 'A', wrap)).toBe(true); + }); + expect(output).toBe(`${expected}\nconst __SENTRY_WRAPPED_A__ = wrap(A);\n`); + }); + + it('wraps an exported function', () => { + const output = rewrite('export async function load() {}', (state, ast) => { + wrapInlineExport(state, namedExportsOf(ast)[0]!, 'load', wrap); + }); + expect(output).toContain('async function load() {}'); + expect(output).toContain('const __SENTRY_WRAPPED_load__ = wrap(load);'); + expect(output).toContain('export { __SENTRY_WRAPPED_load__ as load };'); + }); + + it('keeps the other names of the same declaration exported', () => { + const output = rewrite('export const load = () => {}, prerender = true;', (state, ast) => { + wrapInlineExport(state, namedExportsOf(ast)[0]!, 'load', wrap); + }); + expect(output).toContain('const load = () => {}, prerender = true;'); + expect(output).toContain('export { __SENTRY_WRAPPED_load__ as load, prerender };'); + }); + + it('wraps two names of the same declaration', () => { + const output = rewrite('export const load = () => {}, actions = {};', (state, ast) => { + const node = namedExportsOf(ast)[0]!; + expect(wrapInlineExport(state, node, 'load', wrap)).toBe(true); + expect(wrapInlineExport(state, node, 'actions', wrap)).toBe(true); + }); + expect(output).toBe( + [ + 'export { __SENTRY_WRAPPED_load__ as load, __SENTRY_WRAPPED_actions__ as actions };', + 'const load = () => {}, actions = {};', + 'const __SENTRY_WRAPPED_load__ = wrap(load);', + '', + 'const __SENTRY_WRAPPED_actions__ = wrap(actions);', + '', + ].join('\n'), + ); + }); + + it('keeps TypeScript annotations', () => { + const output = rewrite('export const load: PageLoad = async () => ({});', (state, ast) => { + wrapInlineExport(state, namedExportsOf(ast)[0]!, 'load', wrap); + }); + expect(output).toContain('const load: PageLoad = async () => ({});'); + }); + + it('returns false when the declaration does not declare the name', () => { + const output = rewrite('export const other = 1;', (state, ast) => { + expect(wrapInlineExport(state, namedExportsOf(ast)[0]!, 'load', wrap)).toBe(false); + }); + expect(output).toBe('export const other = 1;'); + }); +}); + +describe('wrapSpecifierExports', () => { + function wrapNamed(code: string, name: string): string { + return rewrite(code, (state, ast) => { + const declaring = collectDeclaringStatements(ast); + for (const node of namedExportsOf(ast)) { + wrapSpecifierExports(state, node, (specifier, sourceLiteral, prelude) => { + const exported = exportedName(specifier.exported); + const local = exportedName(specifier.local); + if (exported !== name || !local) return undefined; + if (sourceLiteral) return wrapForeignExport(state, local, exported, sourceLiteral, prelude, wrap); + return `${wrapLocalBinding(state, local, declaring.get(local)!, wrap)} as ${exported}`; + }); + } + }); + } + + it('re-points a local specifier and keeps the others', () => { + const output = wrapNamed('function load() {}\nconst other = 1;\nexport { load, other };', 'load'); + expect(output).toBe( + [ + 'function load() {}', + 'const __SENTRY_WRAPPED_load__ = wrap(load);', + '', + 'const other = 1;', + 'export { __SENTRY_WRAPPED_load__ as load };', + 'export { other };', + ].join('\n'), + ); + }); + + it('re-points an aliased specifier', () => { + const output = wrapNamed('const impl = () => {};\nexport { impl as load };', 'load'); + expect(output).toContain('const __SENTRY_WRAPPED_impl__ = wrap(impl);'); + expect(output).toContain('export { __SENTRY_WRAPPED_impl__ as load };'); + }); + + it('re-points a string literal export name', () => { + const output = wrapNamed('const impl = () => {};\nexport { impl as "load" };', 'load'); + expect(output).toContain('export { __SENTRY_WRAPPED_impl__ as load };'); + }); + + it('binds a re-export under a private name', () => { + const output = wrapNamed("export { load, other } from './shared';", 'load'); + expect(output).toBe( + [ + "import { load as __SENTRY_REEXPORT_load__ } from './shared';", + 'const __SENTRY_WRAPPED_load__ = wrap(__SENTRY_REEXPORT_load__);', + 'export { __SENTRY_WRAPPED_load__ as load };', + "export { other } from './shared';", + ].join('\n'), + ); + }); + + it('wraps an imported binding that is exported again', () => { + const output = wrapNamed("import { load } from './shared';\nexport { load };", 'load'); + expect(output).toContain("import { load } from './shared';\nconst __SENTRY_WRAPPED_load__ = wrap(load);"); + }); + + it('leaves type-only exports alone', () => { + const code = "export type { load } from './types';\nexport { type load as other } from './types';"; + expect(wrapNamed(code, 'load')).toBe(code); + }); + + it('leaves the statement alone when nothing matches', () => { + const code = 'const a = 1;\nexport { a };'; + expect(wrapNamed(code, 'load')).toBe(code); + }); +}); + +describe('wrapDefaultExport', () => { + function wrapDefault(code: string): string { + return rewrite(code, (state, ast) => wrapDefaultExport(state, defaultExportOf(ast), wrap), 'module.js'); + } + + it('wraps an object-literal default export', () => { + expect(wrapDefault('export default { fetch() {} };')).toBe( + [ + 'var __SENTRY_DEFAULT_EXPORT__ = { fetch() {} };', + 'export { __SENTRY_DEFAULT_EXPORT__ as default };', + '__SENTRY_DEFAULT_EXPORT__ = wrap(__SENTRY_DEFAULT_EXPORT__);', + ].join('\n'), + ); + }); + + it('wraps a default export of an identifier', () => { + expect(wrapDefault('const handler = {};\nexport default handler;')).toContain( + 'var __SENTRY_DEFAULT_EXPORT__ = handler;', + ); + }); + + it('keeps a declared default class bound under its name', () => { + expect(wrapDefault('export default class Handler {}')).toBe( + [ + 'class Handler {}', + 'var __SENTRY_DEFAULT_EXPORT__ = Handler;', + 'export { __SENTRY_DEFAULT_EXPORT__ as default };', + '__SENTRY_DEFAULT_EXPORT__ = wrap(Handler);', + ].join('\n'), + ); + }); + + it('keeps the name `default` for an anonymous class', () => { + expect(wrapDefault('export default class {}')).toBe( + [ + 'var __SENTRY_DEFAULT_EXPORT__ = { default: class {} }.default;', + 'export { __SENTRY_DEFAULT_EXPORT__ as default };', + '__SENTRY_DEFAULT_EXPORT__ = wrap(__SENTRY_DEFAULT_EXPORT__);', + ].join('\n'), + ); + }); + + it('wraps an anonymous function without a trailing semicolon', () => { + expect(wrapDefault('export default function () {}')).toContain( + 'var __SENTRY_DEFAULT_EXPORT__ = { default: function () {} }.default;', + ); + }); + + it.each([ + [ + 'a block comment', + 'export /* default handler */ default /* the default */ { fetch() {} };', + 'var __SENTRY_DEFAULT_EXPORT__ = /* the default */ { fetch() {} };', + ], + [ + 'a line comment', + 'export // default handler\ndefault { fetch() {} };', + 'var __SENTRY_DEFAULT_EXPORT__ = { fetch() {} };', + ], + ])('finds the `default` keyword past %s that names it', (_, code, expected) => { + expect(wrapDefault(code)).toContain(expected); + }); + + it('re-points the default export at an existing wrapper binding', () => { + const output = rewrite( + 'class A {}\nexport default A;', + (state, ast) => { + wrapLocalBinding(state, 'A', ast.body[0]!, wrap); + wrapDefaultExport(state, defaultExportOf(ast), wrap); + }, + 'module.js', + ); + expect(output).toBe('class A {}\nconst __SENTRY_WRAPPED_A__ = wrap(A);\n\nexport default __SENTRY_WRAPPED_A__;'); + }); +}); + +describe('wrapDefaultSpecifier', () => { + it('binds the default where the local is declared and wraps it at the end', () => { + const output = rewrite( + 'const handler = {};\nexport { handler as default };', + (state, ast) => { + const statement = collectDeclaringStatements(ast).get('handler'); + wrapSpecifierExports(state, namedExportsOf(ast)[0]!, specifier => + wrapDefaultSpecifier(state, exportedName(specifier.local)!, statement, wrap), + ); + }, + 'module.js', + ); + expect(output).toBe( + [ + 'const handler = {};', + 'var __SENTRY_DEFAULT_EXPORT__ = handler;', + 'export { __SENTRY_DEFAULT_EXPORT__ as default };', + '__SENTRY_DEFAULT_EXPORT__ = wrap(handler);', + ].join('\n'), + ); + }); + + it('declares the binding at the end when the local has no declaring statement', () => { + const output = rewrite( + 'export { handler as default };\nvar handler = {};', + (state, ast) => { + wrapSpecifierExports(state, namedExportsOf(ast)[0]!, () => + wrapDefaultSpecifier(state, 'handler', undefined, wrap), + ); + }, + 'module.js', + ); + expect(output).toContain('var __SENTRY_DEFAULT_EXPORT__ = wrap(handler);'); + }); +}); + +describe('wrapDefaultReexport', () => { + it.each([ + ["export { default } from './handler';", "import __SENTRY_REEXPORT_default__ from './handler';"], + [ + "export { handler as default } from './handler';", + "import { handler as __SENTRY_REEXPORT_default__ } from './handler';", + ], + ])('wraps %s', (code, importStatement) => { + const output = rewrite( + code, + (state, ast) => { + wrapSpecifierExports(state, namedExportsOf(ast)[0]!, (specifier, sourceLiteral, prelude) => + wrapDefaultReexport(state, exportedName(specifier.local)!, sourceLiteral!, prelude, wrap), + ); + }, + 'module.js', + ); + expect(output).toBe( + [ + importStatement, + 'var __SENTRY_DEFAULT_EXPORT__ = wrap(__SENTRY_REEXPORT_default__);', + 'export { __SENTRY_DEFAULT_EXPORT__ as default };', + ].join('\n'), + ); + }); +}); diff --git a/packages/bundler-plugins/test/rewriter/imports.test.ts b/packages/bundler-plugins/test/rewriter/imports.test.ts new file mode 100644 index 000000000000..1b7e840201e1 --- /dev/null +++ b/packages/bundler-plugins/test/rewriter/imports.test.ts @@ -0,0 +1,58 @@ +import { beforeAll, describe, expect, it } from 'vitest'; +import { addImport, hasImport } from '../../src/rewriter/imports'; +import { loadParser, parseModule } from '../../src/rewriter/parse'; +import { createRewriteState } from '../../src/rewriter/rewriter'; + +beforeAll(async () => { + await loadParser(); +}); + +const IMPORT = "import { wrap } from 'sentry';"; + +function withImport(code: string): string { + const ast = parseModule(code, 'module.ts'); + const state = createRewriteState(code); + addImport(state, ast, IMPORT); + addImport(state, ast, IMPORT); + const output = state.ms.toString(); + expect(() => parseModule(output, 'module.ts')).not.toThrow(); + return output; +} + +describe('addImport', () => { + it('prepends the import once', () => { + expect(withImport('const foo = 1;')).toBe(`${IMPORT}\nconst foo = 1;`); + }); + + it("inserts after a 'use server' directive", () => { + expect(withImport("'use server';\nconst foo = 1;")).toBe(`'use server';\n${IMPORT}\nconst foo = 1;`); + }); + + it('inserts after a "use client" directive without a semicolon', () => { + expect(withImport('"use client"\nconst foo = 1;')).toBe(`"use client"\n${IMPORT}\nconst foo = 1;`); + }); + + it('inserts after several directives', () => { + expect(withImport("'use strict';\n'use server';\nconst foo = 1;")).toBe( + `'use strict';\n'use server';\n${IMPORT}\nconst foo = 1;`, + ); + }); + + it('inserts after a hashbang', () => { + expect(withImport('#!/usr/bin/env node\nconst foo = 1;')).toBe(`#!/usr/bin/env node\n${IMPORT}\nconst foo = 1;`); + }); +}); + +describe('hasImport', () => { + it.each([ + ["import { wrap } from 'sentry';", true], + ["import { other, wrap } from 'sentry';", true], + ["import { wrap as alias } from 'sentry';", false], + ["import { wrap } from 'elsewhere';", false], + ["import type { wrap } from 'sentry';", false], + ["import { type wrap } from 'sentry';", false], + ["import * as wrap from 'sentry';", false], + ])('%s → %s', (code, expected) => { + expect(hasImport(parseModule(code, 'module.ts'), 'sentry', 'wrap')).toBe(expected); + }); +}); diff --git a/packages/bundler-plugins/test/rewriter/module-shape.test.ts b/packages/bundler-plugins/test/rewriter/module-shape.test.ts new file mode 100644 index 000000000000..13ebf2981c69 --- /dev/null +++ b/packages/bundler-plugins/test/rewriter/module-shape.test.ts @@ -0,0 +1,118 @@ +import { beforeAll, describe, expect, it } from 'vitest'; +import { shapeFromAst, shapeFromSource } from '../../src/rewriter/module-shape'; +import { loadParser, parseModule } from '../../src/rewriter/parse'; + +beforeAll(async () => { + await loadParser(); +}); + +describe('shapeFromAst', () => { + it('collects classes with their superclass', () => { + const shape = shapeFromAst( + parseModule(['class A extends B {}', 'export class C extends ns.D {}', 'class E {}'].join('\n'), 'module.js'), + ); + expect(shape.classes).toEqual( + new Map([ + ['A', { kind: 'identifier', name: 'B' }], + ['C', { kind: 'member', object: 'ns', property: 'D' }], + ['E', undefined], + ]), + ); + }); + + it('collects named, default and namespace imports', () => { + const shape = shapeFromAst( + parseModule("import Def, { a as b, c } from 'm';\nimport * as ns from 'n';", 'module.js'), + ); + expect(shape.imports).toEqual( + new Map([ + ['Def', { source: 'm', imported: 'default' }], + ['b', { source: 'm', imported: 'a' }], + ['c', { source: 'm', imported: 'c' }], + ]), + ); + expect(shape.namespaces).toEqual(new Map([['ns', 'n']])); + }); + + it('collects local exports, re-exports and star exports', () => { + const shape = shapeFromAst( + parseModule( + [ + 'class A {}', + 'export { A as B };', + 'export { x as y, z as "w" } from \'./r\';', + "export * from './s';", + "export * as ns from './t';", + ].join('\n'), + 'module.js', + ), + ); + expect(shape.localExports).toEqual(new Map([['B', 'A']])); + expect(shape.reexports).toEqual( + new Map([ + ['y', { source: './r', imported: 'x' }], + ['w', { source: './r', imported: 'z' }], + ]), + ); + expect(shape.starExports).toEqual(['./s']); + }); + + it('records a declared default class', () => { + const shape = shapeFromAst(parseModule('export default class A extends B {}', 'module.js')); + expect(shape.defaultExportIsClass).toBe(true); + expect(shape.defaultExportSuper).toEqual({ kind: 'identifier', name: 'B' }); + expect(shape.classes.has('A')).toBe(true); + }); + + it('records an anonymous default class', () => { + const shape = shapeFromAst(parseModule('export default class extends B {}', 'module.js')); + expect(shape.defaultExportIsClass).toBe(true); + expect(shape.defaultExportSuper).toEqual({ kind: 'identifier', name: 'B' }); + }); + + it('records a default export of an identifier', () => { + const shape = shapeFromAst(parseModule('class A {}\nexport default A;', 'module.js')); + expect(shape.defaultExportName).toBe('A'); + expect(shape.defaultExportIsClass).toBeUndefined(); + }); +}); + +describe('shapeFromSource', () => { + it('reads generic and abstract TypeScript classes', () => { + const code = [ + "import { Agent } from 'agents';", + 'interface Props { name: string }', + 'export abstract class Base> extends Agent {', + ' private field?: T;', + '}', + ].join('\n'); + const shape = shapeFromSource(code, '/app/base.ts'); + expect(shape?.classes).toEqual(new Map([['Base', { kind: 'identifier', name: 'Agent' }]])); + expect(shape?.imports).toEqual(new Map([['Agent', { source: 'agents', imported: 'Agent' }]])); + }); + + it('skips type-only imports and exports', () => { + const code = [ + "import type { A } from './a';", + "import { type B, C } from './b';", + "export type { D } from './d';", + "export { type E, F } from './e';", + "export type * from './g';", + ].join('\n'); + const shape = shapeFromSource(code, '/app/mod.ts'); + expect([...shape!.imports.keys()]).toEqual(['C']); + expect([...shape!.reexports.keys()]).toEqual(['F']); + expect(shape!.starExports).toEqual([]); + }); + + it.each([ + ['TypeScript', "import { Agent } from 'agents';\nexport class Base extends Agent {}"], + ['JSX', "import { Agent } from 'agents';\nconst el =
;\nexport class Base extends Agent {}"], + ])('reads %s from a module whose id names JavaScript', (_, code) => { + expect(shapeFromSource(code, '/app/base.js')?.classes.get('Base')).toEqual({ kind: 'identifier', name: 'Agent' }); + }); + + it('returns undefined for code that does not parse', () => { + expect(shapeFromSource('this is ) not ( javascript', '/app/broken.js')).toBeUndefined(); + }); +}); diff --git a/packages/bundler-plugins/test/rewriter/parse.test.ts b/packages/bundler-plugins/test/rewriter/parse.test.ts new file mode 100644 index 000000000000..51765d09afd4 --- /dev/null +++ b/packages/bundler-plugins/test/rewriter/parse.test.ts @@ -0,0 +1,69 @@ +import { beforeAll, describe, expect, it, vi } from 'vitest'; +import { bundlerParser, langFromId, loadParser, parseModule } from '../../src/rewriter/parse'; + +beforeAll(async () => { + await loadParser(); +}); + +describe('langFromId', () => { + it.each([ + ['/a/b.js', 'js'], + ['/a/b.mjs', 'js'], + ['/a/b.cjs', 'js'], + ['/a/b.jsx', 'jsx'], + ['/a/b.ts', 'ts'], + ['/a/b.mts', 'ts'], + ['/a/b.cts', 'ts'], + ['/a/b.tsx', 'tsx'], + ['/a/b.ts?v=123', 'ts'], + ['/a/b.tsx#hash', 'tsx'], + ['/a/b.svelte', 'js'], + ['virtual:module', 'js'], + ])('%s → %s', (id, lang) => { + expect(langFromId(id)).toBe(lang); + }); +}); + +describe('parseModule', () => { + it('returns an ESTree program with offsets', () => { + const code = 'export const a = 1;'; + const program = parseModule(code, 'a.js'); + const [statement] = program.body; + expect(statement).toMatchObject({ type: 'ExportNamedDeclaration', start: 0, end: code.length }); + }); + + it('parses TypeScript for a .ts id', () => { + expect(() => parseModule('const a: number = 1;', 'a.ts')).not.toThrow(); + }); + + it('rejects TypeScript for a .js id', () => { + expect(() => parseModule('const a: number = 1;', 'a.js')).toThrow(); + }); + + it('parses JSX for a .tsx id', () => { + expect(() => parseModule('const a =
;', 'a.tsx')).not.toThrow(); + }); + + it('throws on a syntax error', () => { + expect(() => parseModule('const a = (', 'a.js')).toThrow(); + }); +}); + +describe('bundlerParser', () => { + it("parses with Rolldown's `this.parse`, in the dialect the id names", () => { + const parse = vi.fn((input: string) => parseModule(input, 'module.ts')); + const parser = bundlerParser({ meta: { rolldownVersion: '1.2.11' }, parse }); + + parser!('const a: number = 1;', '/app/a.mts?v=1'); + expect(parse).toHaveBeenCalledWith('const a: number = 1;', { lang: 'ts', preserveParens: false }); + }); + + it('is undefined for Rollup, whose `this.parse` cannot read TypeScript', () => { + expect(bundlerParser({ meta: {}, parse: vi.fn() })).toBeUndefined(); + }); + + it('is undefined without a context or a parse function', () => { + expect(bundlerParser(undefined)).toBeUndefined(); + expect(bundlerParser({ meta: { rolldownVersion: '1.2.11' } })).toBeUndefined(); + }); +}); diff --git a/packages/bundler-plugins/test/rewriter/parser-loading.test.ts b/packages/bundler-plugins/test/rewriter/parser-loading.test.ts new file mode 100644 index 000000000000..ac20344c4ab0 --- /dev/null +++ b/packages/bundler-plugins/test/rewriter/parser-loading.test.ts @@ -0,0 +1,39 @@ +import { describe, expect, it, vi } from 'vitest'; + +const { gate } = vi.hoisted(() => { + let release = (): void => {}; + const promise = new Promise(resolve => { + release = resolve; + }); + return { gate: { promise, release: () => release() } }; +}); + +vi.mock('oxc-parser', async importOriginal => { + await gate.promise; + return importOriginal(); +}); + +describe('the rewriter while `oxc-parser` loads', () => { + it('waits for it on the first transform and stays synchronous after', async () => { + const { createCallSiteRewriter, isParserLoading, wrapArrayLiteral, walk } = await import('../../src/rewriter'); + const rewriter = createCallSiteRewriter([ + { + name: 'arrays', + include: {}, + apply: ({ ast, state }) => + walk(ast, node => { + if (node.type === 'ArrayExpression') wrapArrayLiteral(state, node, 'array', names => names.join()); + }), + }, + ]); + + expect(isParserLoading()).toBe(true); + const pending = rewriter.transform('f([a]);', '/app/a.ts'); + expect(pending).toBeInstanceOf(Promise); + + gate.release(); + expect((await pending)?.code).toBe('f(a);'); + expect(isParserLoading()).toBe(false); + expect(rewriter.transform('f([b]);', '/app/b.ts')).toEqual(expect.objectContaining({ code: 'f(b);' })); + }); +}); diff --git a/packages/bundler-plugins/test/rewriter/parser-unavailable.test.ts b/packages/bundler-plugins/test/rewriter/parser-unavailable.test.ts new file mode 100644 index 000000000000..cc041c249195 --- /dev/null +++ b/packages/bundler-plugins/test/rewriter/parser-unavailable.test.ts @@ -0,0 +1,55 @@ +import { afterEach, describe, expect, it, vi } from 'vitest'; + +vi.mock('oxc-parser', () => { + throw new Error('Cannot find native binding.'); +}); + +const MESSAGE = + '[@sentry/bundler-plugins] Could not load `oxc-parser` for this platform. ' + + 'Modules that need it will not be auto-instrumented.'; + +describe('the rewriter without `oxc-parser`', () => { + afterEach(() => { + vi.restoreAllMocks(); + }); + + it('leaves modules unchanged and warns once', async () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); + const { createCallSiteRewriter, loadParser, shapeFromSource, wrapArrayLiteral, walk } = + await import('../../src/rewriter'); + const rewriter = createCallSiteRewriter([ + { + name: 'arrays', + include: {}, + apply: ({ ast, state }) => + walk(ast, node => { + if (node.type === 'ArrayExpression') wrapArrayLiteral(state, node, 'array', names => names.join()); + }), + }, + ]); + + // A transform that starts while the import is still pending waits for it. + expect(await rewriter.transform('f([a]);', '/app/a.ts')).toBeNull(); + await expect(loadParser()).resolves.toBe(false); + expect(rewriter.transform('f([b]);', '/app/b.ts')).toBeNull(); + expect(shapeFromSource('export class A {}', '/app/c.ts')).toBeUndefined(); + + expect(warn).toHaveBeenCalledTimes(1); + expect(warn).toHaveBeenCalledWith(MESSAGE); + }); + + it("still parses with Rolldown's `this.parse`", async () => { + vi.spyOn(console, 'warn').mockImplementation(() => {}); + const { createCallSiteRewriter, loadParser } = await import('../../src/rewriter'); + const { parseAst } = await import('rolldown/parseAst'); + await loadParser(); + + const rewriter = createCallSiteRewriter([ + { name: 'edit', include: {}, apply: ({ state }) => void state.ms.append('\n// edited') }, + ]); + const context = { meta: { rolldownVersion: '1.2.11' }, parse: parseAst }; + expect(rewriter.transform('const a: number = 1;', '/app/a.ts', context)).toEqual( + expect.objectContaining({ code: 'const a: number = 1;\n// edited' }), + ); + }); +}); diff --git a/packages/bundler-plugins/test/rewriter/report.test.ts b/packages/bundler-plugins/test/rewriter/report.test.ts new file mode 100644 index 000000000000..3d899b5c0e0c --- /dev/null +++ b/packages/bundler-plugins/test/rewriter/report.test.ts @@ -0,0 +1,18 @@ +import { describe, expect, it } from 'vitest'; +import { createReport, formatReport } from '../../src/rewriter/report'; + +describe('formatReport', () => { + it('is undefined when nothing was skipped', () => { + const report = createReport(); + report.wrapped.push('a'); + expect(formatReport(report, '/app/a.ts')).toBeUndefined(); + }); + + it('names the skipped sites and the module', () => { + const report = createReport(); + report.skipped.push('requestMiddleware', 'functionMiddleware'); + expect(formatReport(report, '/app/start.ts')).toBe( + '[Sentry] Could not auto-instrument requestMiddleware and functionMiddleware in /app/start.ts.', + ); + }); +}); diff --git a/packages/bundler-plugins/test/rewriter/rewriter.test.ts b/packages/bundler-plugins/test/rewriter/rewriter.test.ts new file mode 100644 index 000000000000..935d0aad841f --- /dev/null +++ b/packages/bundler-plugins/test/rewriter/rewriter.test.ts @@ -0,0 +1,138 @@ +import { beforeAll, describe, expect, it, vi } from 'vitest'; +import { addImport } from '../../src/rewriter/imports'; +import { wrapArrayLiteral } from '../../src/rewriter/arrays'; +import { type BaseNode, walk } from '../../src/rewriter/ast'; +import { loadParser, parseModule } from '../../src/rewriter/parse'; +import { createCallSiteRewriter, type RewriteRule, type RuleContext } from '../../src/rewriter/rewriter'; +import { parseAst } from 'rolldown/parseAst'; + +beforeAll(async () => { + await loadParser(); +}); + +function wrapArrays(ctx: RuleContext): void { + walk(ctx.ast, node => { + if (node.type === 'ArrayExpression') { + wrapArrayLiteral(ctx.state, node, 'array', names => `wrap({ ${names.join(', ')} })`); + } + }); + if (ctx.state.needsImport) addImport(ctx.state, ctx.ast, "import { wrap } from 'sentry';"); +} + +const arrayRule: RewriteRule = { name: 'arrays', include: { id: /\.ts$/, contains: ['['] }, apply: wrapArrays }; + +describe('createCallSiteRewriter', () => { + it('rewrites a matching module with a source map', () => { + const result = createCallSiteRewriter([arrayRule]).transform('f([a]);', '/app/a.ts'); + expect(result).not.toBeInstanceOf(Promise); + const { code, map } = result as { code: string; map: { mappings: string } }; + expect(code).toBe("import { wrap } from 'sentry';\nf(wrap({ a }));"); + expect(map.mappings).not.toBe(''); + }); + + it('returns null when nothing changed', () => { + expect(createCallSiteRewriter([arrayRule]).transform('f([]);', '/app/a.ts')).toBeNull(); + }); + + it.each([ + ['the id does not match', 'f([a]);', '/app/a.css'], + ['the source lacks a substring', 'f(a);', '/app/a.ts'], + ])('does not parse when %s', (_, code, id) => { + const parse = vi.fn(parseModule); + expect(createCallSiteRewriter([arrayRule], { parse }).transform(code, id)).toBeNull(); + expect(parse).not.toHaveBeenCalled(); + }); + + it('matches on the basename', () => { + const rule: RewriteRule = { ...arrayRule, include: { basename: /^\+page\.ts$/ } }; + const rewriter = createCallSiteRewriter([rule]); + expect(rewriter.transform('f([a]);', '/app/routes/+page.ts')).not.toBeNull(); + expect(rewriter.transform('f([a]);', '/app/+page.ts/other.ts')).toBeNull(); + }); + + it('returns null when the module does not parse', () => { + expect(createCallSiteRewriter([arrayRule]).transform('f([a);', '/app/a.ts')).toBeNull(); + }); + + it('uses the given parser', () => { + const parse = vi.fn(parseModule); + createCallSiteRewriter([arrayRule], { parse }).transform('f([a]);', '/app/a.ts'); + expect(parse).toHaveBeenCalledWith('f([a]);', '/app/a.ts'); + }); + + it("parses with Rolldown's `this.parse` when the context is Rolldown's", () => { + const parse = vi.fn(parseAst); + const context = { meta: { rolldownVersion: '1.2.11' }, parse }; + const code = 'const a: string[] = [];\nf([a]);'; + + const result = createCallSiteRewriter([arrayRule]).transform(code, '/app/a.ts', context); + expect(parse).toHaveBeenCalledWith(code, { lang: 'ts', preserveParens: false }); + expect((result as { code: string }).code).toBe( + (createCallSiteRewriter([arrayRule]).transform(code, '/app/a.ts') as { code: string }).code, + ); + }); + + it("does not use Rollup's `this.parse`", () => { + const parse = vi.fn(); + createCallSiteRewriter([arrayRule]).transform('f([a]);', '/app/a.ts', { meta: {}, parse }); + expect(parse).not.toHaveBeenCalled(); + }); + + it('prefers the parser given in the options over the context', () => { + const parse = vi.fn(parseModule); + const contextParse = vi.fn(); + createCallSiteRewriter([arrayRule], { parse }).transform('f([a]);', '/app/a.ts', { + meta: { rolldownVersion: '1.2.11' }, + parse: contextParse, + }); + expect(parse).toHaveBeenCalled(); + expect(contextParse).not.toHaveBeenCalled(); + }); + + it('runs every matching rule on one parse and one set of edits', () => { + const parse = vi.fn(parseModule); + const second: RewriteRule = { + name: 'second', + include: {}, + apply: ({ state, ast }) => addImport(state, ast, "import 'second';"), + }; + const result = createCallSiteRewriter([arrayRule, second], { parse }).transform('f([a]);', '/app/a.ts'); + expect(parse).toHaveBeenCalledTimes(1); + expect((result as { code: string }).code).toBe("import { wrap } from 'sentry';\nimport 'second';\nf(wrap({ a }));"); + }); + + it('returns a promise once a rule is async, and runs the later rules after it', async () => { + const order: string[] = []; + const rules: RewriteRule[] = [ + { + name: 'async', + include: {}, + apply: async () => { + await Promise.resolve(); + order.push('async'); + }, + }, + { name: 'sync', include: {}, apply: ctx => (order.push('sync'), wrapArrays(ctx)) }, + ]; + const result = createCallSiteRewriter(rules).transform('f([a]);', '/app/a.ts'); + expect(result).toBeInstanceOf(Promise); + expect((await result)?.code).toContain('wrap({ a })'); + expect(order).toEqual(['async', 'sync']); + }); + + it('warns about skipped sites, also when nothing changed', () => { + const warn = vi.fn(); + const result = createCallSiteRewriter([arrayRule], { logger: { warn } }).transform('f([g()]);', '/app/a.ts'); + expect(result).toBeNull(); + expect(warn).toHaveBeenCalledWith('[Sentry] Could not auto-instrument array in /app/a.ts.'); + }); + + it('hands each rule the module', () => { + let seen: Partial = {}; + const rule: RewriteRule = { name: 'spy', include: {}, apply: ctx => void (seen = ctx) }; + createCallSiteRewriter([rule]).transform('const a = 1;', '/app/a.ts'); + expect(seen.code).toBe('const a = 1;'); + expect(seen.id).toBe('/app/a.ts'); + expect((seen.ast?.body[0] as BaseNode).type).toBe('VariableDeclaration'); + }); +});