Пример #1
0
 proxy.addFilter(function(httpData, next){
     if(bOpenUrl === true){
         var responseContent = httpData.responseContent;
         if(httpData.responseCode === 200 &&
             responseContent !== undefined &&
             httpData.responseType === 'js' &&
             pagerun.isMatchUrl(httpData.url, include)
             ){
                 // beautify the js code
                 if(beautify === true){
                     var syntax = esprima.parse(responseContent, { raw: true, tokens: true, range: true, comment: true });
                     syntax = escodegen.attachComments(syntax, syntax.comments, syntax.tokens);
                     responseContent = escodegen.generate(syntax, 
                         {
                             comment: true,
                             format: {
                                 indent: {
                                     style: '  '
                                 },
                                 quotes: 'single'
                             }
                         }
                     );
                 }
                 httpData.responseContent = jscover.instrument(responseContent, httpData.url);
         }
     }
     next();
 });
Пример #2
0
function uniffe(contents) {
  var comments = [];
  var tokens = [];

  var ast = acorn.parse(contents, {
    ranges: true,
    onComment: comments,
    onToken: tokens
  });

  escodegen.attachComments(ast, comments, tokens);

  if (ast.body[0].expression === undefined ||
      ast.body[0].expression.callee === undefined) {
    return contents;
  }

  var rootProgram = ast.body[0].expression.callee.body;

  rootProgram.type = 'Program';
  // drop use strict
  rootProgram.body = rootProgram.body.slice(1);
  // attach all leading comments from outside iffe
  rootProgram.leadingComments = ast.body[0].leadingComments;

  return escodegen.generate(rootProgram, {comment: true});
}
Пример #3
0
function convert(src, shouldCommentOut) {

	let comments = [],
		tokens = [];

    let opts = {
        ranges: true,
        ecmaVersion: 7
    }

	opts.plugins = {
		tropigate: true
	};

	opts.onComment = comments;
    opts.onToken = tokens;

	//Use plugin to transform the source
	let ast = acorn.parse(Prelude(src, doInjection), opts);

	if (shouldCommentOut) {
		escodegen.attachComments(ast, comments, tokens);
	}

	return escodegen.generate(ast, {
		comments: true
	});
}
Пример #4
0
var instrumentSource = function (source, fileName) {
    var syntax = esprima.parse(source, {
        raw: true,
        tokens: true,
        range: true,
        loc: true,
        comment: true
    });
    syntax = escodegen.attachComments(syntax, syntax.comments, syntax.tokens);
    var lclass, frags = [];

    function embed(node) {
        if (node.type == 'AssignmentExpression') {
            var leftName = escodegen.generate(node.left),
                left = leftName.split('.');
            if (left[0] == 'dc') {
                lclass = left[1];
                try {
                    frags.push({
                        index: node.range[0],
                        text: api[left[1]]['class']
                    });
                } catch (e) {}
            } else if (left[0] == '_chart') {
                if (api[lclass] && api[lclass][left[1]]) {
                    try {
                        frags.push({
                            index: node.range[0],
                            text: api[lclass][left[1]]
                        });
                    } catch (e) {
                        //console.log(e);
                    }
                }
            }
            embed(node.right);
        } else {
            for (var i in node) {
                if (typeof (node[i]) == 'object' && node[i]) {
                    embed(node[i]);
                }
            }
        }
    }
    embed(syntax);
    try {
        frags.map(function (f) {
            f.text = "/**\n" + f.text + "**/\n";
            var offset = f.index - source.lastIndexOf('\n', f.index);
            offset = new Array(offset).join(' ');
            f.text = f.text.replace(/(\r\n|\n|\r)/gm, "\n" + offset);
            f.text = f.text.replace(/\n\s+\n/gm,"\n\n");
            return f;
        });
    } catch (e) {
        //console.log(e);
    }

    return insert(source, frags);
};
Пример #5
0
function Tree(source, escodegenOptions, esprimaOptions) {
  this.esprimaOptionDefaults = _.merge({}, esprimaOptionDefaults, esprimaOptions);
  this.tree = esprima.parse(source.toString(), this.esprimaOptionDefaults);
  this.tree = escodegen.attachComments(this.tree, this.tree.comments, this.tree.tokens);
  this.body = new Body(this.tree.body);
  this.escodegenOptions = _.merge({}, escodegenOptionDefaults, escodegenOptions);
}
Пример #6
0
Файл: ast.js Проект: gdhuang/atg
function parse(str){
    var filename = str,
        code = str,
        ast;

    if(fs.existsSync(filename)) {
        code = fs.readFileSync(filename, 'utf-8');        
    } else {
        filename = '';
    }
    try {
        ast = esprima.parse(code, { comment: true, tokens: true, range: true, loc: true });
    } catch (err) {
        logger.error('fail to parse:' + code);
        throw err;
    }
    ast = escodegen.attachComments(ast, ast.comments, ast.tokens);
    ast.filename = filename;
    visitor.traverse(ast, function (node, path) {
        for(var i=0; i<path.length; i++) {
            if(typeof path[i].type !== 'undefined') {
                node.parent = path[i];
                break;
            }
        }
        
    });
    
    return ast;
}
Пример #7
0
	generate: function(syntax) {
        syntax = escodegen.attachComments(syntax, syntax.comments, syntax.tokens);
        var code = escodegen.generate(syntax, default_options);

        log.debug('\n\n:: generator.generate() - code::');
        log.debug(code);

        return code;
    }
