Rewrites top level var names from
"var foo; console.log(foo);" to
"var module$contents$Foo_foo; console.log(module$contents$Foo_foo);"
556669
private void maybeUpdateTopLevelName(NodeTraversal t, Node nameNode) {
    String name = nameNode.getString();
    if (!currentScript.isModule || !currentScript.topLevelNames.contains(name)) {
      return;
    }
    Var var = t.getScope().getVar(name);
    // If the name refers to a var that is not from the top level scope.
    if (var == null || var.getScope().getRootNode() != currentScript.rootNode) {
      // Then it shouldn't be renamed.
      return;
    }

    // If the name is part of a destructuring import, the import rewriting will take care of it
    if (var.getNameNode() == nameNode
        && nameNode.getParent().isStringKey()
        && nameNode.getGrandparent().isObjectPattern()) {
      Node destructuringLhsNode = nameNode.getGrandparent().getParent();
      if (isCallTo(destructuringLhsNode.getLastChild(), GOOG_REQUIRE)
          || isCallTo(destructuringLhsNode.getLastChild(), GOOG_REQUIRETYPE)) {
        return;
      }
    }

    // If the name is an alias for an imported namespace rewrite from
    // "new Foo;" to "new module$exports$Foo;"
    boolean nameIsAnAlias = currentScript.namesToInlineByAlias.containsKey(name);
    if (nameIsAnAlias && var.getNode() != nameNode) {
      maybeAddAliasToSymbolTable(nameNode, currentScript.legacyNamespace);

      String namespaceToInline = currentScript.namesToInlineByAlias.get(name);
      if (namespaceToInline.equals(currentScript.getBinaryNamespace())) {
        currentScript.hasCreatedExportObject = true;
      }
      safeSetMaybeQualifiedString(nameNode, namespaceToInline);

      // Make sure this action won't shadow a local variable.
      if (namespaceToInline.indexOf('.') != -1) {
        String firstQualifiedName = namespaceToInline.substring(0, namespaceToInline.indexOf('.'));
        Var shadowedVar = t.getScope().getVar(firstQualifiedName);
        if (shadowedVar == null
            || shadowedVar.isGlobal()
            || shadowedVar.getScope().isModuleScope()) {
          return;
        }
        t.report(
            shadowedVar.getNode(),
            IMPORT_INLINING_SHADOWS_VAR,
            shadowedVar.getName(),
            namespaceToInline);
      }
      return;
    }

    // For non-import alias names rewrite from
    // "var foo; console.log(foo);" to
    // "var module$contents$Foo_foo; console.log(module$contents$Foo_foo);"
    safeSetString(nameNode, currentScript.contentsPrefix + name);
  }
667833
function rewrite(args) {
    // check if splicable is already in the body text
    const re = new RegExp(args.splicable.map(line => `\\s*${escapeRegExp(line)}`).join('\n'));

    if (re.test(args.haystack)) {
        return args.haystack;
    }

    const lines = args.haystack.split('\n');

    let otherwiseLineIndex = -1;
    lines.forEach((line, i) => {
        if (line.includes(args.needle)) {
            otherwiseLineIndex = i;
        }
    });

    let spaces = 0;
    while (lines[otherwiseLineIndex].charAt(spaces) === ' ') {
        spaces += 1;
    }

    let spaceStr = '';

    // eslint-disable-next-line no-cond-assign
    while ((spaces -= 1) >= 0) {
        spaceStr += ' ';
    }

    lines.splice(otherwiseLineIndex, 0, args.splicable.map(line => spaceStr + line).join('\n'));

    return lines.join('\n');
}
478085
def convertVariable(self, key, varName, varValue):
        """"""
        if isinstance(varValue, encapsulation.FunctionEncapsulation):
            result = varValue.getFunction()

            # Update the global scope of the function to match the current module
            mainModule = sys.modules["__main__"]
            result.__name__ = varName
            result.__globals__.update(mainModule.__dict__)
            setattr(mainModule, varName, result)
            shared.elements[key].update({
                varName: result,
            })
