For browser field entries in package.json files that are used in an advanced manner
(https://github.com/defunctzombie/package-browser-field-spec/#replace-specific-files---advanced),
track the entries in that object literal as module file replacements.
771369
private void processBrowserFieldAdvancedUsage(String dirName, Node entry) {
    for (Node child : entry.children()) {
      Node value = child.getFirstChild();

      checkState(child.isStringKey() && (value.isString() || value.isFalse()));

      String path = child.getString();

      if (path.startsWith(ModuleLoader.DEFAULT_FILENAME_PREFIX)) {
        path = path.substring(ModuleLoader.DEFAULT_FILENAME_PREFIX.length());
      }

      String replacement =
          value.isString()
              ? dirName + value.getString()
              : ModuleLoader.JSC_BROWSER_BLACKLISTED_MARKER;

      packageJsonMainEntries.put(dirName + path, replacement);
    }
  }
194764
function AnalyzeSourceCodeMiddleware (context)
{
  var grunt = context.grunt;

  //--------------------------------------------------------------------------------------------------------------------
  // PUBLIC API
  //--------------------------------------------------------------------------------------------------------------------

  this.analyze = function (filesArray)
  {
    var src = util.sortFilesBeforeSubfolders (filesArray.src);

    // Load the script files and scan them for module definitions.
    src.forEach (function (path)
    {

      if (!grunt.file.exists (path)) {
        warn ('Source file "' + path + '" not found.');
        return;
      }
      // Read the script and scan it for module declarations.
      var script = grunt.file.read (path);
      /** @type {ModuleHeaderInfo[]} */
      var moduleHeaders;
      try {
        moduleHeaders = sourceExtract.extractModuleHeaders (script);
      }
      catch (e) {
        if (typeof e === 'string')
          return warn (e + NL + reportErrorLocation (path));
        throw e;
      }

      // Ignore irrelevant files.
      if (!moduleHeaders.length) {
        if (!filesArray.forceInclude || !grunt.file.isMatch ({matchBase: true}, filesArray.forceInclude, path)) {
          info ('Ignored file: %', path.cyan);
          return;
        }
        context.standaloneScripts.push ({
          path:    path,
          content: script
        });
      }
      else moduleHeaders.forEach (function (header)
      {
        setupModuleInfo (header, script, path);
      });
    });

  };

  this.trace = function (module)
  {
    /* jshint unused: vars */
    // Do nothing
  };

  this.build = function (targetScript)
  {
    /* jshint unused: vars */
    // Do nothing
  };

  //--------------------------------------------------------------------------------------------------------------------
  // PRIVATE
  //--------------------------------------------------------------------------------------------------------------------

  /**
   * Store information about the specified module retrieved from the given source code on the specified file.
   *
   * @param {ModuleHeaderInfo} moduleHeader
   * @param {string} fileContent
   * @param {string} filePath
   */
  function setupModuleInfo (moduleHeader, fileContent, filePath)
  {
    // Get information about the specified module.
    var module = context.modules[moduleHeader.name];
    // If this is the first time a specific module is mentioned, create the respective information record.
    if (!module)
      module = context.modules[moduleHeader.name] = new ModuleDef (moduleHeader.name);
    // Skip the file if it defines an external module.
    else if (module.external)
      return;
    // Reject additional attempts to redeclare a module (only appending is allowed).
    else if (module.head && !moduleHeader.append)
      fatal ('Can\'t redeclare module <cyan>%</cyan>', moduleHeader.name);
    // The file is appending definitions to a module declared elsewhere.
    if (moduleHeader.append) {
      // Append the file path to the paths list.
      if (!~module.bodyPaths.indexOf (filePath)) {
        module.bodies.push (fileContent);
        module.bodyPaths.push (filePath);
      }
    }
    // Otherwise, the file contains a module declaration.
    else {
      if (module.head)
        fatal ('Duplicate module definition: <cyan>%</cyan>', moduleHeader.name);
      module.head = fileContent;
      module.headPath = filePath;
      module.requires = moduleHeader.requires;
    }
    module.configFn = moduleHeader.configFn;
  }

}
1158755
function replaceFilePlaceholders(oFile, aReplacementRules) {
  // parse file
  const sRaw = oFile.contents.toString('utf8')
  const sUpdatedFile = aReplacementRules.reduce((oResult, oRule) => {
    return oResult.replace(oRule.identifier, oRule.content)
  }, sRaw)

  // update new raw content
  oFile.contents = new Buffer(sUpdatedFile)

  // return updated file
  return oFile
}
330681
def update_docstrings():
    
    modules_dict = parse_readme()
    files = {}
    # update modules
    for mod in modules_dict:
        mod_file = os.path.join(modules_directory(), mod + ".py")
        with open(mod_file) as f:
            files[mod] = f.readlines()

    for mod in files:
        replaced = False
        done = False
        lines = False
        out = []
        quotes = None
        for row in files[mod]:
            # deal with single or double quoted docstring
            if not quotes:
                if row.strip().startswith('"""'):
                    quotes = '"""'
                if row.strip().startswith("'''"):
                    quotes = "'''"
            if quotes and row.strip().startswith(quotes) and not done:
                out.append(row)
                if not replaced:
                    out = out + [
                        "".join(_to_docstring(modules_dict[mod])).strip() + "\n"
                    ]
                    replaced = True
                if lines:
                    done = True
                if not done and not lines:
                    lines = True
                continue
            if not lines or done:
                out.append(row)
        mod_file = os.path.join(modules_directory(), mod + ".py")
        with open(mod_file, "w") as f:
            f.writelines(out)
    print_stderr("Modules updated from README.md")
934646
function ()
		{
			var nmPath = this.modulePath + 'node_modules/';
			var pkgJson;
			var pkgName;
			var pkgInfo;
			var packageList = {};
			var validScript = /[\w|\W]+\.[js|coffee]+$/;
			if (fs.existsSync(nmPath))
			{
				this.e.log&&this.e.log('Importing packages...','system');
				var packages = fs.readdirSync(nmPath);
				for (p in packages)
				{
					try {
						if (packages[p].indexOf('wns')!==-1 &&
							(packages[p].indexOf('pkg') !== -1 || packages[p].indexOf('package') !== -1))
						{
							pkgName = packages[p];
							pkgDir = nmPath + pkgName;
							pkgJson = pkgDir + '/package.json';
							if (fs.existsSync(pkgJson))
							{
								pkgInfo = JSON.parse(fs.readFileSync(pkgJson));
								pkgInfo.require = pkgInfo.require||{};
								Object.defineProperty(pkgInfo,'classes',{ value: {}, enumerable: false })
								var files = fs.readdirSync(pkgDir);
								for (f in files)
								{
									var fileName = files[f].split('/').pop();
									if (validScript.test(fileName))
									{
										var className = fileName.split('.');
										className.splice(-1);
										pkgInfo.classes[className] = pkgDir+'/'+fileName;
									}
								}
								packageList[pkgInfo.name]=pkgInfo;
							}
						}
					} catch (e)
					{
						console.error('Error on loading package `'+pkgName+"`.")
						throw e;
					}
				}
			}

			this.removeInvalidPackages(packageList);
			this.loadPackages(packageList);
		}
883838
function checkPackageJson(pth, cb) {
  var p = path.join(pth, 'package.json');
  checkStatFile(p, function(err, pack){
    if (err) return cb(err);
    if (!pack || !pack.strider) return cb(null, false);
    if (!pack.strider.id) {
      pack.strider.id = pack.name;
    }
    return cb(null, pack.strider);
  });
}
408953
function WebpackLaravelMixManifest({ filename = null, transform = null } = {}) {
  this.filename = filename ? filename : 'mix-manifest.json';
  this.transform = transform instanceof Function ? transform : require('./transform');
}
1246252
def _replace_by(module_function, warn=False):
    """"""
    def decorate(func, module_function=module_function, warn=warn):
        sys.path.append(os.path.dirname(__file__))
        try:
            module, function = module_function.split('.')
            func, oldfunc = getattr(__import__(module), function), func
            globals()['__old_' + func.__name__] = oldfunc
        except Exception:
            if warn:
                warnings.warn("failed to import %s" % module_function)
        sys.path.pop()
        return func

    return decorate
1133996
function (uri) {
	var lastSlash = uri.lastIndexOf("/");
	var sub;
	if (lastSlash == -1) {
		sub = uri;
	} else {
		sub = uri.substr(lastSlash + 1);
	}
	sub = sub.toLowerCase();
	var parsed = parseModuleName(sub);
	var path = removeFiletype(parsed.modulePath || sub);
	var matches = path.match(/^[\w-\s\.]+/);
	return matches ? matches[0] : "";
}
121802
function getPackageMetaFile(answers) {
    const packageFields = ['name', 'version', 'license', 'category'];
    const packageObject = merge(pick(packageFields, answers),
        { dependencies: { 'rung-cli': '1.0.0' } });

    return {
        filename: path.join(answers.name, 'package.json'),
        content: JSON.stringify(packageObject, null, 2)
    };
}
951122
function getUpdatedEmittedFiles(emittedFiles, webpackRuntimeFiles) {
    let fallbackFiles = [];
    let hotHash;
    if (emittedFiles.some(x => x.endsWith('.hot-update.json'))) {
        let result = emittedFiles.slice();
        const hotUpdateScripts = emittedFiles.filter(x => x.endsWith('.hot-update.js'));
        hotUpdateScripts.forEach(hotUpdateScript => {
            const { name, hash } = parseHotUpdateChunkName(hotUpdateScript);
            hotHash = hash;
            // remove bundle/vendor.js files if there's a bundle.XXX.hot-update.js or vendor.XXX.hot-update.js
            result = result.filter(file => file !== `${name}.js`);
            if (webpackRuntimeFiles && webpackRuntimeFiles.length) {
                // remove files containing only the Webpack runtime (e.g. runtime.js)
                result = result.filter(file => webpackRuntimeFiles.indexOf(file) === -1);
            }
        });
        //if applying of hot update fails, we must fallback to the full files
        fallbackFiles = emittedFiles.filter(file => result.indexOf(file) === -1);
        return { emittedFiles: result, fallbackFiles, hash: hotHash };
    }
    else {
        return { emittedFiles, fallbackFiles };
    }
}
1371503
function replace(root, options, callback) {
	analyser.readDir(root, options, function(err, files) {
		files = _.flatten(files);
		_.each(files, function(file){ 
			fs.readFile(file, 'UTF-8', function(err, data) {
				if(err) {throw err;}
				var i, value;
				for(i=0; i<options.values.length; i++) {
					value = options.values[i];
					if(value === Object(value)) {
						for(var key in value) {
							if(value.hasOwnProperty(key)) {
								data = data.replace(new RegExp('{{'+key+'}}','g'), value[key]);
							}
						}
					}
					fs.writeFile(file, data);
				}
			});
		});	
		if(callback) {
			callback(err, files);
		}
	});
}
914572
function basePackageJson (opts) {
  opts = opts || {}
  const _name = opts.name || '<name>'
  const _version = opts.version || '1.0.0'
  const _private = opts.private || false

  var called = false

  return from({ objectMode: true }, function (size, next) {
    if (called) return next(null, null)

    const res = { name: _name, version: _version }
    if (_private) res.private = true
    res.scripts = {}
    res.dependencies = {}
    res.devDependencies = {}

    called = true
    next(null, res)
  })
}
331332
function findModuleVersion(modulePath, load) {
  if (modulePath) {
    var pjson = path.join(modulePath, 'package.json');
    if (fs.existsSync(pjson)) {
      return load(pjson).version;
    }
  }
  return process.version;
}
124623
function patchType (content, type, peerPaths) {
  let normalizedPaths = peerPaths.map(path => slash(normalize(path)))
  switch (type) {
    case 'script':
      let scriptImports = normalizedPaths.map(path => `import '${path}'\n`)
      content = content.replace(RE_SCRIPT, match => {
        return `${match}\n${scriptImports.join('')}`
      })
      break
    case 'style':
      let styleImports = normalizedPaths.map(path => {
        let langStr = ''
        let ext = getExtname(path)
        if (ext !== 'css') {
          langStr = `lang="${ext}" `
        }
        return `<style ${langStr}src="${path}"></style>\n`
      })
      content += styleImports.join('')
      break
    default:
      break
  }

  return content
}
1127680
async function updatePackageJSON (version) {
  ['package.json'].forEach(async fileName => {
    const filePath = path.resolve(__dirname, '..', fileName)
    const file = require(filePath)
    file.version = version
    await writeFile(filePath, JSON.stringify(file, null, 2))
  })
}
881760
function enableModuleReplacement(opts) {
  // TODO: use proxy here instead of just monkey-patching so all furure extensions are tracked automatically
  const savedExtensions = Module._extensions;
  const _extensions = {};
  Object.keys(savedExtensions).forEach(extension => {
    _extensions[extension] = function(module, filename) {
      addHMRHooks(module);
      savedExtensions[extension](module, filename);
    };
  });

  Module._extensions = _extensions;

  // module is changed, which dependency needs to be reloaded?
  function collectDependencies(module) {
    let paths = [];
    function pathsToAcceptingModules(path, root) {
      const requiredMe = parents[root.filename];
      if (module.hot._selfAccepted) {
        paths.push(path.concat(root.filename));
        return;
      }
      if (module.hot._selfDeclined) {
        return;
      }
      for (let next in requiredMe) {
        let parentHotRuntime = requiredMe[next].hot;
        if (parentHotRuntime._acceptedDependencies[root.filename]) {
          paths.push(path.concat(root.filename));
          continue;
        }
        if (parentHotRuntime._declinedDependencies[root.filename]) {
          continue;
        }
        pathsToAcceptingModules(path.concat(root.filename), requiredMe[next]);
      }
    }
    pathsToAcceptingModules([], module);
    return paths;
  }

  opts = opts || {};
  function ignore(path) {
    if (isBuiltinModule(path)) {
      return true;
    }
    if (typeof opts.ignore === 'function') {
      return opts.ignore(path);
    }
    if (opts.ignore instanceof RegExp) {
      return !!opts.ignore.exec(path);
    }
  }

  const watching = {};
  function startWatching(path) {
    if (ignore(path)) {
      return;
    }
    if (watching[path]) {
      return;
    }
    watching[path] = watch(path, { persistent: false }, function(eventType, filename) {
      const oldModule = require.cache[path];

      const deps = oldModule ? collectDependencies(oldModule) : [];
      const reloaded = {};

      for (let d = 0; d < deps.length; ++d) {
        for (let l = 0; l < deps[d].length; ++l) {
          const path = deps[d][l];
          if (reloaded[path]) {
            continue;
          }
          reloaded[path] = true;
          const oldModule = require.cache[path];
          if (oldModule.hot._disposeHandlers) {
            oldModule.hot._disposeHandlers.forEach(h => h());
          }
          const newModule = new Module(path, oldModule.parent);
          addHMRHooks(newModule);
          try {
            newModule.load(path);
            require.cache[path] = newModule;
            const ps = parents[path];
            for (parentPath in ps) {
              let parent = require.cache[parentPath];
              if (parent.hot._acceptedDependencies[path]) {
                // TODO: try/catch here?
                parent.hot._acceptedDependencies[path](path);
              }
            }
          } catch (e) {
            console.log(e);
          }
        }
      }
    });
  }

  // monkey-patch require
  const originalRequire = Module.prototype.require;
  const originalLoad = Module._load;
  const originalCompile = Module.prototype._compile;

  const parents = {};
  Module._load = function(request, parent, isMain) {
    const requirePath = Module._resolveFilename(request, parent);
    if (ignore(requirePath)) {
      return originalLoad(request, parent, isMain);
    }

    startWatching(requirePath);
    const parentPath = parent && parent.filename;
    const myParents = parents[requirePath];
    if (parentPath) {
      if (!myParents) {
        var p = {};
        p[parentPath] = parent;
        parents[requirePath] = p;
      } else {
        myParents[parentPath] = parent;
      }
    }
    return originalLoad(request, parent, isMain);
  };

  if (module.parent) {
    if (!module.parent.hot) {
      addHMRHooks(module.parent);
    }
  }

  function addHMRHooks(module) {
    const resolve = name => {
      return Module._resolveFilename(name, module);
    };
    // copied directly from webpack HMR
    // https://github.com/webpack/webpack/blob/0257f6c6e41255cf26230c099fb90140f1f0e0bb/lib/HotModuleReplacement.runtime.js#L77
    var hot = {
      // private stuff
      _acceptedDependencies: {},
      _declinedDependencies: {},
      _selfAccepted: false,
      _selfDeclined: false,
      _disposeHandlers: [],
      // _main: hotCurrentChildModule !== moduleId,

      // Module API
      active: true,
      accept: function(dep, callback) {
        if (typeof dep === 'undefined') hot._selfAccepted = true;
        else if (typeof dep === 'function') hot._selfAccepted = dep;
        else if (typeof dep === 'object')
          for (var i = 0; i < dep.length; i++)
            hot._acceptedDependencies[resolve(dep[i])] = callback || function() {};
        else hot._acceptedDependencies[resolve(dep)] = callback || function() {};
      },
      decline: function(dep) {
        if (typeof dep === 'undefined') hot._selfDeclined = true;
        else if (typeof dep === 'object')
          for (var i = 0; i < dep.length; i++) hot._declinedDependencies[resolve(dep[i])] = true;
        else hot._declinedDependencies[resolve(dep)] = true;
      },
      dispose: function(callback) {
        hot._disposeHandlers.push(callback);
      },
      addDisposeHandler: function(callback) {
        hot._disposeHandlers.push(callback);
      },
      removeDisposeHandler: function(callback) {
        var idx = hot._disposeHandlers.indexOf(callback);
        if (idx >= 0) hot._disposeHandlers.splice(idx, 1);
      }
      /*
      // TODO: Management API
      check: hotCheck,
      apply: hotApply,

      status: function(l) {
        if (!l) return hotStatus;
        hotStatusHandlers.push(l);
      },
      addStatusHandler: function(l) {
        hotStatusHandlers.push(l);
      },
      removeStatusHandler: function(l) {
        var idx = hotStatusHandlers.indexOf(l);
        if (idx >= 0) hotStatusHandlers.splice(idx, 1);
      }

      //inherit from previous dispose call
      data: hotCurrentModuleData[moduleId]
    */
    };
    module.hot = hot;
  }
}