Пример #8
0
exports.runInContext = function (code, contextifiedSandbox, options) {
  if (code === "this") {
    // Special case for during window creation.
    return contextifiedSandbox;
  }

  if (options === undefined) {
    options = {};
  }

  const comments = [];
  const tokens = [];
  const ast = acorn.parse(code, {
    ecmaVersion: 6,
    allowReturnOutsideFunction: true,
    ranges: true,
    // collect comments in Esprima's format
    onComment: comments,
    // collect token ranges
    onToken: tokens
  });

  // make sure we keep comments
  escodegen.attachComments(ast, comments, tokens);

  const globals = findGlobals(ast);
  for (let i = 0; i < globals.length; ++i) {
    if (globals[i].name === "window") {
      continue;
    }

    const nodes = globals[i].nodes;
    for (let j = 0; j < nodes.length; ++j) {
      const type = nodes[j].type;
      const name = nodes[j].name;
      nodes[j].type = "MemberExpression";
      nodes[j].property = { name, type };
      nodes[j].computed = false;
      nodes[j].object = {
        name: "window",
        type: "Identifier"
      };
    }
  }

  const lastNode = ast.body[ast.body.length - 1];
  if (lastNode.type === "ExpressionStatement") {
    lastNode.type = "ReturnStatement";
    lastNode.argument = lastNode.expression;
    delete lastNode.expression;
  }

  const rewrittenCode = escodegen.generate(ast, { comment: true });
  const suffix = options.filename !== undefined ? "\n//# sourceURL=" + options.filename : "";

  return Function("window", rewrittenCode + suffix).bind(contextifiedSandbox)(contextifiedSandbox);
};
Пример #9
0
module.exports.generateAST = function(js){
  var ast = esprima.parse(js, {
    raw: true,
    tokens: true,
    range: true,
    comment: true
  });
  ast = escodegen.attachComments(ast, ast.comments, ast.tokens);
  return ast;
};
Пример #10
0
 ast: function() {
   if (!this.derived.esprimaAst) {
     var ast = esprima.parse(this.source, {
       range: true,
       tokens: true,
       comment: true
     });
     ast = escodegen.attachComments(ast, ast.comments, ast.tokens);
     this.derived.esprimaAst = ast;
   }
   return this.derived.esprimaAst;
 },
Пример #11
0
 transform: function (src) {
     // https://github.com/Constellation/escodegen/issues/85
     let ast = esprima.parse(src, {
         range: true,
         tokens: true,
         comment: true
     });
     ast = escodegen.attachComments(ast, ast.comments, ast.tokens);
     delete ast.tokens;
     delete ast.comments;
     return ast;
 },