1040328
function substituteVars(rawText, vars)
{
    if (!vars)
    {
        return rawText;
    }
    //after loading contents, perform variable substitution
    Object.keys(vars).forEach(function (varName)
    {
        if (vars.hasOwnProperty(varName))
        {
            var varValue = vars[varName];
            rawText = replaceAll(rawText, varName, varValue);
        }
    });
    return rawText;
}
339098
function encodeBlocks($, prefix, blockType, args, block) {
      if (!prefix) prefix = "";
      if (blockType == "function") {
        // decode the function block (THIS IS THE IMPORTANT BIT)
        // We are retrieving all sub-blocks and will re-parse them in light
        // of newly shrunk variables
        block = args + decodeBlocks(block, SCOPED);
        prefix = prefix.replace(BRACKETS, "");
        
        // create the list of variable and argument names
        args = args.slice(1, -1);
        
        if (args != "_no_shrink_") {
          var vars = match(block, VARS).join(";").replace(VAR_g, ";var");
          while (BRACKETS.test(vars)) {
            vars = vars.replace(BRACKETS_g, "");
          }
          vars = vars.replace(VAR_TIDY, "").replace(VAR_EQUAL, "");
        }
        block = decodeBlocks(block, ENCODED_BLOCK);
        
        // process each identifier
        if (args != "_no_shrink_") {
          var count = 0, shortId;
          var ids = match([args, vars], IDENTIFIER);
          var processed = {};
          for (var i = 0; i < ids.length; i++) {
            id = ids[i];
            if (!processed["#" + id]) {
              processed["#" + id] = true;
              id = rescape(id);
              // encode variable names
              while (new RegExp(Shrinker.PREFIX + count + "\\b").test(block)) count++;
              var reg = new RegExp("([^\\w$.])" + id + "([^\\w$:])");
              while (reg.test(block)) {
                block = block.replace(global(reg), "$1" + Shrinker.PREFIX + count + "$2");
              }
              var reg = new RegExp("([^{,\\w$.])" + id + ":", "g");
              block = block.replace(reg, "$1" + Shrinker.PREFIX + count + ":");
              count++;
            }
          }
          total = Math.max(total, count);
        }
        var replacement = prefix + "~" + blocks.length + "~";
        blocks.push(block);
      } else {
        var replacement = "~#" + blocks.length + "~";
        blocks.push(prefix + block);
      }
      return replacement;
    }
