Example #1
0
function replaceRequires(prefix, filePath, code) {
    var ast = recast.visit(recast.parse(code.toString()), {
        visitCallExpression: function(nodePath) {
            var expr = nodePath.node;
            this.traverse(nodePath);

            if (expr.callee.name != 'require' ||
                expr.arguments.length == 0) {
                return;
            }

            var modulePathArg = expr.arguments[0];
            if (modulePathArg.value.charAt(0) != '.') {
                return;
            }

            var quote = modulePathArg.raw.charAt(0);

            var modulePath = path.relative(prefix,
                                path.resolve(path.dirname(filePath),
                                    modulePathArg.value));
            var moduleName = genModuleName(modulePath);
            expr.arguments[0] = quote + './' + moduleName + quote;
        },
    });

    return recast.print(ast).code;
}
export default function getMemberExpressionValuePath(
  variableDefinition: NodePath,
  memberName: string
): ?NodePath {
  var localName = resolveName(variableDefinition);
  var program = getRoot(variableDefinition);

  if (!localName) {
    // likely an immediately exported and therefore nameless/anonymous node
    // passed in
    return;
  }

  var result;
  recast.visit(program, {
    visitAssignmentExpression(path) {
      var memberPath = path.get('left');
      if (!types.MemberExpression.check(memberPath.node)) {
        return this.traverse(path);
      }

      if (
        (!memberPath.node.computed || types.Literal.check(memberPath.node.property)) &&
        getNameOrValue(memberPath.get('property')) === memberName
      ) {
        result = path.get('right');
        return false;
      }

      this.traverse(memberPath);
    },
  });

  return result; // eslint-disable-line consistent-return
}
module.exports = function transform(source) {
  var ast = parseAst(source);
  var needs, emberImport;
  var uses = [];
  recast.visit(ast, {
    visitProperty: function(path) {
      if(isNeedsDeclaration(path)) {
        needs = path;
        return false;
      }
      this.traverse(path);
    },
    visitLiteral: function(path) {
      if (isNeedsUsage(path)) {
        uses.push(path);
      }
      this.traverse(path);
    },
    visitImportDeclaration: function(path) {
      if (isImportFor('ember', path.node)) {
        emberImport = path;
      }
      this.traverse(path);
    },
  });

  transformNeeds(ast, needs, uses, emberImport);
  return recast.print(ast, { tabWidth: 2, quote: 'single' }).code;
};
Example #4
0
YuiModule.prototype.visit = function (tree) {
    var instanceNodes = this.nodes;

    return recast.visit(tree, {
        visitCallExpression: function (currentPath) {
            var node = currentPath.node;
            if (node.callee &&
                node.callee.object &&
                node.callee.object.name === 'YUI' &&
                node.callee.property.name === 'add') {
                // [name, fn, version, cfg]
                var args = node.arguments;

                instanceNodes.add  = node;          // CallExpression
                instanceNodes.name = args[0];       // Literal
                instanceNodes.body = args[1].body;  // BlockStatement
                instanceNodes.meta = args[3];       // ObjectExpression

                return false; // don't visit deeper
            }

            this.traverse(currentPath);
        }
    });
};
export default function importsHandler(
  documentation: Documentation,
  path: NodePath
): void {
  const imports: string[] = [];
  const root = path.scope.getGlobalScope().node;

  recast.visit(root, {
    visitImportDeclaration({ node }: NodePath) {
      if (imports.indexOf(node.source.value) === -1) {
        imports.push(node.source.value);
      }
      return false;
    },
    visitCallExpression({ node }: NodePath) {
      if (
        isRequire(node) &&
        hasStaticArgument(node) &&
        imports.indexOf(node.arguments[0].value) === -1
      ) {
        imports.push(node.arguments[0].value);
      }
      return false;
    },
  });

  documentation.set('imports', imports);
}
module.exports = function transform(source) {
  var ast = recast.parse(source);
  var assert = 'assert';

  recast.visit(ast, {
    visitCallExpression: function(path){
      var node = path.node;

      if (isTestCall(node)) {
        assert = assertName(node);
      } else if (isAssertion(node, assert, 'ok')) {
        transformUnaryAssertion(node, 'ok: ');
      } else if (isAssertion(node, assert, 'notOk')) {
        transformUnaryAssertion(node, 'not ok: ');
      } else if (isAssertion(node, assert, 'equal')) {
        transformBinaryAssertion(node, 'equal: ', '==');
      } else if (isAssertion(node, assert, 'notEqual')) {
        transformBinaryAssertion(node, 'not equal: ', '!=');
      }

      this.traverse(path);
    }
  });

  return recast.print(ast, {quote: 'single'}).code;
};
module.exports = function transform(source) {
  var sections = {
    computedProperties: [],
    observers: []
  };

  var ast = recast.parse(source);

  recast.visit(ast, {
    visitCallExpression: function(path) {
      var node = path.node;

      if (isComputedProperty(node)) {
        sections.computedProperties.push(path);
      }

      if (isObserver(node)) {
        sections.observers.push(path);
      }

      this.traverse(path);
    }
  });

  sections.computedProperties.forEach(function(cp) {
    transformComputedProperty(cp);
  });

  sections.observers.forEach(function(observer) {
    transformObserver(observer);
  });

  return recast.print(ast, { tabWidth: 2, quote: 'single' }).code;
};
Example #8
0
var transform = function transform(file, encoding, options) {
    var inputMap =file.sourceMap;
    var inputSource = file.contents.toString(encoding);
    var ast = recast.parse(inputSource, {
        sourceFileName : file.relative
    });

    recast.visit(ast, options);

    var output = recast.print(ast, {sourceMapName : file.relative + '.map'});

    file.contents = new Buffer(output.code);
    if( inputMap ) {
        var outputMap = convert.fromJSON(JSON.stringify(output.map));
        outputMap.setProperty('sources', inputMap.sources);
        outputMap.setProperty('sourcesContent', inputMap.sourcesContent);
        var mergedSourceMap;
        if(inputMap.mappings === '') {
            applySourceMap(file, outputMap.toJSON());
            mergedSourceMap = convert.fromObject(file.sourceMap);
        } else {
            mergedSourceMap = convert.fromJSON( transfer({
                fromSourceMap : JSON.parse(outputMap.toJSON()),
                toSourceMap : inputMap
            }) );
        }
        mergedSourceMap.setProperty('sources', inputMap.sources);
        mergedSourceMap.setProperty('sourcesContent', inputMap.sourcesContent);
	mergedSourceMap.setProperty('file', inputMap.file);
        file.sourceMap = mergedSourceMap.toObject();
    }
};
Example #9
0
function renameClass(renames, src) {
  var ast = recast.parse(src);

  recast.visit(ast, {
    visitJSXOpeningElement: function(path) {
      if (path.node.name.name[0] === path.node.name.name[0].toLowerCase()) {
        path.node.attributes.forEach(function(attribute) {
          var name = attribute.name.name;
          if (
            name === 'className' &&
              n.Literal.check(attribute.value) &&
              typeof attribute.value.value === 'string'
          ) {
            attribute.value.value = attribute.value.value.split(' ').map(function(className) {
              return renames[className] || className;
            }).join(' ');
          }
        });
      }
      this.traverse(path);
    }
  });

  return recast.print(ast).code;
}
Example #10
0
function annotateStyleName(tree, prefix, query) {

  return recast.visit(tree, {
    visitCallExpression: function(path) {
      var node = path.value;
      if (this.isStyleDeclaration(path)) {
        if (node.arguments.length === 1) {
          var styleName = this.getStyleClassName(path);
          var replacement = this.buildStyleClassDeclaration(
            node.callee, node.arguments[0], styleName);
          path.replace(replacement);
        }
        else if (node.arguments.length === 2) {
          var replacement = this.buildStyleClassDeclaration(
            node.callee, node.arguments[0], this.getStyleName(prefix, node.arguments[1].value));
          path.replace(replacement);
        }
        return false;
      }
      this.traverse(path);
    },

    isStyleDeclaration: function(path) {
      var node = path.value;
      return (
        n.MemberExpression.check(node.callee) &&
        n.Identifier.check(node.callee.object) &&
        node.callee.object.name === 'StyleSheet' &&
        n.Identifier.check(node.callee.property) &&
        node.callee.property.name === 'create'
        );
    },

    buildStyleClassDeclaration: function(callee, style, styleName) {
      return b.callExpression(callee, [style, b.literal(styleName), b.literal(true)]);
    },

    getStyleClassName: function(path) {
      var styleClassName = '';

      // development time className
      if (path.parent.value.key && path.parent.value.key.name) {
        styleClassName = path.parent.value.key.name;
      }

      // user defined className
      if (n.VariableDeclarator.check(path.parentPath.value)) {
        styleClassName = path.parentPath.value.id.name;
      }

      if (prefix) {
        styleClassName = prefix + '_' + styleClassName;
      }

      return styleClassName;
    }

  });
}
Example #11
0
  return through2.obj(function (file, enc, next) {
    if (logAmount && logAmount > 2) {
      gutil.log(`>>> flattener starting file '${gutil.colors.cyan(path.dirname(file.relative) + path.sep + path.basename(file.path))}'`);
    }

    if (!file.isDirectory() && !file.isNull() && !file.isStream()) {
      try {
        file.contents = new Buffer(recast.print(recast.visit(recast.parse(file.contents.toString()), {
          visitCallExpression: function (filePath) {
            var expr = filePath.node;

            if (expr.callee.name != 'require') {
              this.traverse(filePath);
            } else if (expr.callee.name == 'require') {
              this.traverse(filePath);
              if (expr.arguments.length && expr.arguments[0].value && expr.arguments[0].value[0] == '.') {
                let arg = expr.arguments[0];
                let value = path.posix.normalize(path.dirname(file.relative).split(path.sep).join(path.posix.sep) + '/./' + arg.value);
                let result = './' + value.split('/').join('.');

                if (stringFilter) result = stringFilter(result);

                if (logAmount && logAmount > 1) {
                  gutil.log(`> in file '${gutil.colors.cyan(path.dirname(file.relative) + path.sep + path.basename(file.path))}', flattened path '${gutil.colors.cyan(expr.arguments[0].value)}' into '${gutil.colors.cyan(result)}'`);
                }

                expr.arguments[0] = arg.raw.charAt(0) + result + arg.raw.charAt(0);
              } else {
                if (logAmount && logAmount > 2) {
                  gutil.log('> failed test: expr.arguments.length && expr.arguments[0].value[0] == \'.\' : ' + expr.arguments[0].value);
                }
              }
            } else {
              return false;
            }
          },
        })).code);

        let relPath = path.dirname(file.relative).split(path.sep);
        relPath.push(path.basename(file.path));

        let newName = relPath.join('.');

        while (newName[0] == '.') newName = newName.slice(1);
        if (stringFilter) newName = stringFilter(result);

        if (logAmount && logAmount > 0) {
          gutil.log(`>> flattened file '${gutil.colors.cyan(path.dirname(file.relative) + path.sep + path.basename(file.path))}' into '${gutil.colors.cyan(newName)}'`);
        }

        file.path = path.join(file.base, '', newName);
        this.push(file);
      } catch (e) {
        this.emit('error', new PluginError('flatten', e));
      }
    }

    next();
  });
