Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
// Babylon currently has...abysmal support for typescript. We need to transpile
// it with the standard typescript library first.
// TODO: When Typescript support lands in Babylon, remove this: https://github.com/babel/babylon/issues/320
if (path.parse(template.identifier).ext === ".tsx") {
let wat = typescript.transpileModule(template.data, {
compilerOptions: {
module: typescript.ModuleKind.ES2015,
jsx: typescript.JsxEmit.Preserve,
target: typescript.ScriptTarget.Latest,
},
});
template.data = wat.outputText;
}
analysis.template.ast = some(babylon.parse(template.data, this.options.parserOptions));
} catch (e) {
process.chdir(oldDir);
throw new JSXParseError(`Error parsing '${template.identifier}'\n${e.message}\n\n${template.data}: ${e.message}`, { filename: template.identifier });
}
// The blocks importer will insert a promise that resolves to a `ResolvedBlock`
// for each CSS Blocks import it encounters. Every new `tsx` or `jsx` file discovered
// will kick of another `Analyzer.parse()` for that file.
let blockPromises: Promise[] = [];
let childTemplatePromises: Promise[] = [];
traverse(unwrap(analysis.template.ast), importVisitor(template, this, analysis, blockPromises, childTemplatePromises, this.options));
// Once all blocks this file is waiting for resolve, resolve with the File object.
// After import traversal, it is safe to move back to our old working directory.
process.chdir(oldDir);
// Read the content of the file as a string.
const content = fs.readFileSync(filename, 'utf-8');
// Now we try to figure out which files this file depends on. We can do that
// by looking at its content for import strings. However, this is a pretty
// clunky approach, so instead, we will use a JavaScript parser.
//
// JavaScript parsers are tools that can read and understand JavaScript code.
// They generate a more abstract model called an AST (abstract syntax tree).
// I strongly suggest that you look at AST Explorer (https://astexplorer.net)
// to see how an AST looks like.
//
// The AST contains a lot of information about our code. We can query it to
// understand what our code is trying to do.
const ast = babylon.parse(content, {
sourceType: 'module',
});
// This array will hold the relative paths of modules this module depends on.
const dependencies = [];
// We traverse the AST to try and understand which modules this module depends
// on. To do that, we check every import declaration in the AST.
traverse(ast, {
// EcmaScript modules are fairly easy because they are static. This means
// that you can't import a variable, or conditionally import another module.
// Every time we see an import statement we can just count its value as a
// dependency.
ImportDeclaration: ({node}) => {
// We push the value that we import into the dependencies array.
dependencies.push(node.source.value);
}
switch (ext) {
case '.mjs':
try {
return babylon.parse(code, { sourceType: 'module' });
} catch (e) { /* ignore */ }
try {
return babylon.parse(code);
} catch (e) { /* ignore */ }
break;
case '.js':
try {
return babylon.parse(code);
} catch (e) { /* ignore */ }
try {
return babylon.parse(code, { sourceType: 'module' });
} catch (e) { /* ignore */ }
break;
}
return 'unparsed';
}
"classConstructorCall",
"classProperties",
"decorators",
"doExpressions",
"exponentiationOperator",
"exportExtensions",
"functionBind",
"functionSent",
"objectRestSpread",
"trailingFunctionCommas"
]
};
var ast;
try {
ast = parse(code, opts);
} catch (err) {
if (err instanceof SyntaxError) {
err.lineNumber = err.loc.line;
err.column = err.loc.column + 1;
// remove trailing "(LINE:COLUMN)" acorn message and add in esprima syntax error message start
err.message = "Line " + err.lineNumber + ": " + err.message.replace(/ \((\d+):(\d+)\)$/, "");
}
throw err;
}
// remove EOF token, eslint doesn't use this for anything and it interferes with some rules
// see https://github.com/babel/babel-eslint/issues/2 for more info
// todo: find a more elegant way to do this
ast.tokens.pop();
CallExpression(callPath: BabelPath) {
if (
looksLike(callPath, {
node: {
callee: { type: 'Identifier', name: 'test' },
},
})
) {
const testTitlePath = callPath.get('arguments')[0]
existTestCases.push(testTitlePath.get('value').node)
}
},
})
const code = fs.readFileSync(from, 'utf8')
const ast = parse(code, {
sourceType: 'module',
plugins: ['flow', 'objectRestSpread'],
})
const typeNameSet: Set = new Set()
traverse(ast, {
TypeAlias(path: BabelPath) {
if (path.get('id').node.name === 'Action') {
const right = path.get('right')
if (right.isUnionTypeAnnotation()) {
for (const typePath of right.get('types')) {
typeNameSet.add(typePath.get('id').node.name)
}
} else if (right.isGenericTypeAnnotation()) {
typeNameSet.add(right.get('id').node.name)
process.stdin.on('end', function() {
var ast = babylon.parse(source, { plugins: ["classProperties", "jsx", "objectRestSpread"], strictMode: false, sourceType: "module" });
var program = ast.program;
console.log(
JSON.stringify(format(program))
);
});
function _parse(code, opts) {
return babylon.parse(code, {
...opts,
tokens: true
});
}
export default function convert(code) {
const ast = babylon.parse(code, {
sourceType: "module",
plugins: ["jsx"]
});
const context = {
namedExport: null,
defaultExport: null,
identifier: null,
type: null,
props: [],
jsxBodyTree: null
};
walkTree(ast.program, context);
return output(context);
}
module.exports = (res, { content }) => {
try {
let entry;
const ast = babylon.parse(content, { sourceType: 'module' });
traverse(ast, {
Identifier: {
enter(traversePath) {
if (traversePath.node.name === 'entry') {
let entryValueInWebpackConfig = content
.slice(traversePath.parent.value.start + 1, traversePath.parent.value.end - 1)
.trim();
let entryValuePlusRootDir = path.join(res.rootDir, entryValueInWebpackConfig);
if (fs.existsSync(entryValueInWebpackConfig)) {
entry = entryValueInWebpackConfig;
} else if (fs.existsSync(entryValuePlusRootDir)) {
entry = entryValuePlusRootDir;
}
}
},
},
static parseFrom(filePath, resolver) {
try {
const ast = Babylon.parse(fs.readFileSync(filePath, 'utf-8'), {
sourceType: 'module',
plugins: [
'jsx',
'flow',
'estree',
'typescript',
'doExpressions',
'objectRestSpread',
'decorators',
'decorators2',
'classProperties',
'classPrivateProperties',
'classPrivateMethods',
'exportExtensions',
'asyncGenerators',
'functionBind',