How to use esprima - 10 common examples

To help you get started, we’ve selected a few esprima examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github darlanalves / angular-di-annotations / test / Generator.spec.js View on Github external
}];

				// AngularStub creates this variable to check the injections
				lib.constants.MODULE = '$module';

				var node = TestHelper.createFunctionNode(this.functionName, this.functionParams, annotationTags);
				var code = Generator.generateCodeForNode(node);
				var expectedParams = '[\'%1\']'.replace('%1', this.functionParams.join('\',\''));
				var expectedCode = "%module.%type('%name', %value);\n%value.$inject=%injection;"
					.replace('%module', '$module')
					.replace('%type', dependencyType)
					.replace('%name', this.dependencyName)
					.replace(/%value/g, this.functionName)
					.replace('%injection', expectedParams);

				var codeTokens = esprima.tokenize(code),
					expectedTokens = esprima.tokenize(expectedCode);

				compareTokens(codeTokens, expectedTokens);
			}
		});
github SAP / ui5-builder / lib / lbt / resources / ResourcePool.js View on Github external
async function determineDependencyInfo(resource, rawInfo, pool) {
	const info = new ModuleInfo(resource.name);
	info.size = resource.fileSize;
	if ( /\.js$/.test(resource.name) ) {
		// console.log("analyzing %s", resource.file);
		const code = await resource.buffer();
		info.size = code.length;
		const promises = [];
		try {
			const ast = esprima.parseScript(code.toString(), {comment: true});
			jsAnalyzer.analyze(ast, resource.name, info);
			new XMLCompositeAnalyzer(pool).analyze(ast, resource.name, info);
		} catch (error) {
			log.error("failed to parse or analyze %s:", resource.name, error);
		}
		if ( rawInfo ) {
			info.rawModule = true;
			// console.log("adding preconfigured dependencies for %s:", resource.name, rawInfo.dependencies);
			rawInfo.dependencies.forEach( (dep) => info.addDependency(dep) );
			if ( rawInfo.requiresTopLevelScope ) {
				info.requiresTopLevelScope = true;
			}
			if ( rawInfo.ignoredGlobals ) {
				info.ignoredGlobals = rawInfo.ignoredGlobals;
			}
		}
github SAP / ui5-webcomponents / packages / core / lib / esm-abs-to-rel / index.js View on Github external
const convertImports = (srcPath) => {
	let changed = false;
	// console.log("scanning imports of", srcPath);
	let code = fs.readFileSync(srcPath).toString();
	const tree = esprima.parseModule(code);
	const importer = srcPath.replace(basePath, "");
	const importerDir = path.dirname(importer);
	// console.log("-> ", importer);
	tree.body.forEach(node => {
		if (node.type === "ImportDeclaration") {
			let importee = node.source.value;
			if (importee.startsWith(".")) {
				return;
			}
			let importeeDir = path.dirname(importee);
			let importeeFile = path.basename(importee);
			let relativePath = path.relative(importerDir, importeeDir);
			if (relativePath.length === 0) {
				relativePath = "."
			}
			if (!relativePath.startsWith(".")) {
github SAP / ui5-webcomponents / packages / main / lib / less-to-json-imports / index.js View on Github external
const convertImports = (srcPath) => {
	let changed = false;
	// console.log("scanning imports of", srcPath);
	let code = fs.readFileSync(srcPath).toString();
	if (code.includes("import.meta.url")) {
		console.log(`skipping convertion for ${srcPath} due to import.meta.url usage`);
		return;
	}
	const tree = esprima.parseModule(code);
	const importer = srcPath.replace(basePath, "");
	const importerDir = path.dirname(importer);
	tree.body.forEach(node => {
		if (node.type === "ImportDeclaration" && node.source.value.endsWith(".less")) {
			let importee = node.source.value;
			node.source.value = importee.replace(".less", "-css.js");
			changed = true;
			// console.log(importee, "from", importer);
		}
	});

	if (changed) {
		fs.writeFileSync(srcPath, escodegen.generate(tree));
	}
}
github SAP / ui5-builder / lib / lbt / utils / ASTUtils.js View on Github external
function isNamedObject(node, objectPath, length) {
	// console.log("checking for named object ", node, objectPath, length);
	while ( length > 1
			&& node.type === Syntax.MemberExpression
			&& isIdentifier(node.property, objectPath[length-1]) ) {
		node = node.object;
		length--;
	}
	return length === 1 && isIdentifier(node, objectPath[0]);
}
github SAP / ui5-builder / lib / lbt / calls / SapUiDefine.js View on Github external
// assert(String)
			this.name = args[i++].value;
		}

		if ( args[i].type === Syntax.ArrayExpression ) {
			this.dependencyArray = args[i++];
			this.dependencies = this.dependencyArray.elements.map( (elem) => {
				if ( !isString(elem) ) {
					throw new TypeError();
				}
				return ModuleName.resolveRelativeRequireJSName(this.name, elem.value);
			});
			this.dependencyInsertionIdx = this.dependencyArray.elements.length;
		}

		if ( args[i].type === Syntax.FunctionExpression ) {
			this.factory = args[i++];
			params = this.factory.params;
			this.paramNames = params.map( (param) => {
				if ( param.type !== Syntax.Identifier ) {
					throw new TypeError();
				}
				return param.name;
			});
			if ( this.factory.params.length < this.dependencyInsertionIdx ) {
				this.dependencyInsertionIdx = this.factory.params.length;
			}
		}

		// console.log("declared dependencies: " + this.dependencies);
	}
github thomasboyt / defeatureify / index.js View on Github external
var featureify = function(source, config) {
  config = config || {};
  enabled = config.enabled || {};

  var namespace = config.namespace || "Ember";

  var tree = esprima.parse(source, {
    range: true
  });

  var sourceModifier = new SourceModifier(source);
  var walk = function(node) {
    if (node.type === "IfStatement") {
      if (node.test.type === "CallExpression" && node.test.callee) {
        // test object.property.property
        if (node.test.callee.object &&
            node.test.callee.object.object &&
            node.test.callee.object.property) {
          // test namespace.FEATURES.isEnabled()
          if (node.test.callee.object.object.name === namespace &&
              node.test.callee.object.property.name === "FEATURES" &&
              node.test.callee.property.name === "isEnabled") {
            var featureName = node.test.arguments[0].value;
github jaredly / treed / plugins / ijs / eval.js View on Github external
module.exports = function (text, output, scope) {

  var tree = esprima.parse(text);
  var tracker = newScope()

  crawlScope(tree, function (node, scope, parent, param, path) {
    var fn = crawls[node.type]
    if (fn) fn(node, scope, parent, param, path)
  }, tracker, newScope);

  var globals = Object.getOwnPropertyNames(window)
    .concat(['arguments', 'this', 'setTimeout', 'clearTimeout', 'setInterval', 'clearInterval']);

  // fixScope(tracker, tree, globals)

  catchOutputs(tree, '$out')

  var code = escodegen.generate(tree)
  code += ';' + tracker.declared.map(function (name) {
github jscs-dev / node-jscs / lib / modules / string-checker.js View on Github external
checkString: function(str, filename) {
        filename = filename || 'input';
        var tree;
        str = str.replace(/^#![^\n]+\n/, '\n');
        try {
            tree = esprima.parse(str, {loc: true, range: true, comment: true, tokens: true});
        } catch (e) {
            throw new Error('Syntax error at ' + filename + ': ' + e.message);
        }
        var file = new JsFile(filename, str, tree);
        var errors = new Errors(file);
        this._activeRules.forEach(function(rule) {

            // Do not process the rule if it's equals to null (#203)
            if (this._config[rule.getOptionName()] !== null ) {
                rule.check(file, errors);
            }

        }, this);

        // sort errors list to show errors as they appear in source
        errors.getErrorList().sort(function(a, b) {
github probmods / webppl / src / transforms / adify.js View on Github external
function addAdRequire(ast, adRequirePath) {
  var body = ast.body;
  var useStrictNode = body[0];
  assert.ok(isUseStrictExpr(useStrictNode));
  var requireNode = parse("var ad = require('" + adRequirePath + "');").body[0];
  var rest = body.slice(1);
  // Remove any existing calls to require ad, to avoid duplication.
  var restFiltered = rest.filter(function(node) {
    return !_.isEqual(node, requireNode);
  });
  return build.program([useStrictNode, requireNode].concat(restFiltered));
}