Пример #12
0
module.exports = function(jsCode) {
  var options = this.options;
  var ast = esprima.parse(jsCode, {
    range: true,
    tokens: true,
    comment: true
  });
  var attachedAst = escodegen.attachComments(ast, ast.comments, ast.tokens);
  var modifiedAst = estraverse.replace(attachedAst, unassert.createVisitor(options));
  this.callback(null, escodegen.generate(modifiedAst, {
    comment: true
  }), null);
};
Пример #13
0
exports.parse = function (input, options) {
    OBLIGATIONS.precondition(typeof input === 'string');
    var __result;
    options = options || {};
    options.comment = true;
    options.tokens = true;
    options.range = true;
    options.loc = true;
    var ast = esprima.parse(input, options);
    escodegen.attachComments(ast, ast.comments, ast.tokens);
    __result = ast;
    OBLIGATIONS.postcondition(__result && typeof __result === 'object');
    return __result;
};
Пример #14
0
var parse = function(string, path) {
  var ast, error;

  try {
    ast = espree.parse(string, { range: true, tokens: true, comment: true });
    escodegen.attachComments(ast, ast.comments, ast.tokens);
  } catch(err) {
    console.error("error parsing", path);
    error = err;
  }

  if (error) throw error;
  return ast;
};
Пример #15
0
    md.instrumentSource = function (source, fileName) {
        var syntax = esprima.parse(source, {
            raw: true,
            tokens: true,
            range: true,
            loc: true,
            comment: true
        });
        syntax = escodegen.attachComments(syntax, syntax.comments, syntax.tokens);

        var comments = md.extractComments(syntax);

        var fragments = comments.map(function (c) {
            var s = +(c.value[0] == '*'),
                e = +(c.value[c.value.length - 1] == '*'),
                value = c.value.slice(s, c.value.length - e).replace(/\s+$/, ''),
                r = /(\n[ \t]+)[^ \t\n]/g,
                prefix,
                result;

            while (result = r.exec(value)) {
                if (prefix === undefined || result[1].length < prefix.length)
                    prefix = result[1];
            }

            var aligned = value.split(prefix).join('\n').replace(/^\n+/, ''),
                assignment = c.
            for +"." + DOC + "=",
            doc = {
                value: aligned,
                for: c.
                for,
                from: c. in
            };

            if (fileName) {
                doc.file = fileName;
                doc.line = c.loc;
            }

            return {
                index: c.range[1] + 1,
                text: "\n" + assignment + JSON.stringify(doc) + "\n"
            };
        });

        return md.insert(source, fragments);
    };
Пример #16
0
module.exports = function(ast) {
  var amdclean = this;
  var options = amdclean.options;
  var esprimaOptions = options.esprima || {};
  var escodegenOptions = options.escodegen || {};

  // Check if both the esprima and escodegen comment options are set to true
  if(esprimaOptions.comment === true && escodegenOptions.comment === true) {
    try {
      // Needed to keep source code comments when generating the code with escodegen
      ast = escodegen.attachComments(ast, ast.comments, ast.tokens);
    } catch(e) {}
  }

  return escodegen.generate(ast, escodegenOptions);
};
Пример #17
0
	return through.obj(function (file, enc, callback) {
		/*jshint validthis:true*/

		// Do nothing if no contents
		if (file.isNull()) {
			return callback(null, file);
		}

		if (file.isStream()) {
			return callback(new gutil.PluginError('gulp-wrap-js', 'Stream content is not supported'));
		}

		// check if file.contents is a `Buffer`
		if (file.isBuffer()) {
			try {
				var ast = esprima.parse(file.contents, {
					loc: true,
					source: file.relative,
					range: true,
					tokens: true,
					comment: true
				});
				escodegen.attachComments(ast, ast.comments, ast.tokens);
				ast.file = file;
				ast = tmpl(ast);
				var result = escodegen.generate(ast, {
					comment: true,
					format: format,
					sourceMap: true,
					sourceMapWithCode: true,
					file: file.relative
				});
			} catch(e) {
				// Relative to gulpfile.js filepath with forward slashes
				file = gutil.colors.magenta(path.relative('.', file.path).split(path.sep).join('/'));
				return callback(new gutil.PluginError('gulp-wrap-js', file + ' ' + e.message))
			}

			file.contents = new Buffer(result.code);
			if (file.sourceMap) {
				applySourceMap(file, JSON.parse(result.map.toString()));
			}
			return callback(null, file);
		}
	});