Example #12
0
	it('should require fixtures', () => {
		// Given.
		const givenAST = getAST('require-fixtures', 'given');

		// When.
		visit(givenAST, requireFixturesVisitor);

		// Then.
		verifyASTIsAsExpected('require-fixtures', 'expected', givenAST);
	});
function hasThisExpression(ast) {
  var isDynamic = false;
  recast.visit(ast, {
    visitThisExpression: function(node) {
      isDynamic = true;
      this.traverse(node);
    }
  });
  return isDynamic;
}
	it('should flatten a program IIFE.', function() {
		// Given.
		const givenAST = getAST('flatten-program-iife', 'given');

		// When.
		visit(givenAST, flattenProgramIIFEVisitor);

		// Then.
		verifyASTIsAsExpected('flatten-program-iife', 'expected', givenAST);
	});
	it('should expand var namespace aliases to namespaces.', () => {
		//Given.
		varNamespaceAliasExpanderVisitor.initialize(['my']);

		//When.
		visit(givenAST, varNamespaceAliasExpanderVisitor);

		//Then.
		assert.equal(print(givenAST).code, expectedCode);
	});
Example #16
0
	it('should only wrap a module if it has contents.', () => {
		// Given.
		const givenAST = getAST('wrap-module-in-iife', 'given-comment');

		// When.
		visit(givenAST, wrapModuleInIIFEVisitor);

		// Then.
		verifyASTIsAsExpected('wrap-module-in-iife', 'expected-comment', givenAST);
	});
