Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
export default function getStandaloneModule ( options ) {
let code, ast;
if ( typeof options.source === 'object' ) {
code = options.source.code;
ast = options.source.ast;
} else {
code = options.source;
}
let toRemove = [];
let mod = {
body: new MagicString( code ),
ast: ast || ( acorn.parse( code, {
ecmaVersion: 6,
sourceType: 'module',
onComment ( block, text, start, end ) {
// sourceMappingURL comments should be removed
if ( !block && SOURCEMAPPINGURL_REGEX.test( text ) ) {
toRemove.push({ start, end });
}
}
}))
};
toRemove.forEach( ({ start, end }) => mod.body.remove( start, end ) );
let { imports, exports, defaultExport } = findImportsAndExports( mod.ast, code );
public async preCompilation(code: string): Promise {
if (isESMFormat(this.outputOptions.format)) {
await this.deriveExports(code);
const source = new MagicString(code);
for (const key of this.originalExports.keys()) {
const value: ExportDetails = this.originalExports.get(key) as ExportDetails;
// Remove export statements before Closure Compiler sees the code
// This prevents CC from transpiling `export` statements when the language_out is set to a value
// where exports were not part of the language.
source.remove(...value.range);
// Window scoped references for each key are required to ensure Closure Compilre retains the code.
if (value.source === null) {
source.append(`\nwindow['${value.closureName}'] = ${value.local};`);
} else {
source.append(`\nwindow['${value.closureName}'] = ${value.exported};`);
}
}
export default function preproc (code, filename, _options) {
const options = parseOptions(filename, _options)
const magicStr = new MagicString(code)
const parser = new Parser(options)
const re = parser.getRegex() // $1:keyword, $2:expression
let changes = false
let output = true
let hideStart = 0
let lastIndex
let match
re.lastIndex = lastIndex = 0
while ((match = re.exec(code))) {
let index = match.index
if (output) {
}
timeStart('generate ast', 3);
this.esTreeAst = ast || tryParse(this, this.graph.acornParser, this.graph.acornOptions);
markPureCallExpressions(this.comments, this.esTreeAst);
timeEnd('generate ast', 3);
this.resolvedIds = resolvedIds || Object.create(null);
// By default, `id` is the file name. Custom resolvers and loaders
// can change that, but it makes sense to use it for the source file name
const fileName = this.id;
this.magicString = new MagicString(code, {
filename: (this.excludeFromSourcemap ? null : fileName) as string, // don't include plugin helpers in sourcemap
indentExclusionRanges: []
});
this.removeExistingSourceMap();
timeStart('analyse ast', 3);
this.astContext = {
addDynamicImport: this.addDynamicImport.bind(this),
addExport: this.addExport.bind(this),
addImport: this.addImport.bind(this),
addImportMeta: this.addImportMeta.bind(this),
annotations: (this.graph.treeshakingOptions &&
this.graph.treeshakingOptions.annotations) as boolean,
code, // Only needed for debugging
deoptimizationTracker: this.graph.deoptimizationTracker,
function combine(bundle) {
bundle.body = new MagicString.Bundle({
separator: '\n\n'
});
// give each module in the bundle a unique name
populateModuleNames(bundle);
// determine which specifiers are imported from
// external modules
populateExternalModuleImports(bundle);
// determine which identifiers need to be replaced
// inside this bundle
populateIdentifierReplacements(bundle);
bundle.exports = resolveExports(bundle);
function createBundle(
modules: { dep: string; file: MagicString; hasInvalidShim: boolean }[],
) {
const bundle = new Bundle();
const depsWithInvalidShims: string[] = [];
bundle.prepend(
`/* Generated by @magento/baler - ${new Date().toISOString()} */\n\n`,
);
for (const { dep, file, hasInvalidShim } of modules) {
bundle.addSource({
filename: `../${dep}.js`,
content: file,
});
if (hasInvalidShim) depsWithInvalidShims.push(dep);
}
return { bundle, depsWithInvalidShims };
}
render ( options = {} ) {
const format = options.format || 'es6';
// Determine export mode - 'default', 'named', 'none'
const exportMode = getExportMode( this, options.exports );
let magicString = new MagicString.Bundle({ separator: '\n\n' });
let usedModules = [];
this.orderedModules.forEach( module => {
const source = module.render( format === 'es6' );
if ( source.toString().length ) {
magicString.addSource( source );
usedModules.push( module );
}
});
const intro = [ options.intro ]
.concat(
this.plugins.map( plugin => plugin.intro && plugin.intro() )
)
.filter( Boolean )
.join( '\n\n' );
// correct SourceMapSegment tuples. Cast it here to gain type safety.
let source = new Link(map as ExistingDecodedSourceMap, moduleSources);
source = bundleSourcemapChain.reduce(linkMap, source);
let { sources, sourcesContent, names, mappings } = source.traceMappings();
if (file) {
const directory = dirname(file);
sources = sources.map((source: string) => relative(directory, source));
file = basename(file);
}
sourcesContent = (excludeContent ? null : sourcesContent) as string[];
return new SourceMap({ file, sources, sourcesContent, names, mappings });
}
files.map(file => {
if (PREFIX_SRC_PATTERN.test(file)) {
const module = bundle[file];
if (isAsset(module)) {
return;
}
module.fileName = rewrite(module.fileName);
module.facadeModuleId = rewrite(module.fileName);
if (module.code) {
const magicString = new MagicString(module.code);
const ast = this.parse(module.code, {
sourceType: 'module',
});
const extract = (node: Node) => {
const req =
getRequireSource(node) ||
getImportSource(node) ||
getExportSource(node);
if (req) {
const { start, end } = req;
const distance = req.value
.split('/')
.filter((d: string) => d === '..').length;
const targetDistance = winPath(
path.relative(path.dirname(file), options.rootDir)
transform(code, id) {
if (!filter(id)) return null;
if (functions.length > 0 && !firstpass.test(code)) return null;
let ast;
try {
ast = this.parse(code);
} catch (err) {
err.message += ` in ${id}`;
throw err;
}
const magicString = new MagicString(code);
let edited = false;
function remove(start, end) {
while (whitespace.test(code[start - 1])) start -= 1;
magicString.remove(start, end);
}
function isBlock(node) {
return node && (node.type === 'BlockStatement' || node.type === 'Program');
}
function removeExpression(node) {
const { parent } = node;
if (parent.type === 'ExpressionStatement') {
removeStatement(parent);