Пример #18
0
exports.parse = function (input, options) {
  pre:
    typeof input === 'string';
  main:
    options = options || {};
    options.comment = true;
    options.tokens = true;
    options.range = true;
    options.loc = true;

    var ast = esprima.parse(input, options);

    escodegen.attachComments(ast, ast.comments, ast.tokens);

    return ast;
  post:
    __result && typeof __result === 'object';
};
Пример #19
0
util.prettify = function(code, options) {
  try {
    if(code.indexOf('\n') < 0 && code.indexOf('//') === 0) {
      // Workaround for issue with one-line comments and escodegen.
      return code
    }
    var ast = esprima.parse(code, {
      tokens: true,
      attachComment: true,
      range: true
    })
    escodegen.attachComments(ast, ast.comments, ast.tokens)
    return escodegen.generate(ast, options)
  } catch(err) {
    tap.comment(code)
    tap.comment(err.stack)
    throw new Error('Unable to prettify code')
  }
}
Пример #20
0
  function testComments() {
	  var code = getFile();
	  var offset = 0;
	  var options = { comment: true, loc: true, range: true, tokens: true, raw: false};
	  var ast = esprima.parse(code, options);
	  ast = escodegen.attachComments(ast, ast.comments, ast.tokens);

	  var comments = ast.comments;
	  //console.log(JSON.stringify(comments));

	  var newCode = escodegen.generate(ast, {comment: true, format: { 
		  indent: { 
			  adjustMultilineComment: true 
		  } 
	  }  
	  });
	  console.log(newCode);
	  console.log(comments.length);
	  /*
	  for (var i = comments.length-1; i >= 0; i--) {
	  var comment = comments[i];
	  var str = comment.value;
	  var replace ="";
	  if (comment.type == 'Block')
	  //      replace = "\n/*"+ comment.value + "/\n";
  		else
	  replace = "\n//" + comment.value + "\n";
	  newCode = newCode.substring(0, comment.range[0]) +  replace +
	  newCode.substring(comment.range[0], newCode.length);

	  console.log(newCode.substring(0, comment.range[0]));
	  console.log(newCode.substring( comment.range[0], newCode.length));
	  console.log(newCode);
	  }
	  */

	  /*comments.forEach(function (comment) {
		  var str = comment.value;
		  newCode = newCode.substring(0, offset + comment.range[0]) + comment.value +
		  newCode.substring(offset + comment.range[1]+1, newCode.length);
		  });*/
  }
Пример #21
0
	return through.obj(function (file, enc, callback) {
		/*jshint validthis:true*/

		// Do nothing if no contents
		if (file.isNull()) {
			this.push(file);
			return callback();
		}

		if (file.isStream()) {
			this.emit('error', new gutil.PluginError('gulp-wrap-js', 'Stream content is not supported'));
			return callback();
		}

		// check if file.contents is a `Buffer`
		if (file.isBuffer()) {
			var ast = esprima.parse(file.contents, {
				loc: true,
				source: file.relative,
				range: true,
				tokens: true,
				comment: true
			});
			escodegen.attachComments(ast, ast.comments, ast.tokens);
			ast = tmpl(ast);
			var result = escodegen.generate(ast, {
				comment: true,
				format: format,
				sourceMap: true,
				sourceMapWithCode: true,
				file: file.relative
			});
			file.contents = new Buffer(result.code);
			if (file.sourceMap) {
				applySourceMap(file, JSON.parse(result.map.toString()));
			}
			this.push(file);
		}

		return callback();
	});
Пример #22
0
  o.run = function (code, filename) {
    var comments = [], tokens = [];
    var ast = acorn.parse(code, {
      ecmaVersion: 6,
      allowReturnOutsideFunction: true,
      ranges: true,
      // collect comments in Esprima's format 
      onComment: comments,
      // collect token ranges 
      onToken: tokens
    });

    // make sure we keep comments
    escodegen.attachComments(ast, comments, tokens);

    var globals = findGlobals(ast);
    for (var i = 0; i < globals.length; ++i) {
      if (globals[i].name === "window") {
        continue;
      }

      var nodes = globals[i].nodes;
      for (var j = 0; j < nodes.length; ++j) {
        var type = nodes[j].type;
        var name = nodes[j].name;
        nodes[j].type = "MemberExpression";
        nodes[j].property = {
          name: name,
          type: type
        };
        nodes[j].computed = false;
        nodes[j].object = {
          name: "window",
          type: "Identifier"
        };
      }
    }

    code = escodegen.generate(ast, { comment: true });
    new Function("window", code + "\n//# sourceURL=" + filename).bind(o)(o); // jshint ignore:line
  };
