How to use the esprima.parseScript function in esprima

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 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 pilagod / js-tracker / test / benchmark / ESTreeNodeFinder.ts View on Github external
function initializeESTreeNodes(sets) {
    let script = ''
    for (let i = 0; i < sets; i++) {
      script += 'div.addEventListener(\'click\', function () {\n    div.style.color = \'red\'\n})\n'
    }
    const nodes = []
    esprima.parseScript(script, { loc: true }, (node) => {
      nodes.push(node)
    })
    return nodes
  }
github TradeMe / tractor / packages / file-javascript / src / javascript-file.spec.ts View on Github external
it('should rebuild any regular expressions in the AST', async () => {
            const ast = parseScript('/regex/', { comment: true });
            const fileStructure = new FileStructure(path.resolve(__dirname, '../fixtures/save'));
            const file = new JavaScriptFile(path.join(fileStructure.path, 'save-regex.js'), fileStructure);

            await file.save(ast);
            expect(ast).to.deep.equal({
                body: [{
                    expression: {
                        raw: '/regex/',
                        regex: {
                            flags: '',
                            pattern: 'regex'
                        },
                        type: 'Literal',
                        value: /regex/,
                    },
                    type: 'ExpressionStatement'
github TradeMe / tractor / packages / file-javascript / src / javascript-file.spec.ts View on Github external
it(`should include the file's AST`, () => {
            const ast = parseScript('');
            const fileStructure = new FileStructure(path.resolve(__dirname, '../fixtures'));
            const filePath = path.join(fileStructure.path, 'test.js');

            const file = new JavaScriptFile(filePath, fileStructure);
            file.ast = ast;

            file.serialise();

            expect(file.ast).to.equal(ast);
        });
    });
github TradeMe / tractor / packages / file-javascript / src / javascript-file-refactorer.spec.js View on Github external
it(`should update an identifier in a file's AST`, () => {
            let ast = esprima.parseScript('var oldName');

            let fileStructure = new FileStructure(path.join(path.sep, 'file-structure'));
            let filePath = path.join(path.sep, 'file-structure', 'directory', 'file.js');

            let file = new JavaScriptFile(filePath, fileStructure);
            file.ast = ast;

            JavaScriptFileRefactorer.identifierChange(file, {
                oldName: 'oldName',
                newName: 'newName'
            });

            let [identifier] = esquery(ast, 'Identifier');

            expect(identifier.name).to.equal('newName');
        });
github ambientsprotocol / ambc / src / fromjs / index.js View on Github external
module.exports = function (input) {
  const js = fs.readFileSync(input || process.argv[2] || './source.js').toString()
  const parsed = esprima.parseScript(js)
  return parseBlock(parsed, null, 0, '', {names: {}, aliases: {}})
}
github Cherrison / CrackMinApp / nodejs / nodejs / wuWxml.js View on Github external
function doWxml(state,dir,name,code,z,xPool,rDs,wxsList,moreInfo){
	let rname=code.slice(code.lastIndexOf("return")+6).replace(/[\;\}]/g,"").trim();
	code=code.slice(code.indexOf("\n"),code.lastIndexOf("return")).trim();
	let r={son:[]};
	analyze(esprima.parseScript(code).body,z,{[rname]:r},xPool,{[rname]:r});
	let ans=[];
	for(let elem of r.son)ans.push(elemToString(elem,0,moreInfo));
	let result=[ans.join("")];
	for(let v in rDs){
		state[0]=v;
		let oriCode=rDs[v].toString();
		let rname=oriCode.slice(oriCode.lastIndexOf("return")+6).replace(/[\;\}]/g,"").trim();
		let tryPtr=oriCode.indexOf("\ntry{");
		let zPtr=oriCode.indexOf("var z=gz$gwx");
		let code=oriCode.slice(tryPtr+5,oriCode.lastIndexOf("\n}catch(")).trim();
		if(zPtr!=-1&&tryPtr>zPtr){
			let attach=oriCode.slice(zPtr);
			attach=attach.slice(0,attach.indexOf("()"))+"()\n";
			code=attach+code;
		}
		let r={tag:"template",v:{name:v},son:[]};
github codeforequity-at / botium-core / src / helpers / HookUtils.js View on Github external
} catch (err) {
    }
  }

  if (resultWithRequire) {
    if (_.isFunction(resultWithRequire)) {
      debug(`found hook, type: require, in ${tryLoadFile}`)
      return resultWithRequire
    } else {
      throw new Error(`Cant load hook ${tryLoadFile} because it is not a function`)
    }
  }

  if (_.isString(data)) {
    try {
      esprima.parseScript(data)
    } catch (err) {
      throw new Error(`Cant load hook, syntax is not valid - ${util.inspect(err)}`)
    }

    debug('Found hook, type: JavaScript as String')
    return data
  }

  throw new Error(`Not valid hook ${util.inspect(data)}`)
}
github TradeMe / tractor / packages / file-javascript / src / javascript-file.ts View on Github external
private _setAST (content: string): string {
        this.ast = parseScript(content, {
            comment: true
        });
        return content;
    }
}