Example #17
0
	it('should wrap module contents in an IIFE.', () => {
		// Given.
		const givenAST = getAST('wrap-module-in-iife', 'given');

		// When.
		visit(givenAST, wrapModuleInIIFEVisitor);

		// Then.
		verifyASTIsAsExpected('wrap-module-in-iife', 'expected', givenAST);
	});
	it('should flatten all occurences of a member expression.', function() {
		//Given.
		flattenMemberExpression.initialize(['some', 'call'], 'newcall');

		//When.
		visit(givenAST, flattenMemberExpression);

		//Then.
		assert.equal(print(givenAST).code, expectedCode);
	});
function checkIfVarIsAvailable(varNameToCheck, freeVariableName) {
	// Given.
	verifyVarIsAvailableVisitor.initialize();

	// When.
	visit(givenAST, verifyVarIsAvailableVisitor);

	// Then.
	assert.equal(verifyVarIsAvailableVisitor.getFreeVariation(varNameToCheck), freeVariableName);
}
	it('should add interface as last argument.', () => {
		// Given.
		const givenAST = getAST('add-interface-argument-to-eventhub', 'given');

		// When.
		visit(givenAST, addInterfaceArgumentToEventHubVisitor);

		// Then.
		verifyASTIsAsExpected('add-interface-argument-to-eventhub', 'expected', givenAST);
	});