Пример #23
0
  instrumentSync (code, fileName) {

    const result = this._r =
      babelTransform(code, { ...this.babelOptions, filename: fileName });
    this._babelMap = new SourceMapConsumer(result.map);

    // PARSE
    let program = parse(result.code, {
      loc: true,
      range: true,
      tokens: this.opts.preserveComments,
      comment: true
    });

    if (this.opts.preserveComments) {
      program = escodegen
        .attachComments(program, program.comments, program.tokens);
    }

    return this.instrumentASTSync(program, fileName, code);
  }
Пример #24
0
function testString() {
      var code = getFile();
      var offset = 0;
      //var options = { comment: true, loc: true, range: true, tokens: true, raw: true, tolerant: true};
      var options = { comment: true, loc: true, range: true, tokens: true, tolerant: true};
      var ast = esprima.parse(code, options);
      ast = escodegen.attachComments(ast, ast.comments, ast.tokens);

      var comments = ast.comments;
      //console.log(JSON.stringify(comments));

      var newCode = escodegen.generate(ast, {comment: true, format: { 
            raw: false,
          indent: { 
              adjustMultilineComment: true 
          } 
      },
      parse: esprima.parse
      });
      console.log(newCode);
      console.log(comments.length);
  }
Пример #25
0
/**
 * 格式化JS代码
 * 
 * @param {string} sourceCode 要格式化的JS代码
 * 
 * @return {string} 格式化后的JS代码
 */
function beautifyJs(sourceCode) {
    var ast = require('esprima').parse(sourceCode, {
        range: true,
        comment: true,
        tokens: true
    });


    var escodegen = require('escodegen');
    escodegen.attachComments(ast, ast.comments, ast.tokens);

    return escodegen.generate(ast, {
        comment: true,
        format: {
            indent: {
                style: '    '
            },
            escapeless: true
        } 
    });

}
Пример #26
0
exports.refactorPromises = function refactorPromises(code, opts) {

    options = {
        check_only_error_first: opts.check_only_error_first || false,
        flatten_chains: opts.flatten_chains || false,
        func_name_suffix: opts.func_name_suffix || 'Promised'
    };

    // Parse
    var ast = esprima.parse(code, {
        loc: true,
        range: true,
        raw: true,
        tokens: true,
        comment: true
    });

    // Add comments to nodes.
    ast = escodegen.attachComments(ast, ast.comments, ast.tokens);


    estraverse.replace(ast, {
        leave: curry(callbackReplacer, hasNodeCallback, replaceNodeCallback)
    });
    estraverse.replace(ast, {
        enter: thenFlattener
    });

    // generate
    var generated = escodegen.generate(ast, {parse: esprima.parse, comment: true});
    template = 'function(err,data){\n\
                    if(err !== null)\n\
                        return reject(err);\n\
                    resolve(data);\n\
                }';
    return generated.replace(/g5k3d9/g, template);
};
Пример #27
0
 transform: (content, filename) => {
   if (filename.indexOf('node_modules') !== -1 || content.indexOf('power-assert') === -1) return content
   let ast
   const comments = []
   const tokens = []
   try {
     ast = acorn.parse(content, {
       ecmaVersion: 8,
       ranges: true,
       locations: true,
       sourceFile: true,
       onComment: comments,
       onToken: tokens
     })
   } catch (err) {
     // remove stack for simpler errors
     delete err.stack
     throw err
   }
   // attach comments using collected information
   escodegen.attachComments(ast, comments, tokens)
   // generate code
   return escodegen.generate(espower(ast))
 }
