@sentry/bundler-plugins 11.19.0 → 11.20.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/build/cjs/core/version.js +1 -1
- package/build/cjs/core/version.js.map +1 -1
- package/build/cjs/rewriter/arrays.js +25 -0
- package/build/cjs/rewriter/arrays.js.map +1 -0
- package/build/cjs/rewriter/ast.js +102 -0
- package/build/cjs/rewriter/ast.js.map +1 -0
- package/build/cjs/rewriter/class-extends.js +67 -0
- package/build/cjs/rewriter/class-extends.js.map +1 -0
- package/build/cjs/rewriter/exports.js +241 -0
- package/build/cjs/rewriter/exports.js.map +1 -0
- package/build/cjs/rewriter/imports.js +22 -0
- package/build/cjs/rewriter/imports.js.map +1 -0
- package/build/cjs/rewriter/index.js +45 -0
- package/build/cjs/rewriter/module-shape.js +120 -0
- package/build/cjs/rewriter/module-shape.js.map +1 -0
- package/build/cjs/rewriter/parse.js +64 -0
- package/build/cjs/rewriter/parse.js.map +1 -0
- package/build/cjs/rewriter/report.js +17 -0
- package/build/cjs/rewriter/report.js.map +1 -0
- package/build/cjs/rewriter/rewriter.js +68 -0
- package/build/cjs/rewriter/rewriter.js.map +1 -0
- package/build/esm/core/version.js +1 -1
- package/build/esm/core/version.js.map +1 -1
- package/build/esm/package.json +1 -1
- package/build/esm/rewriter/arrays.js +25 -0
- package/build/esm/rewriter/arrays.js.map +1 -0
- package/build/esm/rewriter/ast.js +95 -0
- package/build/esm/rewriter/ast.js.map +1 -0
- package/build/esm/rewriter/class-extends.js +67 -0
- package/build/esm/rewriter/class-extends.js.map +1 -0
- package/build/esm/rewriter/exports.js +231 -0
- package/build/esm/rewriter/exports.js.map +1 -0
- package/build/esm/rewriter/imports.js +21 -0
- package/build/esm/rewriter/imports.js.map +1 -0
- package/build/esm/rewriter/index.js +11 -0
- package/build/esm/rewriter/module-shape.js +118 -0
- package/build/esm/rewriter/module-shape.js.map +1 -0
- package/build/esm/rewriter/parse.js +60 -0
- package/build/esm/rewriter/parse.js.map +1 -0
- package/build/esm/rewriter/report.js +16 -0
- package/build/esm/rewriter/report.js.map +1 -0
- package/build/esm/rewriter/rewriter.js +65 -0
- package/build/esm/rewriter/rewriter.js.map +1 -0
- package/build/types/core/version.d.ts +1 -1
- package/build/types/rewriter/arrays.d.ts +12 -0
- package/build/types/rewriter/arrays.d.ts.map +1 -0
- package/build/types/rewriter/ast.d.ts +120 -0
- package/build/types/rewriter/ast.d.ts.map +1 -0
- package/build/types/rewriter/class-extends.d.ts +16 -0
- package/build/types/rewriter/class-extends.d.ts.map +1 -0
- package/build/types/rewriter/exports.d.ts +88 -0
- package/build/types/rewriter/exports.d.ts.map +1 -0
- package/build/types/rewriter/imports.d.ts +7 -0
- package/build/types/rewriter/imports.d.ts.map +1 -0
- package/build/types/rewriter/index.d.ts +10 -0
- package/build/types/rewriter/index.d.ts.map +1 -0
- package/build/types/rewriter/module-shape.d.ts +47 -0
- package/build/types/rewriter/module-shape.d.ts.map +1 -0
- package/build/types/rewriter/parse.d.ts +27 -0
- package/build/types/rewriter/parse.d.ts.map +1 -0
- package/build/types/rewriter/report.d.ts +12 -0
- package/build/types/rewriter/report.d.ts.map +1 -0
- package/build/types/rewriter/rewriter.d.ts +64 -0
- package/build/types/rewriter/rewriter.d.ts.map +1 -0
- package/package.json +9 -4
|
@@ -0,0 +1,231 @@
|
|
|
1
|
+
import { declarationOf, declaredNames, exportedName, isAnonymousFunctionOrClass, isCallToMethod, isTypeOnlyExport } from "./ast.js";
|
|
2
|
+
// src/rewriter/exports.ts
|
|
3
|
+
/** Specifier name a `export { default as X } from '...'` re-export uses for the source's default. */
|
|
4
|
+
const DEFAULT_IMPORT = "default";
|
|
5
|
+
/** Top-level class declarations, exported or not, by name. */
|
|
6
|
+
function collectTopLevelClasses(ast) {
|
|
7
|
+
const classes = /* @__PURE__ */ new Map();
|
|
8
|
+
for (const node of ast.body) {
|
|
9
|
+
const declaration = declarationOf(node);
|
|
10
|
+
if (declaration?.type !== "ClassDeclaration") continue;
|
|
11
|
+
const classNode = declaration;
|
|
12
|
+
if (classNode.id?.name) classes.set(classNode.id.name, classNode);
|
|
13
|
+
}
|
|
14
|
+
return classes;
|
|
15
|
+
}
|
|
16
|
+
/** Top-level value binding name → the statement that declares it. */
|
|
17
|
+
function collectDeclaringStatements(ast) {
|
|
18
|
+
const statements = /* @__PURE__ */ new Map();
|
|
19
|
+
for (const node of ast.body) {
|
|
20
|
+
const declaration = declarationOf(node);
|
|
21
|
+
if (!declaration) continue;
|
|
22
|
+
const names = declaration.type === "ImportDeclaration" ? valueImportNames(declaration) : declaredNames(declaration) ?? [];
|
|
23
|
+
for (const name of names) if (name) statements.set(name, node);
|
|
24
|
+
}
|
|
25
|
+
return statements;
|
|
26
|
+
}
|
|
27
|
+
function valueImportNames(node) {
|
|
28
|
+
if (node.importKind === "type") return [];
|
|
29
|
+
return (node.specifiers ?? []).filter((specifier) => specifier.importKind !== "type").map((specifier) => specifier.local?.name);
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* Top-level bindings already assigned the result of one of `wrapperNames`
|
|
33
|
+
* (`const X = wrap(...)`), so exporting one must not wrap it a second time.
|
|
34
|
+
*/
|
|
35
|
+
function collectManuallyWrappedLocals(ast, wrapperNames) {
|
|
36
|
+
const locals = /* @__PURE__ */ new Set();
|
|
37
|
+
for (const node of ast.body) {
|
|
38
|
+
const declaration = declarationOf(node);
|
|
39
|
+
if (declaration?.type !== "VariableDeclaration") continue;
|
|
40
|
+
for (const declarator of declaration.declarations ?? []) {
|
|
41
|
+
const name = declarator.id?.type === "Identifier" ? declarator.id.name : void 0;
|
|
42
|
+
const init = declarator.init;
|
|
43
|
+
if (name && init && wrapperNames.some((wrapper) => isCallToMethod(init, wrapper))) locals.add(name);
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
return locals;
|
|
47
|
+
}
|
|
48
|
+
/** The value export statements (`export const`, `export { }`) that export `name`. */
|
|
49
|
+
function findNamedExports(ast, name) {
|
|
50
|
+
const found = [];
|
|
51
|
+
for (const node of ast.body) {
|
|
52
|
+
if (node.type !== "ExportNamedDeclaration" || isTypeOnlyExport(node)) continue;
|
|
53
|
+
const exportNode = node;
|
|
54
|
+
if (exportNode.declaration ? !!declaredNames(exportNode.declaration)?.includes(name) : (exportNode.specifiers ?? []).some((specifier) => !isTypeOnlyExport(specifier) && exportedName(specifier.exported) === name)) found.push(exportNode);
|
|
55
|
+
}
|
|
56
|
+
return found;
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* Wrap a binding declared in this module and return the binding that holds the wrapper.
|
|
60
|
+
*
|
|
61
|
+
* The declaration is left exactly as written, so a class or function keeps its
|
|
62
|
+
* `Function.prototype.name`. Only the *export* has to become the wrapper, so the wrapper gets its
|
|
63
|
+
* own binding and the export is aliased to it.
|
|
64
|
+
*/
|
|
65
|
+
function wrapLocalBinding(state, localName, declaringNode, wrap) {
|
|
66
|
+
const existing = state.wrappedLocals.get(localName);
|
|
67
|
+
if (existing) return existing;
|
|
68
|
+
const wrappedName = `__SENTRY_WRAPPED_${localName}__`;
|
|
69
|
+
state.wrappedLocals.set(localName, wrappedName);
|
|
70
|
+
state.ms.appendLeft(declaringNode.end, `\nconst ${wrappedName} = ${wrap(localName)};\n`);
|
|
71
|
+
state.needsImport = true;
|
|
72
|
+
return wrappedName;
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* Wrap `localName` where an inline export declares it (`export class X {}`,
|
|
76
|
+
* `export const x = ...`, `export function x() {}`). The `export` keyword is
|
|
77
|
+
* replaced by an export clause that aliases the name to the wrapper. Other
|
|
78
|
+
* names the same declaration exports are exported again, through their
|
|
79
|
+
* wrapper when a later call wraps them too.
|
|
80
|
+
*
|
|
81
|
+
* @returns whether the declaration exports `localName`
|
|
82
|
+
*/
|
|
83
|
+
function wrapInlineExport(state, exportNode, localName, wrap) {
|
|
84
|
+
const declaration = exportNode.declaration;
|
|
85
|
+
const names = declaration ? declaredNames(declaration) : void 0;
|
|
86
|
+
if (!declaration || !names?.includes(localName)) return false;
|
|
87
|
+
wrapLocalBinding(state, localName, declaration, wrap);
|
|
88
|
+
const specifiers = names.map((name) => {
|
|
89
|
+
const wrappedName = state.wrappedLocals.get(name);
|
|
90
|
+
return wrappedName ? `${wrappedName} as ${name}` : name;
|
|
91
|
+
});
|
|
92
|
+
const decoratorStart = declaration.decorators?.[0]?.start ?? exportNode.start;
|
|
93
|
+
const start = Math.min(decoratorStart, exportNode.start);
|
|
94
|
+
const decorators = state.ms.original.slice(start, exportNode.start);
|
|
95
|
+
state.ms.overwrite(start, declaration.start, `export { ${specifiers.join(", ")} };\n${decorators}`);
|
|
96
|
+
return true;
|
|
97
|
+
}
|
|
98
|
+
/**
|
|
99
|
+
* Wrap the specifiers of an `export { ... }` statement that `wrapSpecifier` picks.
|
|
100
|
+
*
|
|
101
|
+
* Each such specifier is re-pointed at a binding holding the wrapper, which means rebuilding the
|
|
102
|
+
* statement; the other specifiers are carried over verbatim. A binding that lives in **another**
|
|
103
|
+
* module is first bound under a private name (see {@link wrapForeignExport}), since an import
|
|
104
|
+
* binding cannot be reassigned and the `from` form has no local binding at all.
|
|
105
|
+
*/
|
|
106
|
+
function wrapSpecifierExports(state, node, wrapSpecifier) {
|
|
107
|
+
const specifiers = node.specifiers ?? [];
|
|
108
|
+
if (specifiers.length === 0 || isTypeOnlyExport(node)) return;
|
|
109
|
+
const sourceLiteral = node.source ? state.ms.original.slice(node.source.start, node.source.end) : void 0;
|
|
110
|
+
const prelude = [];
|
|
111
|
+
const wrappedPairs = [];
|
|
112
|
+
const kept = [];
|
|
113
|
+
for (const specifier of specifiers) {
|
|
114
|
+
const pair = isTypeOnlyExport(specifier) ? void 0 : wrapSpecifier(specifier, sourceLiteral, prelude);
|
|
115
|
+
if (pair) wrappedPairs.push(pair);
|
|
116
|
+
else kept.push(state.ms.original.slice(specifier.start, specifier.end));
|
|
117
|
+
}
|
|
118
|
+
if (wrappedPairs.length === 0) return;
|
|
119
|
+
const statements = [...prelude, `export { ${wrappedPairs.join(", ")} };`];
|
|
120
|
+
if (kept.length > 0) {
|
|
121
|
+
const clause = `export { ${kept.join(", ")} }`;
|
|
122
|
+
statements.push(sourceLiteral ? `${clause} from ${sourceLiteral};` : `${clause};`);
|
|
123
|
+
}
|
|
124
|
+
state.ms.overwrite(node.start, node.end, statements.join("\n"));
|
|
125
|
+
}
|
|
126
|
+
/**
|
|
127
|
+
* Wrap a binding that comes from another module: imported and re-exported
|
|
128
|
+
* (`sourceLiteral` undefined), or re-exported directly (`export { x } from`).
|
|
129
|
+
* Pushes the statements that bind the wrapper onto `prelude` and returns the
|
|
130
|
+
* pair to export.
|
|
131
|
+
*/
|
|
132
|
+
function wrapForeignExport(state, localName, exportedAs, sourceLiteral, prelude, wrap) {
|
|
133
|
+
let target = localName;
|
|
134
|
+
if (sourceLiteral) {
|
|
135
|
+
target = `__SENTRY_REEXPORT_${exportedAs}__`;
|
|
136
|
+
prelude.push(importAs(localName, target, sourceLiteral));
|
|
137
|
+
}
|
|
138
|
+
const wrappedName = `__SENTRY_WRAPPED_${exportedAs}__`;
|
|
139
|
+
prelude.push(`const ${wrappedName} = ${wrap(target)};`);
|
|
140
|
+
state.needsImport = true;
|
|
141
|
+
return `${wrappedName} as ${exportedAs}`;
|
|
142
|
+
}
|
|
143
|
+
/**
|
|
144
|
+
* Wrap `export default <declaration or expression>`.
|
|
145
|
+
*
|
|
146
|
+
* `export default Foo`, where `Foo` already has a wrapper binding (a class
|
|
147
|
+
* also exported by name), is re-pointed at that binding instead of wrapping
|
|
148
|
+
* twice.
|
|
149
|
+
*/
|
|
150
|
+
function wrapDefaultExport(state, node, wrap) {
|
|
151
|
+
const decl = node.declaration;
|
|
152
|
+
if (decl.type === "Identifier") {
|
|
153
|
+
const wrappedName = state.wrappedLocals.get(decl.name);
|
|
154
|
+
if (wrappedName) {
|
|
155
|
+
state.ms.overwrite(decl.start, decl.end, wrappedName);
|
|
156
|
+
return;
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
const source = state.ms.original;
|
|
160
|
+
const keywordsEnd = exportDefaultKeywordsEnd(source, node.start);
|
|
161
|
+
const declaredName = decl.type === "ClassDeclaration" || decl.type === "FunctionDeclaration" ? decl.id?.name : void 0;
|
|
162
|
+
let wrapped = "__SENTRY_DEFAULT_EXPORT__";
|
|
163
|
+
if (declaredName) {
|
|
164
|
+
state.ms.remove(node.start, decl.start);
|
|
165
|
+
state.ms.appendLeft(node.end, `\nvar __SENTRY_DEFAULT_EXPORT__ = ${declaredName};`);
|
|
166
|
+
wrapped = declaredName;
|
|
167
|
+
} else if (isAnonymousFunctionOrClass(decl)) {
|
|
168
|
+
const hasSemicolon = source[node.end - 1] === ";";
|
|
169
|
+
state.ms.overwrite(node.start, keywordsEnd, "var __SENTRY_DEFAULT_EXPORT__ = { default:");
|
|
170
|
+
state.ms.appendLeft(hasSemicolon ? node.end - 1 : node.end, hasSemicolon ? " }.default" : " }.default;");
|
|
171
|
+
} else state.ms.overwrite(node.start, keywordsEnd, "var __SENTRY_DEFAULT_EXPORT__ =");
|
|
172
|
+
state.ms.appendLeft(node.end, "\nexport { __SENTRY_DEFAULT_EXPORT__ as default };");
|
|
173
|
+
state.ms.append(`\n__SENTRY_DEFAULT_EXPORT__ = ${wrap(wrapped)};`);
|
|
174
|
+
state.needsImport = true;
|
|
175
|
+
}
|
|
176
|
+
/**
|
|
177
|
+
* Offset just past the `default` keyword of the `export default` statement at `start`. Comments can
|
|
178
|
+
* sit between `export`, `default` and the expression, and may themselves contain the word `default`.
|
|
179
|
+
*/
|
|
180
|
+
function exportDefaultKeywordsEnd(source, start) {
|
|
181
|
+
let index = start + 6;
|
|
182
|
+
while (index < source.length && !source.startsWith("default", index)) if (source.startsWith("//", index)) {
|
|
183
|
+
const lineEnd = source.indexOf("\n", index);
|
|
184
|
+
index = lineEnd === -1 ? source.length : lineEnd;
|
|
185
|
+
} else if (source.startsWith("/*", index)) {
|
|
186
|
+
const commentEnd = source.indexOf("*/", index + 2);
|
|
187
|
+
index = commentEnd === -1 ? source.length : commentEnd + 2;
|
|
188
|
+
} else index++;
|
|
189
|
+
return index + 7;
|
|
190
|
+
}
|
|
191
|
+
/**
|
|
192
|
+
* `export { handler as default }`, the form bundlers emit for a default export. The export is set
|
|
193
|
+
* in two steps. Right after `handler` is declared, it is bound to `handler` as-is, so a circular
|
|
194
|
+
* import that reads it during module evaluation gets the handler, as before the transform. At the
|
|
195
|
+
* end of the module, it is rebound to the wrapper, so a handler assigned or given methods later is
|
|
196
|
+
* wrapped as it ends up. The binding is a `var`: a read before `handler` is declared gets
|
|
197
|
+
* `undefined`, as it would from the bundler's own `var`, where a `const` would throw and stop the
|
|
198
|
+
* Worker from starting.
|
|
199
|
+
*
|
|
200
|
+
* @returns the pair to export in place of the specifier
|
|
201
|
+
*/
|
|
202
|
+
function wrapDefaultSpecifier(state, localName, declaringStatement, wrap) {
|
|
203
|
+
const wrappedName = state.wrappedLocals.get(localName);
|
|
204
|
+
if (wrappedName) return `${wrappedName} as default`;
|
|
205
|
+
if (declaringStatement) state.ms.appendLeft(declaringStatement.end, `\nvar __SENTRY_DEFAULT_EXPORT__ = ${localName};`);
|
|
206
|
+
state.ms.append(`\n${declaringStatement ? "" : "var "}__SENTRY_DEFAULT_EXPORT__ = ${wrap(localName)};`);
|
|
207
|
+
state.needsImport = true;
|
|
208
|
+
return "__SENTRY_DEFAULT_EXPORT__ as default";
|
|
209
|
+
}
|
|
210
|
+
/**
|
|
211
|
+
* `export { default } from './handler'` and `export { x as default } from './handler'`.
|
|
212
|
+
*
|
|
213
|
+
* The original re-export is a live binding to the handler module's export, but the wrapper is not
|
|
214
|
+
* set until this module's body runs. A circular import that reads the default export before then
|
|
215
|
+
* gets `undefined` instead of the handler. The binding is a `var` so that the read does not throw,
|
|
216
|
+
* as a `const` would, and stop the Worker from starting. See `wrapDefaultSpecifier`.
|
|
217
|
+
*
|
|
218
|
+
* @returns the pair to export in place of the specifier
|
|
219
|
+
*/
|
|
220
|
+
function wrapDefaultReexport(state, localName, sourceLiteral, prelude, wrap) {
|
|
221
|
+
const target = "__SENTRY_REEXPORT_default__";
|
|
222
|
+
prelude.push(importAs(localName, target, sourceLiteral), `var __SENTRY_DEFAULT_EXPORT__ = ${wrap(target)};`);
|
|
223
|
+
state.needsImport = true;
|
|
224
|
+
return "__SENTRY_DEFAULT_EXPORT__ as default";
|
|
225
|
+
}
|
|
226
|
+
function importAs(importedName, localName, sourceLiteral) {
|
|
227
|
+
return importedName === DEFAULT_IMPORT ? `import ${localName} from ${sourceLiteral};` : `import { ${importedName} as ${localName} } from ${sourceLiteral};`;
|
|
228
|
+
}
|
|
229
|
+
export { collectDeclaringStatements, collectManuallyWrappedLocals, collectTopLevelClasses, findNamedExports, wrapDefaultExport, wrapDefaultReexport, wrapDefaultSpecifier, wrapForeignExport, wrapInlineExport, wrapLocalBinding, wrapSpecifierExports };
|
|
230
|
+
|
|
231
|
+
//# sourceMappingURL=exports.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"exports.js","names":[],"sources":["../../../src/rewriter/exports.ts"],"sourcesContent":["import type {\n BaseNode,\n ClassDeclarationNode,\n ExportDefaultNode,\n ExportNamedNode,\n ExportSpecifierNode,\n IdentifierNode,\n ImportDeclarationNode,\n ProgramBody,\n VariableDeclarationNode,\n} from './ast';\nimport {\n declarationOf,\n declaredNames,\n exportedName,\n isAnonymousFunctionOrClass,\n isCallToMethod,\n isTypeOnlyExport,\n} from './ast';\nimport type { RewriteState } from './rewriter';\n\n/** Builds the expression that wraps `target`, e.g. `target => \\`wrap(${target})\\``. */\nexport type WrapExpression = (target: string) => string;\n\n/**\n * Handles one export specifier of a statement passed to {@link wrapSpecifierExports}.\n * Returns the `Wrapped as Exported` pair to emit in its place, or `undefined`\n * to keep the specifier as written. Statements the pair depends on go onto\n * `prelude`, which is emitted before the rebuilt export.\n */\nexport type SpecifierWrapper = (\n specifier: ExportSpecifierNode,\n sourceLiteral: string | undefined,\n prelude: string[],\n) => string | undefined;\n\n/** Specifier name a `export { default as X } from '...'` re-export uses for the source's default. */\nconst DEFAULT_IMPORT = 'default';\n\n/** Top-level class declarations, exported or not, by name. */\nexport function collectTopLevelClasses(ast: ProgramBody): Map<string, ClassDeclarationNode> {\n const classes = new Map<string, ClassDeclarationNode>();\n for (const node of ast.body) {\n const declaration = declarationOf(node);\n if (declaration?.type !== 'ClassDeclaration') continue;\n const classNode = declaration as ClassDeclarationNode;\n if (classNode.id?.name) classes.set(classNode.id.name, classNode);\n }\n return classes;\n}\n\n/** Top-level value binding name → the statement that declares it. */\nexport function collectDeclaringStatements(ast: ProgramBody): Map<string, BaseNode> {\n const statements = new Map<string, BaseNode>();\n for (const node of ast.body) {\n const declaration = declarationOf(node);\n if (!declaration) continue;\n const names =\n declaration.type === 'ImportDeclaration' ? valueImportNames(declaration) : (declaredNames(declaration) ?? []);\n for (const name of names) {\n if (name) statements.set(name, node);\n }\n }\n return statements;\n}\n\nfunction valueImportNames(node: ImportDeclarationNode): (string | undefined)[] {\n if (node.importKind === 'type') return [];\n return (node.specifiers ?? [])\n .filter(specifier => specifier.importKind !== 'type')\n .map(specifier => specifier.local?.name);\n}\n\n/**\n * Top-level bindings already assigned the result of one of `wrapperNames`\n * (`const X = wrap(...)`), so exporting one must not wrap it a second time.\n */\nexport function collectManuallyWrappedLocals(ast: ProgramBody, wrapperNames: readonly string[]): Set<string> {\n const locals = new Set<string>();\n\n for (const node of ast.body) {\n const declaration = declarationOf(node);\n if (declaration?.type !== 'VariableDeclaration') continue;\n for (const declarator of (declaration as VariableDeclarationNode).declarations ?? []) {\n const name = declarator.id?.type === 'Identifier' ? (declarator.id as IdentifierNode).name : undefined;\n const init = declarator.init;\n if (name && init && wrapperNames.some(wrapper => isCallToMethod(init, wrapper))) {\n locals.add(name);\n }\n }\n }\n\n return locals;\n}\n\n/** The value export statements (`export const`, `export { }`) that export `name`. */\nexport function findNamedExports(ast: ProgramBody, name: string): ExportNamedNode[] {\n const found: ExportNamedNode[] = [];\n for (const node of ast.body) {\n if (node.type !== 'ExportNamedDeclaration' || isTypeOnlyExport(node as ExportNamedNode)) continue;\n const exportNode = node as ExportNamedNode;\n const exportsName = exportNode.declaration\n ? !!declaredNames(exportNode.declaration)?.includes(name)\n : (exportNode.specifiers ?? []).some(\n specifier => !isTypeOnlyExport(specifier) && exportedName(specifier.exported) === name,\n );\n if (exportsName) found.push(exportNode);\n }\n return found;\n}\n\n/**\n * Wrap a binding declared in this module and return the binding that holds the wrapper.\n *\n * The declaration is left exactly as written, so a class or function keeps its\n * `Function.prototype.name`. Only the *export* has to become the wrapper, so the wrapper gets its\n * own binding and the export is aliased to it.\n */\nexport function wrapLocalBinding(\n state: RewriteState,\n localName: string,\n declaringNode: BaseNode,\n wrap: WrapExpression,\n): string {\n const existing = state.wrappedLocals.get(localName);\n if (existing) return existing;\n\n const wrappedName = `__SENTRY_WRAPPED_${localName}__`;\n state.wrappedLocals.set(localName, wrappedName);\n state.ms.appendLeft(declaringNode.end, `\\nconst ${wrappedName} = ${wrap(localName)};\\n`);\n state.needsImport = true;\n return wrappedName;\n}\n\n/**\n * Wrap `localName` where an inline export declares it (`export class X {}`,\n * `export const x = ...`, `export function x() {}`). The `export` keyword is\n * replaced by an export clause that aliases the name to the wrapper. Other\n * names the same declaration exports are exported again, through their\n * wrapper when a later call wraps them too.\n *\n * @returns whether the declaration exports `localName`\n */\nexport function wrapInlineExport(\n state: RewriteState,\n exportNode: ExportNamedNode,\n localName: string,\n wrap: WrapExpression,\n): boolean {\n const declaration = exportNode.declaration;\n const names = declaration ? declaredNames(declaration) : undefined;\n if (!declaration || !names?.includes(localName)) return false;\n\n wrapLocalBinding(state, localName, declaration, wrap);\n const specifiers = names.map(name => {\n const wrappedName = state.wrappedLocals.get(name);\n return wrappedName ? `${wrappedName} as ${name}` : name;\n });\n // In `@dec export class A {}` the decorators come before `export`, so the\n // clause has to go before them.\n const decoratorStart = (declaration as ClassDeclarationNode).decorators?.[0]?.start ?? exportNode.start;\n const start = Math.min(decoratorStart, exportNode.start);\n const decorators = state.ms.original.slice(start, exportNode.start);\n // A second call for another name of this declaration overwrites the same range again.\n state.ms.overwrite(start, declaration.start, `export { ${specifiers.join(', ')} };\\n${decorators}`);\n return true;\n}\n\n/**\n * Wrap the specifiers of an `export { ... }` statement that `wrapSpecifier` picks.\n *\n * Each such specifier is re-pointed at a binding holding the wrapper, which means rebuilding the\n * statement; the other specifiers are carried over verbatim. A binding that lives in **another**\n * module is first bound under a private name (see {@link wrapForeignExport}), since an import\n * binding cannot be reassigned and the `from` form has no local binding at all.\n */\nexport function wrapSpecifierExports(\n state: RewriteState,\n node: ExportNamedNode,\n wrapSpecifier: SpecifierWrapper,\n): void {\n const specifiers = node.specifiers ?? [];\n if (specifiers.length === 0 || isTypeOnlyExport(node)) return;\n\n const sourceLiteral = node.source ? state.ms.original.slice(node.source.start, node.source.end) : undefined;\n\n const prelude: string[] = [];\n const wrappedPairs: string[] = [];\n const kept: string[] = [];\n\n for (const specifier of specifiers) {\n const pair = isTypeOnlyExport(specifier) ? undefined : wrapSpecifier(specifier, sourceLiteral, prelude);\n if (pair) {\n wrappedPairs.push(pair);\n } else {\n kept.push(state.ms.original.slice(specifier.start, specifier.end));\n }\n }\n\n if (wrappedPairs.length === 0) return;\n\n const statements = [...prelude, `export { ${wrappedPairs.join(', ')} };`];\n if (kept.length > 0) {\n const clause = `export { ${kept.join(', ')} }`;\n statements.push(sourceLiteral ? `${clause} from ${sourceLiteral};` : `${clause};`);\n }\n state.ms.overwrite(node.start, node.end, statements.join('\\n'));\n}\n\n/**\n * Wrap a binding that comes from another module: imported and re-exported\n * (`sourceLiteral` undefined), or re-exported directly (`export { x } from`).\n * Pushes the statements that bind the wrapper onto `prelude` and returns the\n * pair to export.\n */\nexport function wrapForeignExport(\n state: RewriteState,\n localName: string,\n exportedAs: string,\n sourceLiteral: string | undefined,\n prelude: string[],\n wrap: WrapExpression,\n): string {\n let target = localName;\n\n if (sourceLiteral) {\n target = `__SENTRY_REEXPORT_${exportedAs}__`;\n prelude.push(importAs(localName, target, sourceLiteral));\n }\n\n const wrappedName = `__SENTRY_WRAPPED_${exportedAs}__`;\n prelude.push(`const ${wrappedName} = ${wrap(target)};`);\n state.needsImport = true;\n return `${wrappedName} as ${exportedAs}`;\n}\n\n/**\n * Wrap `export default <declaration or expression>`.\n *\n * `export default Foo`, where `Foo` already has a wrapper binding (a class\n * also exported by name), is re-pointed at that binding instead of wrapping\n * twice.\n */\nexport function wrapDefaultExport(state: RewriteState, node: ExportDefaultNode, wrap: WrapExpression): void {\n const decl = node.declaration;\n\n if (decl.type === 'Identifier') {\n const wrappedName = state.wrappedLocals.get((decl as IdentifierNode).name);\n if (wrappedName) {\n state.ms.overwrite(decl.start, decl.end, wrappedName);\n return;\n }\n }\n\n // Only the `export default` keywords are replaced, so parentheses around the expression stay.\n const source = state.ms.original;\n const keywordsEnd = exportDefaultKeywordsEnd(source, node.start);\n const declaredName =\n decl.type === 'ClassDeclaration' || decl.type === 'FunctionDeclaration'\n ? (decl as ClassDeclarationNode).id?.name\n : undefined;\n\n // As with `export { handler as default }`, the export is set in two steps: bound as-is where the\n // original statement set it, then rebound at the end of the module to the wrapper, which sees\n // methods added in between. See `wrapDefaultSpecifier`.\n let wrapped = '__SENTRY_DEFAULT_EXPORT__';\n if (declaredName) {\n // `export default class Handler {}`: the declaration stays, so `Handler` stays bound in the module.\n state.ms.remove(node.start, decl.start);\n state.ms.appendLeft(node.end, `\\nvar __SENTRY_DEFAULT_EXPORT__ = ${declaredName};`);\n wrapped = declaredName;\n } else if (isAnonymousFunctionOrClass(decl)) {\n // As a property value, the class or function gets the name `default`, as `export default` gives it.\n const hasSemicolon = source[node.end - 1] === ';';\n state.ms.overwrite(node.start, keywordsEnd, 'var __SENTRY_DEFAULT_EXPORT__ = { default:');\n state.ms.appendLeft(hasSemicolon ? node.end - 1 : node.end, hasSemicolon ? ' }.default' : ' }.default;');\n } else {\n state.ms.overwrite(node.start, keywordsEnd, 'var __SENTRY_DEFAULT_EXPORT__ =');\n }\n state.ms.appendLeft(node.end, '\\nexport { __SENTRY_DEFAULT_EXPORT__ as default };');\n state.ms.append(`\\n__SENTRY_DEFAULT_EXPORT__ = ${wrap(wrapped)};`);\n state.needsImport = true;\n}\n\n/**\n * Offset just past the `default` keyword of the `export default` statement at `start`. Comments can\n * sit between `export`, `default` and the expression, and may themselves contain the word `default`.\n */\nfunction exportDefaultKeywordsEnd(source: string, start: number): number {\n let index = start + 'export'.length;\n while (index < source.length && !source.startsWith('default', index)) {\n if (source.startsWith('//', index)) {\n const lineEnd = source.indexOf('\\n', index);\n index = lineEnd === -1 ? source.length : lineEnd;\n } else if (source.startsWith('/*', index)) {\n const commentEnd = source.indexOf('*/', index + 2);\n index = commentEnd === -1 ? source.length : commentEnd + 2;\n } else {\n index++;\n }\n }\n return index + 'default'.length;\n}\n\n/**\n * `export { handler as default }`, the form bundlers emit for a default export. The export is set\n * in two steps. Right after `handler` is declared, it is bound to `handler` as-is, so a circular\n * import that reads it during module evaluation gets the handler, as before the transform. At the\n * end of the module, it is rebound to the wrapper, so a handler assigned or given methods later is\n * wrapped as it ends up. The binding is a `var`: a read before `handler` is declared gets\n * `undefined`, as it would from the bundler's own `var`, where a `const` would throw and stop the\n * Worker from starting.\n *\n * @returns the pair to export in place of the specifier\n */\nexport function wrapDefaultSpecifier(\n state: RewriteState,\n localName: string,\n declaringStatement: BaseNode | undefined,\n wrap: WrapExpression,\n): string {\n // Same as `export default Foo`: re-point at the wrapper a named export already made.\n const wrappedName = state.wrappedLocals.get(localName);\n if (wrappedName) return `${wrappedName} as default`;\n\n if (declaringStatement) {\n state.ms.appendLeft(declaringStatement.end, `\\nvar __SENTRY_DEFAULT_EXPORT__ = ${localName};`);\n }\n state.ms.append(`\\n${declaringStatement ? '' : 'var '}__SENTRY_DEFAULT_EXPORT__ = ${wrap(localName)};`);\n state.needsImport = true;\n return '__SENTRY_DEFAULT_EXPORT__ as default';\n}\n\n/**\n * `export { default } from './handler'` and `export { x as default } from './handler'`.\n *\n * The original re-export is a live binding to the handler module's export, but the wrapper is not\n * set until this module's body runs. A circular import that reads the default export before then\n * gets `undefined` instead of the handler. The binding is a `var` so that the read does not throw,\n * as a `const` would, and stop the Worker from starting. See `wrapDefaultSpecifier`.\n *\n * @returns the pair to export in place of the specifier\n */\nexport function wrapDefaultReexport(\n state: RewriteState,\n localName: string,\n sourceLiteral: string,\n prelude: string[],\n wrap: WrapExpression,\n): string {\n const target = '__SENTRY_REEXPORT_default__';\n prelude.push(importAs(localName, target, sourceLiteral), `var __SENTRY_DEFAULT_EXPORT__ = ${wrap(target)};`);\n state.needsImport = true;\n return '__SENTRY_DEFAULT_EXPORT__ as default';\n}\n\nfunction importAs(importedName: string, localName: string, sourceLiteral: string): string {\n return importedName === DEFAULT_IMPORT\n ? `import ${localName} from ${sourceLiteral};`\n : `import { ${importedName} as ${localName} } from ${sourceLiteral};`;\n}\n"],"mappings":";;;AAqCA,MAAM,iBAAiB;;AAGvB,SAAgB,uBAAuB,KAAqD;CAC1F,MAAM,0BAAU,IAAI,IAAkC;CACtD,KAAK,MAAM,QAAQ,IAAI,MAAM;EAC3B,MAAM,cAAc,cAAc,IAAI;EACtC,IAAI,aAAa,SAAS,oBAAoB;EAC9C,MAAM,YAAY;EAClB,IAAI,UAAU,IAAI,MAAM,QAAQ,IAAI,UAAU,GAAG,MAAM,SAAS;CAClE;CACA,OAAO;AACT;;AAGA,SAAgB,2BAA2B,KAAyC;CAClF,MAAM,6BAAa,IAAI,IAAsB;CAC7C,KAAK,MAAM,QAAQ,IAAI,MAAM;EAC3B,MAAM,cAAc,cAAc,IAAI;EACtC,IAAI,CAAC,aAAa;EAClB,MAAM,QACJ,YAAY,SAAS,sBAAsB,iBAAiB,WAAW,IAAK,cAAc,WAAW,KAAK,CAAC;EAC7G,KAAK,MAAM,QAAQ,OACjB,IAAI,MAAM,WAAW,IAAI,MAAM,IAAI;CAEvC;CACA,O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ACQ;CACR,MAAM,SAAS;CACf,QAAQ,KAAK,SAAS,WAAW,QAAQ,aAAa,GAAG,mCAAmC,KAAK,MAAM,EAAE,EAAE;CAC3G,MAAM,cAAc;CACpB,OAAO;AACT;AAEA,SAAS,SAAS,cAAsB,WAAmB,eAA+B;CACxF,OAAO,iBAAiB,iBACpB,UAAU,UAAU,QAAQ,cAAc,KAC1C,YAAY,aAAa,MAAM,UAAU,UAAU,cAAc;AACvE"}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { directivesEnd, exportedName } from "./ast.js";
|
|
2
|
+
// src/rewriter/imports.ts
|
|
3
|
+
/** Whether the module already binds `name` to the export of the same name from `module`. */
|
|
4
|
+
function hasImport(ast, module, name) {
|
|
5
|
+
return ast.body.some((node) => {
|
|
6
|
+
if (node.type !== "ImportDeclaration") return false;
|
|
7
|
+
const importNode = node;
|
|
8
|
+
if (importNode.source?.value !== module || importNode.importKind === "type") return false;
|
|
9
|
+
return (importNode.specifiers ?? []).some((specifier) => specifier.type === "ImportSpecifier" && specifier.importKind !== "type" && exportedName(specifier.imported) === name && specifier.local?.name === name);
|
|
10
|
+
});
|
|
11
|
+
}
|
|
12
|
+
/** Adds an import statement after the hashbang and directives, once per module. */
|
|
13
|
+
function addImport(state, ast, statement) {
|
|
14
|
+
if (state.imports.has(statement)) return;
|
|
15
|
+
state.imports.add(statement);
|
|
16
|
+
const position = directivesEnd(ast);
|
|
17
|
+
state.ms.appendLeft(position, position === 0 ? `${statement}\n` : `\n${statement}`);
|
|
18
|
+
}
|
|
19
|
+
export { addImport, hasImport };
|
|
20
|
+
|
|
21
|
+
//# sourceMappingURL=imports.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"imports.js","names":[],"sources":["../../../src/rewriter/imports.ts"],"sourcesContent":["import type { ImportDeclarationNode, ProgramBody } from './ast';\nimport { directivesEnd, exportedName } from './ast';\nimport type { RewriteState } from './rewriter';\n\n/** Whether the module already binds `name` to the export of the same name from `module`. */\nexport function hasImport(ast: ProgramBody, module: string, name: string): boolean {\n return ast.body.some(node => {\n if (node.type !== 'ImportDeclaration') return false;\n const importNode = node as ImportDeclarationNode;\n if (importNode.source?.value !== module || importNode.importKind === 'type') return false;\n return (importNode.specifiers ?? []).some(\n specifier =>\n specifier.type === 'ImportSpecifier' &&\n specifier.importKind !== 'type' &&\n exportedName(specifier.imported) === name &&\n specifier.local?.name === name,\n );\n });\n}\n\n/** Adds an import statement after the hashbang and directives, once per module. */\nexport function addImport(state: RewriteState, ast: ProgramBody, statement: string): void {\n if (state.imports.has(statement)) return;\n state.imports.add(statement);\n\n const position = directivesEnd(ast);\n state.ms.appendLeft(position, position === 0 ? `${statement}\\n` : `\\n${statement}`);\n}\n"],"mappings":";;;AAKA,SAAgB,UAAU,KAAkB,QAAgB,MAAuB;CACjF,OAAO,IAAI,KAAK,MAAK,SAAQ;EAC3B,IAAI,KAAK,SAAS,qBAAqB,OAAO;EAC9C,MAAM,aAAa;EACnB,IAAI,WAAW,QAAQ,UAAU,UAAU,WAAW,eAAe,QAAQ,OAAO;EACpF,QAAQ,WAAW,cAAc,CAAC,EAAA,CAAG,MACnC,cACE,UAAU,SAAS,qBACnB,UAAU,eAAe,UACzB,aAAa,UAAU,QAAQ,MAAM,QACrC,UAAU,OAAO,SAAS,IAC9B;CACF,CAAC;AACH;;AAGA,SAAgB,UAAU,OAAqB,KAAkB,WAAyB;CACxF,IAAI,MAAM,QAAQ,IAAI,SAAS,GAAG;CAClC,MAAM,QAAQ,IAAI,SAAS;CAE3B,MAAM,WAAW,cAAc,GAAG;CAClC,MAAM,GAAG,WAAW,UAAU,aAAa,IAAI,GAAG,UAAU,MAAM,KAAK,WAAW;AACpF"}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import "../_virtual/_rolldown/runtime.js";
|
|
2
|
+
import { declarationOf, declaredNames, directivesEnd, exportedName, isAnonymousFunctionOrClass, isCallToMethod, isTypeOnlyExport, walk } from "./ast.js";
|
|
3
|
+
import { wrapArrayLiteral } from "./arrays.js";
|
|
4
|
+
import { findClassesExtending } from "./class-extends.js";
|
|
5
|
+
import { collectDeclaringStatements, collectManuallyWrappedLocals, collectTopLevelClasses, findNamedExports, wrapDefaultExport, wrapDefaultReexport, wrapDefaultSpecifier, wrapForeignExport, wrapInlineExport, wrapLocalBinding, wrapSpecifierExports } from "./exports.js";
|
|
6
|
+
import { addImport, hasImport } from "./imports.js";
|
|
7
|
+
import { DEFAULT_EXPORT, shapeFromAst, shapeFromSource } from "./module-shape.js";
|
|
8
|
+
import { bundlerParser, isParserLoading, langFromId, loadParser, parseModule } from "./parse.js";
|
|
9
|
+
import { createReport, formatReport } from "./report.js";
|
|
10
|
+
import { createCallSiteRewriter, createRewriteState } from "./rewriter.js";
|
|
11
|
+
export { DEFAULT_EXPORT, addImport, bundlerParser, collectDeclaringStatements, collectManuallyWrappedLocals, collectTopLevelClasses, createCallSiteRewriter, createReport, createRewriteState, declarationOf, declaredNames, directivesEnd, exportedName, findClassesExtending, findNamedExports, formatReport, hasImport, isAnonymousFunctionOrClass, isCallToMethod, isParserLoading, isTypeOnlyExport, langFromId, loadParser, parseModule, shapeFromAst, shapeFromSource, walk, wrapArrayLiteral, wrapDefaultExport, wrapDefaultReexport, wrapDefaultSpecifier, wrapForeignExport, wrapInlineExport, wrapLocalBinding, wrapSpecifierExports };
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
import { exportedName, isTypeOnlyExport } from "./ast.js";
|
|
2
|
+
import { langFromId, parseModule } from "./parse.js";
|
|
3
|
+
// src/rewriter/module-shape.ts
|
|
4
|
+
/** Binding name used for a module's default export. */
|
|
5
|
+
const DEFAULT_EXPORT = "default";
|
|
6
|
+
function emptyShape() {
|
|
7
|
+
return {
|
|
8
|
+
classes: /* @__PURE__ */ new Map(),
|
|
9
|
+
imports: /* @__PURE__ */ new Map(),
|
|
10
|
+
namespaces: /* @__PURE__ */ new Map(),
|
|
11
|
+
reexports: /* @__PURE__ */ new Map(),
|
|
12
|
+
localExports: /* @__PURE__ */ new Map(),
|
|
13
|
+
starExports: []
|
|
14
|
+
};
|
|
15
|
+
}
|
|
16
|
+
/** Collect the shape of a module from its parsed AST. */
|
|
17
|
+
function shapeFromAst(ast) {
|
|
18
|
+
const shape = emptyShape();
|
|
19
|
+
for (const node of ast.body) switch (node.type) {
|
|
20
|
+
case "ClassDeclaration":
|
|
21
|
+
addAstClass(shape, node);
|
|
22
|
+
break;
|
|
23
|
+
case "ImportDeclaration":
|
|
24
|
+
addAstImports(shape, node);
|
|
25
|
+
break;
|
|
26
|
+
case "ExportNamedDeclaration":
|
|
27
|
+
addAstNamedExport(shape, node);
|
|
28
|
+
break;
|
|
29
|
+
case "ExportDefaultDeclaration": {
|
|
30
|
+
const decl = node.declaration;
|
|
31
|
+
if (decl.type === "ClassDeclaration" || decl.type === "ClassExpression") {
|
|
32
|
+
shape.defaultExportIsClass = true;
|
|
33
|
+
shape.defaultExportSuper = superRefFromNode(decl.superClass);
|
|
34
|
+
addAstClass(shape, decl);
|
|
35
|
+
} else if (decl.type === "Identifier") shape.defaultExportName = decl.name;
|
|
36
|
+
break;
|
|
37
|
+
}
|
|
38
|
+
case "ExportAllDeclaration": {
|
|
39
|
+
const starNode = node;
|
|
40
|
+
const source = starNode.exported || isTypeOnlyExport(starNode) ? void 0 : asString(starNode.source?.value);
|
|
41
|
+
if (source) shape.starExports.push(source);
|
|
42
|
+
break;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
return shape;
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* Extract the module shape from unprocessed source, such as a sibling module
|
|
49
|
+
* read off disk. Returns `undefined` when the source does not parse.
|
|
50
|
+
*/
|
|
51
|
+
function shapeFromSource(code, id) {
|
|
52
|
+
const lang = langFromId(id);
|
|
53
|
+
for (const candidate of lang === "tsx" ? [lang] : [lang, "tsx"]) try {
|
|
54
|
+
return shapeFromAst(parseModule(code, id, candidate));
|
|
55
|
+
} catch {}
|
|
56
|
+
}
|
|
57
|
+
function superRefFromNode(superClass) {
|
|
58
|
+
if (!superClass) return void 0;
|
|
59
|
+
if (superClass.type === "Identifier") return {
|
|
60
|
+
kind: "identifier",
|
|
61
|
+
name: superClass.name
|
|
62
|
+
};
|
|
63
|
+
if (superClass.type === "MemberExpression") {
|
|
64
|
+
const member = superClass;
|
|
65
|
+
const object = member.object?.type === "Identifier" ? member.object.name : void 0;
|
|
66
|
+
const property = member.property?.name;
|
|
67
|
+
if (object && property) return {
|
|
68
|
+
kind: "member",
|
|
69
|
+
object,
|
|
70
|
+
property
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
function addAstClass(shape, classNode) {
|
|
75
|
+
if (classNode.id?.name) shape.classes.set(classNode.id.name, superRefFromNode(classNode.superClass));
|
|
76
|
+
}
|
|
77
|
+
function addAstImports(shape, node) {
|
|
78
|
+
const source = asString(node.source?.value);
|
|
79
|
+
if (!source || node.importKind === "type") return;
|
|
80
|
+
for (const specifier of node.specifiers ?? []) {
|
|
81
|
+
const local = specifier.local?.name;
|
|
82
|
+
if (!local || specifier.importKind === "type") continue;
|
|
83
|
+
const imported = exportedName(specifier.imported);
|
|
84
|
+
if (specifier.type === "ImportSpecifier" && imported) shape.imports.set(local, {
|
|
85
|
+
source,
|
|
86
|
+
imported
|
|
87
|
+
});
|
|
88
|
+
else if (specifier.type === "ImportDefaultSpecifier") shape.imports.set(local, {
|
|
89
|
+
source,
|
|
90
|
+
imported: DEFAULT_EXPORT
|
|
91
|
+
});
|
|
92
|
+
else if (specifier.type === "ImportNamespaceSpecifier") shape.namespaces.set(local, source);
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
function addAstNamedExport(shape, node) {
|
|
96
|
+
if (node.declaration?.type === "ClassDeclaration") {
|
|
97
|
+
addAstClass(shape, node.declaration);
|
|
98
|
+
return;
|
|
99
|
+
}
|
|
100
|
+
if (isTypeOnlyExport(node)) return;
|
|
101
|
+
const source = asString(node.source?.value);
|
|
102
|
+
for (const specifier of node.specifiers ?? []) {
|
|
103
|
+
const exported = exportedName(specifier.exported);
|
|
104
|
+
const local = exportedName(specifier.local);
|
|
105
|
+
if (!exported || !local || isTypeOnlyExport(specifier)) continue;
|
|
106
|
+
if (source) shape.reexports.set(exported, {
|
|
107
|
+
source,
|
|
108
|
+
imported: local
|
|
109
|
+
});
|
|
110
|
+
else shape.localExports.set(exported, local);
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
function asString(value) {
|
|
114
|
+
return typeof value === "string" && value ? value : void 0;
|
|
115
|
+
}
|
|
116
|
+
export { DEFAULT_EXPORT, shapeFromAst, shapeFromSource };
|
|
117
|
+
|
|
118
|
+
//# sourceMappingURL=module-shape.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"module-shape.js","names":[],"sources":["../../../src/rewriter/module-shape.ts"],"sourcesContent":["import type {\n BaseNode,\n ClassDeclarationNode,\n ExportAllNode,\n ExportDefaultNode,\n ExportNamedNode,\n IdentifierNode,\n ImportDeclarationNode,\n MemberExpressionNode,\n ProgramBody,\n} from './ast';\nimport { exportedName, isTypeOnlyExport } from './ast';\nimport { langFromId, parseModule } from './parse';\n\n/** Binding name used for a module's default export. */\nexport const DEFAULT_EXPORT = 'default';\n\n/** A resolved superclass reference: a bare identifier or a `ns.Member` expression. */\nexport type SuperRef = { kind: 'identifier'; name: string } | { kind: 'member'; object: string; property: string };\n\n/** The declarations of a single module that binding resolution needs. */\nexport interface ModuleShape {\n /** Top-level class names → their superclass reference (absent when the class has no `extends`). */\n classes: Map<string, SuperRef | undefined>;\n /** Local binding name → the import it came from (`imported` is `default` for a default import). */\n imports: Map<string, { source: string; imported: string }>;\n /** Local binding name → module specifier, for `import * as ns from '...'`. */\n namespaces: Map<string, string>;\n /** Exported name → the re-export it came from, for `export { x as y } from '...'`. */\n reexports: Map<string, { source: string; imported: string }>;\n /** Exported name → local binding name, for `export { x as y }` without a source. */\n localExports: Map<string, string>;\n /** Module specifiers of bare `export * from '...'` declarations. */\n starExports: string[];\n /** `export default <Identifier>` — the local name it refers to. */\n defaultExportName?: string;\n /** True when the module's default export is a class declaration/expression. */\n defaultExportIsClass?: boolean;\n /** Superclass of an anonymous `export default class extends X`. */\n defaultExportSuper?: SuperRef;\n}\n\nfunction emptyShape(): ModuleShape {\n return {\n classes: new Map(),\n imports: new Map(),\n namespaces: new Map(),\n reexports: new Map(),\n localExports: new Map(),\n starExports: [],\n };\n}\n\n/** Collect the shape of a module from its parsed AST. */\nexport function shapeFromAst(ast: ProgramBody): ModuleShape {\n const shape = emptyShape();\n\n for (const node of ast.body) {\n switch (node.type) {\n case 'ClassDeclaration':\n addAstClass(shape, node);\n break;\n case 'ImportDeclaration':\n addAstImports(shape, node);\n break;\n case 'ExportNamedDeclaration':\n addAstNamedExport(shape, node);\n break;\n case 'ExportDefaultDeclaration': {\n const decl = (node as ExportDefaultNode).declaration;\n if (decl.type === 'ClassDeclaration' || decl.type === 'ClassExpression') {\n shape.defaultExportIsClass = true;\n shape.defaultExportSuper = superRefFromNode((decl as ClassDeclarationNode).superClass);\n // `export default class Foo {}` also binds `Foo` locally.\n addAstClass(shape, decl);\n } else if (decl.type === 'Identifier') {\n shape.defaultExportName = (decl as IdentifierNode).name;\n }\n break;\n }\n case 'ExportAllDeclaration': {\n const starNode = node as ExportAllNode;\n // `export * as ns from '...'` binds a namespace object, not the individual exports.\n const source = starNode.exported || isTypeOnlyExport(starNode) ? undefined : asString(starNode.source?.value);\n if (source) shape.starExports.push(source);\n break;\n }\n }\n }\n\n return shape;\n}\n\n/**\n * Extract the module shape from unprocessed source, such as a sibling module\n * read off disk. Returns `undefined` when the source does not parse.\n */\nexport function shapeFromSource(code: string, id: string): ModuleShape | undefined {\n const lang = langFromId(id);\n // A module read off disk may hold TypeScript or JSX whatever its id says,\n // and `tsx` reads everything the other dialects do.\n for (const candidate of lang === 'tsx' ? [lang] : [lang, 'tsx' as const]) {\n try {\n return shapeFromAst(parseModule(code, id, candidate));\n } catch {\n // Try the next dialect.\n }\n }\n return undefined;\n}\n\nfunction superRefFromNode(superClass: BaseNode | null | undefined): SuperRef | undefined {\n if (!superClass) return undefined;\n\n if (superClass.type === 'Identifier') {\n return { kind: 'identifier', name: (superClass as IdentifierNode).name };\n }\n\n if (superClass.type === 'MemberExpression') {\n const member = superClass as MemberExpressionNode;\n const object = member.object?.type === 'Identifier' ? member.object.name : undefined;\n const property = member.property?.name;\n if (object && property) return { kind: 'member', object, property };\n }\n\n return undefined;\n}\n\nfunction addAstClass(shape: ModuleShape, classNode: ClassDeclarationNode): void {\n if (classNode.id?.name) shape.classes.set(classNode.id.name, superRefFromNode(classNode.superClass));\n}\n\nfunction addAstImports(shape: ModuleShape, node: ImportDeclarationNode): void {\n const source = asString(node.source?.value);\n // Type-only imports never contribute a runtime base class.\n if (!source || node.importKind === 'type') return;\n\n for (const specifier of node.specifiers ?? []) {\n const local = specifier.local?.name;\n if (!local || specifier.importKind === 'type') continue;\n\n const imported = exportedName(specifier.imported);\n if (specifier.type === 'ImportSpecifier' && imported) {\n shape.imports.set(local, { source, imported });\n } else if (specifier.type === 'ImportDefaultSpecifier') {\n shape.imports.set(local, { source, imported: DEFAULT_EXPORT });\n } else if (specifier.type === 'ImportNamespaceSpecifier') {\n shape.namespaces.set(local, source);\n }\n }\n}\n\nfunction addAstNamedExport(shape: ModuleShape, node: ExportNamedNode): void {\n if (node.declaration?.type === 'ClassDeclaration') {\n addAstClass(shape, node.declaration);\n return;\n }\n if (isTypeOnlyExport(node)) return;\n\n const source = asString(node.source?.value);\n for (const specifier of node.specifiers ?? []) {\n const exported = exportedName(specifier.exported);\n const local = exportedName(specifier.local);\n if (!exported || !local || isTypeOnlyExport(specifier)) continue;\n\n if (source) {\n shape.reexports.set(exported, { source, imported: local });\n } else {\n shape.localExports.set(exported, local);\n }\n }\n}\n\nfunction asString(value: unknown): string | undefined {\n return typeof value === 'string' && value ? value : undefined;\n}\n"],"mappings":";;;;A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,aAAa,UAAU,KAAK;EAC1C,IAAI,CAAC,YAAY,CAAC,SAAS,iBAAiB,SAAS,GAAG;EAExD,IAAI,QACF,MAAM,UAAU,IAAI,UAAU;GAAE;GAAQ,UAAU;EAAM,CAAC;OAEzD,MAAM,aAAa,IAAI,UAAU,KAAK;CAE1C;AACF;AAEA,SAAS,SAAS,OAAoC;CACpD,OAAO,OAAO,UAAU,YAAY,QAAQ,QAAQ,KAAA;AACtD"}
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import { stripUrlQueryAndFragment } from "@sentry/core";
|
|
2
|
+
// src/rewriter/parse.ts
|
|
3
|
+
const PARSER_UNAVAILABLE_MESSAGE = "[@sentry/bundler-plugins] Could not load `oxc-parser` for this platform. Modules that need it will not be auto-instrumented.";
|
|
4
|
+
let oxc;
|
|
5
|
+
let warnedParserUnavailable = false;
|
|
6
|
+
const oxcLoaded = import("oxc-parser").then((module) => {
|
|
7
|
+
oxc = module;
|
|
8
|
+
return true;
|
|
9
|
+
}, () => {
|
|
10
|
+
oxc = null;
|
|
11
|
+
return false;
|
|
12
|
+
});
|
|
13
|
+
/** Resolves once `oxc-parser` has loaded or failed to load, with whether it is available. */
|
|
14
|
+
function loadParser() {
|
|
15
|
+
return oxcLoaded;
|
|
16
|
+
}
|
|
17
|
+
function isParserLoading() {
|
|
18
|
+
return oxc === void 0;
|
|
19
|
+
}
|
|
20
|
+
/** The source dialect a module id names by its extension. */
|
|
21
|
+
function langFromId(id) {
|
|
22
|
+
const extension = /\.([cm]?[jt]sx?)$/.exec(stripUrlQueryAndFragment(id))?.[1] ?? "js";
|
|
23
|
+
if (extension === "tsx") return "tsx";
|
|
24
|
+
if (extension === "jsx") return "jsx";
|
|
25
|
+
return extension.endsWith("ts") ? "ts" : "js";
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* The default {@link ModuleParser}, over `oxc-parser`. Throws when `oxc-parser`
|
|
29
|
+
* has not loaded; see {@link loadParser}.
|
|
30
|
+
*/
|
|
31
|
+
function parseModule(code, id, lang = langFromId(id)) {
|
|
32
|
+
if (!oxc) {
|
|
33
|
+
if (oxc === null && !warnedParserUnavailable) {
|
|
34
|
+
warnedParserUnavailable = true;
|
|
35
|
+
console.warn(PARSER_UNAVAILABLE_MESSAGE);
|
|
36
|
+
}
|
|
37
|
+
throw new Error(oxc === null ? PARSER_UNAVAILABLE_MESSAGE : "`oxc-parser` has not loaded yet");
|
|
38
|
+
}
|
|
39
|
+
const { program, errors } = oxc.parseSync(id, code, {
|
|
40
|
+
lang,
|
|
41
|
+
sourceType: "module",
|
|
42
|
+
preserveParens: false
|
|
43
|
+
});
|
|
44
|
+
if (errors.length > 0) throw new Error(errors[0]?.message);
|
|
45
|
+
return program;
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* A parser over Rolldown's own `this.parse`, which reads TypeScript when told
|
|
49
|
+
* the dialect. Rollup's `this.parse` cannot, so it is not used.
|
|
50
|
+
*/
|
|
51
|
+
function bundlerParser(context) {
|
|
52
|
+
if (!context?.meta?.rolldownVersion || typeof context.parse !== "function") return void 0;
|
|
53
|
+
return (code, id) => context.parse?.(code, {
|
|
54
|
+
lang: langFromId(id),
|
|
55
|
+
preserveParens: false
|
|
56
|
+
});
|
|
57
|
+
}
|
|
58
|
+
export { bundlerParser, isParserLoading, langFromId, loadParser, parseModule };
|
|
59
|
+
|
|
60
|
+
//# sourceMappingURL=parse.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"parse.js","names":[],"sources":["../../../src/rewriter/parse.ts"],"sourcesContent":["import { stripUrlQueryAndFragment } from '@sentry/core';\nimport type * as OxcParser from 'oxc-parser';\nimport type { ProgramBody } from './ast';\n\nexport type ModuleLang = 'js' | 'jsx' | 'ts' | 'tsx';\n\n/** Parses a module into an ESTree program. Throws when the code does not parse. */\nexport type ModuleParser = (code: string, id: string) => ProgramBody;\n\n/** The part of a bundler's plugin context that can parse code. */\nexport interface ParserContext {\n meta?: { rolldownVersion?: string };\n parse?(input: string, options?: object | null): unknown;\n}\n\nconst PARSER_UNAVAILABLE_MESSAGE =\n '[@sentry/bundler-plugins] Could not load `oxc-parser` for this platform. ' +\n 'Modules that need it will not be auto-instrumented.';\n\n// `undefined` while loading, `null` when it failed to load.\nlet oxc: typeof OxcParser | null | undefined;\nlet warnedParserUnavailable = false;\n\n// The import is dynamic so that a platform without an `oxc-parser` native\n// binary gets a warning instead of a failed build.\nconst oxcLoaded: Promise<boolean> = import('oxc-parser').then(\n module => {\n oxc = module;\n return true;\n },\n () => {\n oxc = null;\n return false;\n },\n);\n\n/** Resolves once `oxc-parser` has loaded or failed to load, with whether it is available. */\nexport function loadParser(): Promise<boolean> {\n return oxcLoaded;\n}\n\nexport function isParserLoading(): boolean {\n return oxc === undefined;\n}\n\n/** The source dialect a module id names by its extension. */\nexport function langFromId(id: string): ModuleLang {\n const extension = /\\.([cm]?[jt]sx?)$/.exec(stripUrlQueryAndFragment(id))?.[1] ?? 'js';\n if (extension === 'tsx') return 'tsx';\n if (extension === 'jsx') return 'jsx';\n return extension.endsWith('ts') ? 'ts' : 'js';\n}\n\n/**\n * The default {@link ModuleParser}, over `oxc-parser`. Throws when `oxc-parser`\n * has not loaded; see {@link loadParser}.\n */\nexport function parseModule(code: string, id: string, lang: ModuleLang = langFromId(id)): ProgramBody {\n if (!oxc) {\n if (oxc === null && !warnedParserUnavailable) {\n warnedParserUnavailable = true;\n // eslint-disable-next-line no-console\n console.warn(PARSER_UNAVAILABLE_MESSAGE);\n }\n throw new Error(oxc === null ? PARSER_UNAVAILABLE_MESSAGE : '`oxc-parser` has not loaded yet');\n }\n\n // `preserveParens: false` matches the AST Vite produces.\n const { program, errors } = oxc.parseSync(id, code, { lang, sourceType: 'module', preserveParens: false });\n if (errors.length > 0) {\n throw new Error(errors[0]?.message);\n }\n return program;\n}\n\n/**\n * A parser over Rolldown's own `this.parse`, which reads TypeScript when told\n * the dialect. Rollup's `this.parse` cannot, so it is not used.\n */\nexport function bundlerParser(context: ParserContext | undefined): ModuleParser | undefined {\n if (!context?.meta?.rolldownVersion || typeof context.parse !== 'function') return undefined;\n return (code, id) => context.parse?.(code, { lang: langFromId(id), preserveParens: false }) as ProgramBody;\n}\n"],"mappings":";;AAeA,MAAM,6BACJ;AAIF,IAAI;AACJ,IAAI,0BAA0B;AAI9B,MAAM,YAA8B,OAAO,aAAa,CAAC,MACvD,WAAU;CACR,MAAM;CACN,OAAO;AACT,SACM;CACJ,MAAM;CACN,OAAO;AACT,CACF;;AAGA,SAAgB,aAA+B;CAC7C,OAAO;AACT;AAEA,SAAgB,kBAA2B;CACzC,OAAO,QAAQ,KAAA;AACjB;;AAGA,SAAgB,WAAW,IAAwB;CACjD,MAAM,YAAY,oBAAoB,KAAK,yBAAyB,EAAE,CAAC,CAAC,GAAG,MAAM;CACjF,IAAI,cAAc,OAAO,OAAO;CAChC,IAAI,cAAc,OAAO,OAAO;CAChC,OAAO,UAAU,SAAS,IAAI,IAAI,OAAO;AAC3C;;;;;AAMA,SAAgB,YAAY,MAAc,IAAY,OAAmB,WAAW,EAAE,GAAgB;CACpG,IAAI,CAAC,KAAK;EACR,IAAI,QAAQ,QAAQ,CAAC,yBAAyB;GAC5C,0BAA0B;GAE1B,QAAQ,KAAK,0BAA0B;EACzC;EACA,MAAM,IAAI,MAAM,QAAQ,OAAO,6BAA6B,iCAAiC;CAC/F;CAGA,MAAM,EAAE,SAAS,WAAW,IAAI,UAAU,IAAI,MAAM;EAAE;EAAM,YAAY;EAAU,gBAAgB;CAAM,CAAC;CACzG,IAAI,OAAO,SAAS,GAClB,MAAM,IAAI,MAAM,OAAO,EAAE,EAAE,OAAO;CAEpC,OAAO;AACT;;;;;AAMA,SAAgB,cAAc,SAA8D;CAC1F,IAAI,CAAC,SAAS,MAAM,mBAAmB,OAAO,QAAQ,UAAU,YAAY,OAAO,KAAA;CACnF,QAAQ,MAAM,OAAO,QAAQ,QAAQ,MAAM;EAAE,MAAM,WAAW,EAAE;EAAG,gBAAgB;CAAM,CAAC;AAC5F"}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
// src/rewriter/report.ts
|
|
2
|
+
function createReport() {
|
|
3
|
+
return {
|
|
4
|
+
wrapped: [],
|
|
5
|
+
skipped: [],
|
|
6
|
+
alreadyWrapped: []
|
|
7
|
+
};
|
|
8
|
+
}
|
|
9
|
+
/** The warning for the skipped sites of a module, or `undefined` when none were skipped. */
|
|
10
|
+
function formatReport(report, id) {
|
|
11
|
+
if (report.skipped.length === 0) return void 0;
|
|
12
|
+
return `[Sentry] Could not auto-instrument ${report.skipped.join(" and ")} in ${id}.`;
|
|
13
|
+
}
|
|
14
|
+
export { createReport, formatReport };
|
|
15
|
+
|
|
16
|
+
//# sourceMappingURL=report.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"report.js","names":[],"sources":["../../../src/rewriter/report.ts"],"sourcesContent":["/** What a rewrite did with the sites it found, by site label. */\nexport interface RewriteReport {\n wrapped: string[];\n /** Sites the rewrite could not wrap, for the user to wrap by hand. */\n skipped: string[];\n /** Sites the user already wrapped. */\n alreadyWrapped: string[];\n}\n\nexport function createReport(): RewriteReport {\n return { wrapped: [], skipped: [], alreadyWrapped: [] };\n}\n\n/** The warning for the skipped sites of a module, or `undefined` when none were skipped. */\nexport function formatReport(report: RewriteReport, id: string): string | undefined {\n if (report.skipped.length === 0) return undefined;\n return `[Sentry] Could not auto-instrument ${report.skipped.join(' and ')} in ${id}.`;\n}\n"],"mappings":";AASA,SAAgB,eAA8B;CAC5C,OAAO;EAAE,SAAS,CAAC;EAAG,SAAS,CAAC;EAAG,gBAAgB,CAAC;CAAE;AACxD;;AAGA,SAAgB,aAAa,QAAuB,IAAgC;CAClF,IAAI,OAAO,QAAQ,WAAW,GAAG,OAAO,KAAA;CACxC,OAAO,sCAAsC,OAAO,QAAQ,KAAK,OAAO,EAAE,MAAM,GAAG;AACrF"}
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import { bundlerParser, isParserLoading, loadParser, parseModule } from "./parse.js";
|
|
2
|
+
import { createReport, formatReport } from "./report.js";
|
|
3
|
+
import MagicString from "magic-string";
|
|
4
|
+
import { basename } from "node:path";
|
|
5
|
+
// src/rewriter/rewriter.ts
|
|
6
|
+
function createRewriteState(code) {
|
|
7
|
+
return {
|
|
8
|
+
ms: new MagicString(code),
|
|
9
|
+
needsImport: false,
|
|
10
|
+
wrappedLocals: /* @__PURE__ */ new Map(),
|
|
11
|
+
imports: /* @__PURE__ */ new Set(),
|
|
12
|
+
report: createReport()
|
|
13
|
+
};
|
|
14
|
+
}
|
|
15
|
+
function createCallSiteRewriter(rules, options = {}) {
|
|
16
|
+
const rewrite = (matching, code, id, parse) => {
|
|
17
|
+
let ast;
|
|
18
|
+
try {
|
|
19
|
+
ast = parse(code, id);
|
|
20
|
+
} catch {
|
|
21
|
+
return null;
|
|
22
|
+
}
|
|
23
|
+
const state = createRewriteState(code);
|
|
24
|
+
const ctx = {
|
|
25
|
+
ast,
|
|
26
|
+
code,
|
|
27
|
+
id,
|
|
28
|
+
state
|
|
29
|
+
};
|
|
30
|
+
const finish = () => {
|
|
31
|
+
const warning = formatReport(state.report, id);
|
|
32
|
+
if (warning) options.logger?.warn(warning);
|
|
33
|
+
if (!state.ms.hasChanged()) return null;
|
|
34
|
+
return {
|
|
35
|
+
code: state.ms.toString(),
|
|
36
|
+
map: state.ms.generateMap({ hires: true })
|
|
37
|
+
};
|
|
38
|
+
};
|
|
39
|
+
const pending = applyRules(matching, ctx, 0);
|
|
40
|
+
return pending ? pending.then(finish) : finish();
|
|
41
|
+
};
|
|
42
|
+
return { transform(code, id, context) {
|
|
43
|
+
const matching = rules.filter((rule) => matches(rule.include, code, id));
|
|
44
|
+
if (matching.length === 0) return null;
|
|
45
|
+
const parse = options.parse ?? bundlerParser(context) ?? parseModule;
|
|
46
|
+
if (isParserLoading()) return loadParser().then(() => rewrite(matching, code, id, parse));
|
|
47
|
+
return rewrite(matching, code, id, parse);
|
|
48
|
+
} };
|
|
49
|
+
}
|
|
50
|
+
function matches(include, code, id) {
|
|
51
|
+
if (include.id && !include.id.test(id)) return false;
|
|
52
|
+
if (include.basename && !include.basename.test(basename(id))) return false;
|
|
53
|
+
if (include.contains && !include.contains.every((substring) => code.includes(substring))) return false;
|
|
54
|
+
return true;
|
|
55
|
+
}
|
|
56
|
+
/** Applies the rules in order, staying synchronous until a rule returns a promise. */
|
|
57
|
+
function applyRules(rules, ctx, from) {
|
|
58
|
+
for (let index = from; index < rules.length; index++) {
|
|
59
|
+
const pending = rules[index]?.apply(ctx);
|
|
60
|
+
if (pending instanceof Promise) return pending.then(() => applyRules(rules, ctx, index + 1));
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
export { createCallSiteRewriter, createRewriteState };
|
|
64
|
+
|
|
65
|
+
//# sourceMappingURL=rewriter.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"rewriter.js","names":[],"sources":["../../../src/rewriter/rewriter.ts"],"sourcesContent":["import { basename } from 'node:path';\nimport MagicString, { type SourceMap } from 'magic-string';\nimport type { ProgramBody } from './ast';\nimport {\n bundlerParser,\n isParserLoading,\n loadParser,\n type ModuleParser,\n parseModule,\n type ParserContext,\n} from './parse';\nimport { createReport, formatReport, type RewriteReport } from './report';\n\n/** The edits a rewrite makes to one module, shared by every rule that runs on it. */\nexport interface RewriteState {\n /** Positions are always relative to the original source. */\n ms: MagicString;\n /** Set once the rewritten code references a binding the caller must import. */\n needsImport: boolean;\n /** Local binding name → the binding that holds its wrapper. */\n wrappedLocals: Map<string, string>;\n /** Import statements already added to this module. */\n imports: Set<string>;\n report: RewriteReport;\n}\n\nexport function createRewriteState(code: string): RewriteState {\n return {\n ms: new MagicString(code),\n needsImport: false,\n wrappedLocals: new Map(),\n imports: new Set(),\n report: createReport(),\n };\n}\n\n/** Which modules a rule runs on. Every given condition must hold. */\nexport interface RuleInclude {\n /** Tested against the full module id. */\n id?: RegExp;\n /** Tested against the last path segment of the module id. */\n basename?: RegExp;\n /** Substrings the source must contain, checked before parsing. */\n contains?: string[];\n}\n\nexport interface RuleContext {\n ast: ProgramBody;\n code: string;\n id: string;\n state: RewriteState;\n}\n\nexport interface RewriteRule {\n name: string;\n include: RuleInclude;\n apply(ctx: RuleContext): void | Promise<void>;\n}\n\nexport interface RewriterOptions {\n /**\n * Defaults to Rolldown's `this.parse` when the transform gets a Rolldown\n * plugin context, and to {@link parseModule} otherwise.\n */\n parse?: ModuleParser;\n /** Receives the warning for sites a rule could not wrap. */\n logger?: { warn(message: string): void };\n}\n\nexport interface RewriteOutput {\n code: string;\n map: SourceMap;\n}\n\nexport interface CallSiteRewriter {\n /**\n * Runs every matching rule on one module. Returns `null` when nothing\n * changed. The result is a promise only while `oxc-parser` is still\n * loading, or when a rule's `apply` returns one.\n *\n * @param context the bundler's plugin context, for its parser\n */\n transform(code: string, id: string, context?: ParserContext): RewriteOutput | null | Promise<RewriteOutput | null>;\n}\n\nexport function createCallSiteRewriter(rules: RewriteRule[], options: RewriterOptions = {}): CallSiteRewriter {\n const rewrite = (\n matching: RewriteRule[],\n code: string,\n id: string,\n parse: ModuleParser,\n ): RewriteOutput | null | Promise<RewriteOutput | null> => {\n let ast: ProgramBody;\n try {\n ast = parse(code, id);\n } catch {\n return null;\n }\n\n const state = createRewriteState(code);\n const ctx: RuleContext = { ast, code, id, state };\n const finish = (): RewriteOutput | null => {\n const warning = formatReport(state.report, id);\n if (warning) options.logger?.warn(warning);\n if (!state.ms.hasChanged()) return null;\n return { code: state.ms.toString(), map: state.ms.generateMap({ hires: true }) };\n };\n\n const pending = applyRules(matching, ctx, 0);\n return pending ? pending.then(finish) : finish();\n };\n\n return {\n transform(code, id, context) {\n const matching = rules.filter(rule => matches(rule.include, code, id));\n if (matching.length === 0) return null;\n\n const parse = options.parse ?? bundlerParser(context) ?? parseModule;\n // Rules may parse other modules with `parseModule`, so it has to be ready\n // whichever parser reads this one.\n if (isParserLoading()) {\n return loadParser().then(() => rewrite(matching, code, id, parse));\n }\n return rewrite(matching, code, id, parse);\n },\n };\n}\n\nfunction matches(include: RuleInclude, code: string, id: string): boolean {\n if (include.id && !include.id.test(id)) return false;\n if (include.basename && !include.basename.test(basename(id))) return false;\n if (include.contains && !include.contains.every(substring => code.includes(substring))) return false;\n return true;\n}\n\n/** Applies the rules in order, staying synchronous until a rule returns a promise. */\nfunction applyRules(rules: RewriteRule[], ctx: RuleContext, from: number): Promise<void> | undefined {\n for (let index = from; index < rules.length; index++) {\n const pending = rules[index]?.apply(ctx);\n if (pending instanceof Promise) {\n return pending.then(() => applyRules(rules, ctx, index + 1));\n }\n }\n return undefined;\n}\n"],"mappings":";;;;;AA0BA,SAAgB,mBAAmB,MAA4B;CAC7D,OAAO;EACL,IAAI,IAAI,YAAY,IAAI;EACxB,aAAa;EACb,+BAAe,IAAI,IAAI;EACvB,yBAAS,IAAI,IAAI;EACjB,QAAQ,aAAa;CACvB;AACF;AAmDA,SAAgB,uBAAuB,OAAsB,UAA2B,CAAC,GAAqB;CAC5G,MAAM,WACJ,UACA,MACA,IACA,UACyD;EACzD,IAAI;EACJ,IAAI;GACF,MAAM,MAAM,MAAM,EAAE;EACtB,QAAQ;GACN,OAAO;EACT;EAEA,MAAM,QAAQ,mBAAmB,IAAI;EACrC,MAAM,MAAmB;GAAE;GAAK;GAAM;GAAI;EAAM;EAChD,MAAM,eAAqC;GACzC,MAAM,UAAU,aAAa,MAAM,QAAQ,EAAE;GAC7C,IAAI,SAAS,QAAQ,QAAQ,KAAK,OAAO;GACzC,IAAI,CAAC,MAAM,GAAG,WAAW,GAAG,OAAO;GACnC,OAAO;IAAE,MAAM,MAAM,GAAG,SAAS;IAAG,KAAK,MAAM,GAAG,YAAY,EAAE,OAAO,KAAK,CAAC;GAAE;EACjF;EAEA,MAAM,UAAU,WAAW,UAAU,KAAK,CAAC;EAC3C,OAAO,UAAU,QAAQ,KAAK,MAAM,IAAI,OAAO;CACjD;CAEA,OAAO,EACL,U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