997881
function transform(str) {
  str = str.split(/^lazy\(/gm).join('require(');
  var lines = str.split(/\r\n|\n/);
  var len = lines.length;
  var re = regex();
  var idx = 0;

  var start = false;
  var isExported = false;
  var namespace;
  var res = '';

  while (idx < len) {
    var line = lines[idx++];
    res += '\n';

    if (/(?:var fn = require|require = utils)/.test(line)) {
      continue;
    }
    if (/^require = fn/.test(line)) {
      continue;
    }
    // adding this line to catch other variable names than the more specific cases above
    if (/^require = (?:.*)/.test(line)) {
      continue;
    }

    var match = re.exec(line);
    if (!match) {
      res += line;
      continue;
    }

    if (match && (match[2] === 'lazy-cache' || match[3] === 'lazy-cache')) {
      namespace = toNamespace(match[1]);
      if (/module\.exports/.test(match[1])) {
        isExported = true;
      }
      line = 'var ' + namespace + ' = {};';
      start = true;
      res += line;
      continue;
    }

    if (!start) {
      res += line;
      continue;
    }

    var variable = toVariable(match);
    var prefix = toProperty(namespace, variable, match[2]);
    line = line.split(match[0]).join(prefix);
    res += line;
  }

  if (isExported) {
    res += '\nmodule.exports = ' + namespace + ';';
  }
  return res.replace(/^\s+/, '');
}
83029
function (module) {
        "use strict";
    
        var getResource = function (hostType, resource) {
    
            var host;
            var modulePath, filePath;
    
            if (resource.substr(0, 1) === '/') {
                resource = resource.substr(1);
            }
    
            if (hostType === 'module') {
    
                if (module.library) {
                    host = beyond.hosts.libraries[module.library.name].js;
                    library = module.library.name;
                }
                else {
                    host = beyond.hosts.application.js;
                    library = undefined;
                }
    
                modulePath = module.path;
                filePath = resource;
    
            }
            else if (hostType === 'application') {
    
                host = beyond.hosts.application.js;
                return host + resource;
    
            }
            else {
    
                var library = hostType;
                host = beyond.hosts.libraries[library];
    
                if (!host) {
                    console.warn('invalid css host on module "' + module.ID + '", resource "' + resource + '"' +
                        ', library "' + library + '" is not defined');
                    return;
                }
    
                if (resource.substr(0, 7) === 'static/') {
                    modulePath = 'main';
                    filePath = resource.substr(7);
                }
                else {
                    var overwrite = resource.split('/static/');
                    modulePath = overwrite[0];
                    filePath = overwrite[1];
                }
    
            }
    
            var overwrites = beyond.overwrites;
            var overwrited;
            if (library) {
                overwrited = overwrites[library];
            }
    
            if (!overwrited || !overwrited[modulePath] ||
                overwrited[modulePath].indexOf(filePath) === -1) {
    
                return host + modulePath + '/static/' + filePath;
            }
    
            return beyond.hosts.application.js +
                'custom/' + library + '/' +
                modulePath + '/static/' + filePath;
    
        };
    
        var setHosts = function (styles) {
    
            // find variables
            var variable;
    
            var replace = {};
    
            var regexp = /#host\.(.*?)#(.*?)[\)\s]/g;
            variable = regexp.exec(styles);
    
            var resource;
            while (variable) {
    
                // hostType can be 'application', 'module', libraryName
                var hostType = variable[1];
                resource = variable[2];
                resource = getResource(hostType, resource);
    
                var original = variable[0];
                if (original.substr(original.length - 1) === ')')
                    original = original.substr(0, original.length - 1);
    
                replace[original] = resource;
                variable = regexp.exec(styles);
    
            }
    
            // replace #host.* variables with their values
            for (var original in replace) {
    
                resource = replace[original];
    
                while (styles.indexOf(original) !== -1)
                    styles = styles.replace(original, resource);
    
            }
    
            return styles;
    
        };
    
        this.process = function (styles) {
    
            // find and replace #host...
            styles = setHosts(styles);
            return styles;
    
        };
    
    }
76967
function block () {
    var code = []
    function push () {
      code.push.apply(code, slice(arguments))
    }

    var vars = []
    function def () {
      var name = 'v' + (varCounter++)
      vars.push(name)

      if (arguments.length > 0) {
        code.push(name, '=')
        code.push.apply(code, slice(arguments))
        code.push(';')
      }

      return name
    }

    return extend(push, {
      def: def,
      toString: function () {
        return join([
          (vars.length > 0 ? 'var ' + vars + ';' : ''),
          join(code)
        ])
      }
    })
  }
1329294
function getModuleName(module) {
    var script = module.replace(/[^a-zA-Z0-9]/g, '.'),
        parts = script.split('.'),
        name = parts.shift();

    if (parts.length) {
      for (var p in parts) {
        name += parts[p].charAt(0).toUpperCase() + parts[p].substr(1, parts[p].length);
      }
    }
    return name;
  }
1265221
function renderTmpl (path, vars, callback) {
    fs.readFile(path, 'utf8', function (err, file) {
        if (err) {
            return callback(err);
        }
        var out = file.replace(/\{\{([a-z]+)\}\}/ig, function (all, name) {
            return vars[name];
        });
        callback(null, out);
    });
}
145900
private void copyTagToPageScope(int scope) {
	Iterator iter = null;

	switch (scope) {
	case VariableInfo.NESTED:
	    if (nestedVars != null) {
		iter = nestedVars.iterator();
	    }
	    break;
	case VariableInfo.AT_BEGIN:
	    if (atBeginVars != null) {
		iter = atBeginVars.iterator();
	    }
	    break;
	case VariableInfo.AT_END:
	    if (atEndVars != null) {
		iter = atEndVars.iterator();
	    }
	    break;
	}

	while ((iter != null) && iter.hasNext()) {
	    String varName = (String) iter.next();
	    Object obj = getAttribute(varName);
	    varName = findAlias(varName);
	    if (obj != null) {
		invokingJspCtxt.setAttribute(varName, obj);
	    } else {
		invokingJspCtxt.removeAttribute(varName, PAGE_SCOPE);
	    }
	}
    }
240358
function(_part){
        if (!_part||!_part.length) return;
        _part.shift(); // remove macro key word
        var _name = _part[0].split('(')[0];
        return 'var '+_name+' = function'+_part.join('').replace(_name,'')+'{var __OUT=[];';
    }
71333
function variableEndPos( $tpl, $relatedTemplateName, &$text, $startPosition, $textLength,
                             &$namespace, &$name, &$scope )
    {
        $currentPosition = $startPosition;
        $namespaces = array();
        $variableName = false;
        $lastPosition = false;
        $scopeType = eZTemplate::NAMESPACE_SCOPE_LOCAL;
        $scopeRead = false;
        while ( $currentPosition < $textLength )
        {
            if ( $lastPosition !== false and
                 $lastPosition == $currentPosition )
            {
                $tpl->error( "ElementParser::variableEndPos", "parser error @ $relatedTemplateName\[" . $currentPosition . "]\n" .
                             "Parser position did not move, this is most likely a bug in the template parser." );
                break;
            }
            $lastPosition = $currentPosition;
            if ( $text[$currentPosition] == '#' )
            {
                if ( $scopeRead )
                {
                    $tpl->error( "ElementParser::variableEndPos", "parser error @ $relatedTemplateName\[" . $currentPosition . "]\n" .
                                 "Namespace scope already declared, cannot set to global." );
                }
                else
                {
                    $scopeType = eZTemplate::NAMESPACE_SCOPE_GLOBAL;
                }
                $scopeRead = true;
                ++$currentPosition;
            }
            else if ( $text[$currentPosition] == ':' )
            {
                if ( $scopeRead )
                {
                    $tpl->error( "ElementParser::variableEndPos", "parser error @ $relatedTemplateName\[" . $currentPosition . "]\n" .
                                 "Namespace scope already declared, cannot set to relative." );
                }
                else
                {
                    $scopeType = eZTemplate::NAMESPACE_SCOPE_RELATIVE;
                }
                $scopeRead = true;
                ++$currentPosition;
            }
            else
            {
                $identifierEndPosition = $this->identifierEndPosition( $tpl, $text, $currentPosition, $textLength );
                if ( $identifierEndPosition > $currentPosition )
                {
                    $identifier = substr( $text, $currentPosition, $identifierEndPosition - $currentPosition );
                    $currentPosition = $identifierEndPosition;
                    if ( $identifierEndPosition < $textLength and
                         $text[$identifierEndPosition] == ':' )
                    {
                        $namespaces[] = $identifier;
                        ++$currentPosition;
                    }
                    else
                        $variableName = $identifier;
                }
                else if ( $identifierEndPosition < $textLength and
                          ( $text[$identifierEndPosition] != ":" and
                            $text[$identifierEndPosition] != "#" ) )
                {
                    if ( $variableName === false )
                    {
                        $tpl->error( "ElementParser::variableEndPos", "parser error @ $relatedTemplateName\[" . $currentPosition . "]\n" .
                                     "No variable name found, this is most likely a bug in the template parser." );
                        return $startPosition;
                    }
                    break;
                }
                else
                {
                    $tpl->error( "ElementParser::variableEndPos", "parser error @ $relatedTemplateName\[" . $currentPosition . "]\n" .
                                 "Missing identifier for variable name or namespace, this is most likely a bug in the template parser." );
                    return $startPosition;
                }
            }
        }
        $scope = $scopeType;
        $namespace = implode( ':', $namespaces );
        $name = $variableName;
        return $currentPosition;
    }
1234214
function stringDotToObj(result, name, value) {
        var parts = name.split('.'),
            prop = parts[0];

        parts.forEach(function (prop, i) {
            if (i === parts.length - 1) {
                result[prop] = value;
            } else {
                if (!result[prop]) {
                    result[prop] = {};
                }
                result = result[prop];
            }

        });
    }
755614
private void saveNestedVariables() {
	if (nestedVars != null) {
	    Iterator iter = nestedVars.iterator();
	    while (iter.hasNext()) {
		String varName = (String) iter.next();
		varName = findAlias(varName);
		Object obj = invokingJspCtxt.getAttribute(varName);
		if (obj != null) {
		    originalNestedVars.put(varName, obj);
		}
	    }
	}
    }
964226
function(pluginName, moduleName, write){
            if(moduleName in buildMap){
                var content = buildMap[moduleName];
                write('define("'+ pluginName +'!'+ moduleName +'", function(){ return '+ content +';});\n');
            }
        }
1225978
function(varName, source) {

    var body = source.substring(source.indexOf('\n') + 1),
      result;

    // Do not parse every variable
    if (ComplexParams.indexOf(varName) === -1) {
      result = body;
    } else {

      result = {};

      body.split('\n').forEach(function(line) {

        var keyVal = line.split(':').map(function(str) {
          str = str.trim();
          if (str.indexOf(',') !== -1) {
            str = str.split(',').map(function(s) {
              return s.trim();
            });
          }
          return str;
        });

        if (!result[keyVal[0]]) {
          // Define new value
          result[keyVal[0]] = keyVal[1];
        } else {
          // Add another value
          if (!(result[keyVal[0]] instanceof Array)) {
            result[keyVal[0]] = [
              result[keyVal[0]]
            ];
          }
          result[keyVal[0]].push(keyVal[1]);
        }

      });
    }

    return result;
  }