Пример #28
0
  fixMyJS.fix = function (code, config) {
    var shebang = SHEBANG.exec(code)
    var ast = esprima.parse(code.replace(SHEBANG, ''), ESPRIMA_OPTIONS)
    var astWithComments = escodegen.attachComments(
      ast, ast.comments, ast.tokens)
    var has = genHas(validateRules(config))
    var rules = getRules(has)
    var options = {
      format: {
        indent: {
          style: createIndent(has('indent', 2), has('indentpref', 'spaces')),
          base: 0
        },
        json: false,
        renumber: false,
        quotes: has('quotmark', 'single'),
        escapeless: false,
        parentheses: true,
        semicolons: !has('asi', false)
      },
      parse: null,
      comment: true
    }
    var modifiedTree = traverse(astWithComments, function (node, parent) {
      return fu.foldl(function (node, f) {
        return f.hasOwnProperty(node.type)
          ? f[node.type](node, parent)
          : node
      }, rules, node)
    })
    var generatedCode = escodegen.generate(modifiedTree, options)

    return shebang === null
      ? generatedCode
      : [shebang[0], generatedCode].join('\n')
  }
Пример #29
0
 this.parseJSSource = content => {
   let tree = esprima.parse(content, esprimaOptions);
   tree = escodegen.attachComments(tree, tree.comments, tree.tokens);
   return tree;
 };
Пример #30
0
function parse(code, options) {
    options = _.extend({},_options, options);
    options.type = options.type || utils.isValidModule(code);
    if(options.type == 1) {
        //commonJS风格,先转换成KISSY风格再进行下一步处理
        code = utils.substitute('KISSY.add(function(S, require, exports, module){{code}});',{code:code});
    }
    var ast = esprima.parse(code, defaultOptions.esprima),
        moduleInfo, variables = [];

    estraverse.replace(ast, {
        enter: function (node, parent) {
            //函数调用

            if(!moduleInfo && utils.isModuleAdd(node)) {
                moduleInfo = convertModuleDefine(node, options);
                moduleInfo.filename = options.filename;
                moduleInfo.options = options;
                return moduleInfo.node;
            }


            if (node.type == 'CallExpression' || node.type == 'NewExpression') {
                var callee = node.callee;

                if(callee.name == 'require') {
                    var args = node.arguments;
                    if(args.length == 1 && args[0].type == 'Literal') {
                        if(moduleInfo) {
                            if(parent.type == 'VariableDeclarator' && parent.id) {
                                if(parent.id.type == 'Identifier') {
                                    moduleInfo.dependencies.unshift(args[0].value);
                                    moduleInfo.params.unshift(parent.id.name);
                                    moduleInfo['requires'][args[0].value] = {
                                        name: parent.id.name,
                                        node: node
                                    }
                                }
                            }
                        }
                    }
                }

                if(!(callee && callee.object)) {
                    return node;
                }

                var object = callee.object;

                if(['Identifier','MemberExpression'].indexOf(object.type) == -1) {
                    return node;
                }

                if(utils.isKISSY(object.name||object.object.name)) {
                    return upgrade(node, moduleInfo, parent);
                }
            }else if(node.type == 'MemberExpression') {
                var object = node.object;

                if(object.type == 'MemberExpression' && utils.isKISSY(object.object.name)) {
                    //S.UA.ie
                    return upgrade(node, moduleInfo, parent);
                }else if(object.type =='Identifier' && utils.isKISSY(object.name)) {
                    //S.UA
                    return upgrade(node, moduleInfo, parent);
                }
            }

            return node;
        },
        leave: function (node, parent) {
            if (node.type == 'Identifier'){
                variables.push(node.name);
            }
        }
    });

    upgrade.fixEvent(ast, moduleInfo)
           .fixRequire(ast, moduleInfo)
           .fixExports(ast, moduleInfo)
           .clean(ast, moduleInfo);

    ast = escodegen.attachComments(ast, ast.comments, ast.tokens);

    if(options.commonJs) {
        if(!moduleInfo.factory.body.body) {
            ast.body = [moduleInfo.factory.body];
        }else {
            ast.body = moduleInfo.factory.body.body;
        }
    }
    var code = utils.decodeVariableName(utils.generateCode(ast), variables);

    return {
        code: code,
        deprecated_api: utils.unique(moduleInfo.deprecated_api),
        unknown_api: utils.unique(moduleInfo.unknown_api)
    }
}