Example #21
0
 this.__paths.forEach(function(p, i) {
   const self = this;
   visitor[visitorMethodName] = function(path) {
     if (self.__paths[i] === path) {
       this.traverse(path);
     } else {
       return visit.call(this, path);
     }
   };
   recast.visit(p, visitor);
 }, this);
	it('should remove globalizeSourceModules call.', function() {
		// Given.
		const givenAST = getAST('remove-globalize-source-modules-call', 'given');
		const removeGlobalizeSourceModulesCallVisitor = createRemoveGlobalizeSourceModulesCallVisitor();

		// When.
		visit(givenAST, removeGlobalizeSourceModulesCallVisitor);

		// Then.
		verifyASTIsAsExpected('remove-globalize-source-modules-call', 'expected', givenAST);
	});
	it('should remove, 4 part, class name class exports.', function() {
		// Given.
		const givenAST = getAST('remove-class-name-class-export', 'given-4part');
		const removeNamespaceExportVisitor = createRemoveClassNameClassExportVisitor('caplin.chart.my.TestStudy');

		// When.
		visit(givenAST, removeNamespaceExportVisitor);

		// Then.
		verifyASTIsAsExpected('remove-class-name-class-export', 'expected', givenAST);
	});
	it('should extract class from IIFE.', () => {
		// Given.
		const givenAST = getAST('iife-class-flattener', 'given');
		iifeClassFlattenerVisitor.initialize('my.long.name.space.SimpleClass');

		// When.
		visit(givenAST, iifeClassFlattenerVisitor);

		// Then.
		verifyASTIsAsExpected('iife-class-flattener', 'expected', givenAST);
	});
	it('should extract class from IIFE with only two levels.', () => {
		// Given.
		const givenTwoLevelAST = getAST('iife-class-flattener', 'given-twolevel');
		iifeClassFlattenerVisitor.initialize('my.Class');

		// When.
		visit(givenTwoLevelAST, iifeClassFlattenerVisitor);

		// Then.
		verifyASTIsAsExpected('iife-class-flattener', 'expected-twolevel', givenTwoLevelAST);
	});
	it('should remove redundant require call.', function() {
		// Given.
		const givenAST = getAST('remove-redundant-requires', 'given');
		removeRedundantRequiresVisitor.initialize();

		// When.
		visit(givenAST, removeRedundantRequiresVisitor);

		// Then.
		verifyASTIsAsExpected('remove-redundant-requires', 'expected', givenAST);
	});
Example #27
0
	return through2.obj((fileMetadata, encoding, callback) => {
		// Verify that the streamlink variable is free to use in this module, if not generate a variation on it that is.
		verifyVarIsAvailableVisitor.initialize();
		visit(fileMetadata.ast, verifyVarIsAvailableVisitor);
		const freeSLJSVariation = verifyVarIsAvailableVisitor.getFreeVariation('sljs');

		// Replace all calls to a certain namespace with calls to the new SLJS identifier.
		flattenMemberExpression.initialize(['caplin', 'streamlink'], freeSLJSVariation);
		visit(fileMetadata.ast, flattenMemberExpression);

		// Add a require that requires SLJS into the module.
		const libraryIdentifiersToRequire = new Map([
			[List.of(freeSLJSVariation), 'sljs']
		]);

		addRequireForGlobalIdentifierVisitor.initialize(libraryIdentifiersToRequire, fileMetadata.ast.program.body);
		visit(fileMetadata.ast, addRequireForGlobalIdentifierVisitor);

		callback(null, fileMetadata);
	});
	it('should remove specified module ids.', function() {
		//Given.
		var requiresToRemove = new Set(['my']);
		cjsRequireRemoverVisitor.initialize(requiresToRemove);

		//When.
		visit(givenAST, cjsRequireRemoverVisitor);

		//Then.
		assert.equal(print(givenAST).code, expectedCode);
	});
	it('should expand var namespace aliases to namespaces.', () => {
		// Given.
		const givenAST = getAST('var-namespace-alias-expander', 'given');

		varNamespaceAliasExpanderVisitor.initialize(['my']);

		// When.
		visit(givenAST, varNamespaceAliasExpanderVisitor);

		// Then.
		verifyASTIsAsExpected('var-namespace-alias-expander', 'expected', givenAST);
	});
	it('should transform specified module IDs.', function() {
		//Given.
		const moduleIDsToConvert = new Map([['my', ['some/Core', 'newVarName']]]);

		moduleIdVisitor.initialize(moduleIDsToConvert);

		//When.
		visit(givenAST, moduleIdVisitor);

		//Then.
		assert.equal(print(givenAST).code, expectedCode);
	});