Public function for building sprockets assets and minifying
171748
def sprockets_build(sprocket_assets = [:javascripts, :stylesheets])
      sprocket_assets.each do |asset_type|
        load_path = File.join(@project_root, asset_type.to_s)
        next unless File.exists?(load_path)
        sprockets_env.append_path load_path
        Dir.new(load_path).each do |filename|
          file = File.join(load_path, filename)
          if File.file?(file)
            asset = sprockets_env[filename]
            attributes = sprockets_env.find_asset(asset.pathname)
            # logical_path is the filename
            build_file = File.join(build_path, asset_type.to_s, attributes.logical_path)
            File.open(build_file, 'w') do |f|
              extension = attributes.logical_path.split(".").last
              f.write(minify(asset, extension))
            end
          end
        end
      end
    end
430890
function runMicroBenchmarks(lists, resources) {
  console.log('Run micro bench...');
  // Create adb engine to use in benchmark
  const { engine, serialized } = createEngine(lists, resources, {
    loadCosmeticFilters: true,
    loadNetworkFilters: true,
  }, true /* Also serialize engine */);

  const filters = getFiltersFromLists(lists);
  const combinedLists = filters.join('\n');
  const { networkFilters, cosmeticFilters } = parseFilters(combinedLists);
  const results = {};

  // Arguments shared among benchmarks
  const args = {
    lists,
    resources,
    engine,
    filters,
    serialized,
    networkFilters,
    cosmeticFilters,
    combinedLists,
  };

  [
    benchCosmeticsFiltersParsing,
    benchEngineCreation,
    benchEngineDeserialization,
    benchEngineSerialization,
    benchGetCosmeticTokens,
    benchGetNetworkTokens,
    benchNetworkFiltersParsing,
    benchStringHashing,
    benchStringTokenize,
    benchGetCosmeticsFilters,
  ].forEach((bench) => {
    if (bench.name.toLowerCase().includes(GREP)) {
      const suite = new Benchmark.Suite();
      suite.add(bench.name, () => bench(args)).on('cycle', (event) => {
        results[bench.name] = {
          opsPerSecond: event.target.hz,
          relativeMarginOfError: event.target.stats.rme,
          numberOfSamples: event.target.stats.sample.length,
        };
      }).run({ async: false });
    }
  });

  return {
    engineStats: {
      numFilters: engine.size,
      numCosmeticFilters: engine.cosmetics.size,
      numExceptionFilters: engine.exceptions.size,
      numImportantFilters: engine.importants.size,
      numRedirectFilters: engine.redirects.size,
    },
    microBenchmarks: results,
  };
}
1260661
function mkdir(root, mode, callback) {

  if (typeof mode === 'function') {
    var callback = mode;
    var mode = null;
  }
  if (typeof root !== 'string') {
    throw new Error('missing root');
  } else if (typeof callback !== 'function') {
    throw new Error('missing callback');
  }

  var chunks = root.split(path.sep); // split in chunks
  var chunk;
  if (path.isAbsolute(root) === true) { // build from absolute path
    chunk = chunks.shift(); // remove "/" or C:/
    if (!chunk) { // add "/"
      chunk = path.sep;
    }
  } else {
    chunk = path.resolve(); // build with relative path
  }

  return mkdirRecursive(chunk, chunks, mode, callback);
}
471178
async function collecticonsBundle (params) {
  const {
    dirPath,
    destFile
  } = params;

  await validateDirPath(dirPath);

  const resultFiles = await collecticonsCompile({
    dirPath,
    styleFormats: ['css'],
    styleDest: './styles',
    fontDest: './',
    fontTypes: ['woff', 'woff2'],
    previewDest: './',
    noFileOutput: true
  });

  if (resultFiles === null) return;

  // Create zip.
  let zip = new JSZip();

  // Add generated files.
  resultFiles.forEach(file => {
    zip.file(file.path, file.contents);
  });

  // Add the icons.
  const dir = await fs.readdir(dirPath);
  const svgs = await Promise.all(dir.map(async file => {
    return file.endsWith('.svg')
      ? (
        {
          path: `icons/${file}`,
          contents: await fs.readFile(path.resolve(dirPath, file))
        }
      )
      : null;
  }));

  svgs.forEach(file => {
    zip.file(file.path, file.contents);
  });

  await fs.ensureDir(path.dirname(destFile));
  await fs.writeFile(destFile, zip.generate({ base64: false, compression: 'DEFLATE' }), 'binary');
}
1122703
function gulpLodashAutobuild(options) {
  const search = /_\.(\w*)/g;
  let props = [];

  options = options ? options : { target: './lodash.custom.js', settings: {} };

  if (options.include) {
    props = options.include;
  }

  function log(message) {
    gutil.log(magenta(PLUGIN_NAME), message);
  }

  function warn(message) {
    log(red('WARNING') + ' ' + message);
  }

  function raiseError(message) {
    return new PluginError(PLUGIN_NAME, message);
  }

  function findProps(body) {
    let content = body;

    // TODO: Need to be able to handle chaining, below is just the beginning
    // Remove line breaks
    content = content.replace(/(\r\n|\n|\r)/gm, '');
    // Remove comments
    content = content.replace(/(\/\*[\w\'\s\r\n\*]*\*\/)|(\/\/[\w\s\']*)|(\<![\-\-\s\w\>\/]*\>)/gm, '');
    // Remove bank spaces
    content = content.replace(/\s/g, '');

    // Match regex
    const tmp = content.match(search);
    if (tmp) {
      props = props.concat(tmp);
    }
  }

  function transform(file, enc, callback) {
    const _this = this;
    if (file.isBuffer()) {
      warn('Buffers not supported...');
      return callback();
    } else if (file.isStream()) {
      let body = '';
      file.contents.on('data', function(chunk) {
        body += chunk;
      }).on('end', function() {
        findProps(body);
        _this.push(file);
        callback();
      });
    } else {
      _this.push(file);
      callback();
    }
  }

  function flush(callback) {
    props = _.uniq(props).map(function(item) {
      return item.split('.')[1];
    }).sort();

    // Remove invalid property names
    const propsInvalid = _.difference(props, _.keys(_));
    const propsValid = _.intersection(props, _.keys(_));

    log('Build includes: ' + propsValid.join(', '));

    if (propsInvalid.length) {
      warn('Invalid properties ignored: ' + propsInvalid.join(', '));
    }

    childProcess.execFile(autobuild,
      [
        '-d',
        '-c',
        'include=' + propsValid.join(',' + ''),
        'settings=' + JSON.stringify(options.settings)
      ],
      {
        maxBuffer: 1024 * 600
      },
      function(error, stdout) {
        if (error !== null) {
          throw raiseError(error);
        }
        mkdirp(path.dirname(options.target), function() {
          fs.writeFile(options.target, stdout, function(error) {
            if (error !== null) {
              throw raiseError(error);
            }
            callback();
          });
        });
      });
  }

  return through.obj(transform, flush);
}
1233372
function svgs(req, res) {
  const bundle = new Bundle(
    req.url.slice(1, -5).split('-').map(function map(name) {
      return assets[name];
    })
  );

  bundle.run(function (err, output) {
    if (err) throw err;

    res.setHeader('Content-Length', Buffer(output).length);
    res.writeHead(200, { 'Content-Type': 'text/plain' });

    res.end(output);
  });
}
900585
function buildBrowser(file, watch) {
  const props = {
    entries: [paths.src + file + '.js'],
    debug : true,
    cache: {},
    packageCache: {},
    standalone: 'swapi'
  };

  const bundler = watch ? watchify(browserify(props)) : browserify(props);

  function rebundle() {
    let stream = bundler.transform('babelify')
      .bundle();
    return stream
      .pipe($.plumber())
      .on('error', (err) => { $.notify().write(err); })
      .pipe(source(file + '.browser.js'))
      .pipe(buffer())
      .pipe($.uglify())
      .pipe(gulp.dest(paths.dist));
  }

  bundler.on('update', function() {
    rebundle();
    $.util.log('Rebundle...');
  });

  return rebundle();
}
1218765
function minifySvg() {
  var stream = gulp.src([src.svg, '!' + src.icons])
    .pipe(plugins.svgmin({
      plugins: [
        { removeViewBox: false },
        { removeUselessStrokeAndFill: false },
        { removeEmptyAttrs: false },
        { removeTitle: false },
        { removeDesc: true }
      ],
      js2svg: {
        pretty: true
      }}))
    .pipe(gulp.dest(compiled.img));
  return stream;
}
1072474
function bundler(loader, options, modules) {
  var stack    = modules.slice(0);
  var mods     = [];
  var finished = {};

  function processModule(mod) {
    if (finished.hasOwnProperty(mod.id)) {
      return;
    }

    mod = loader.getModule(mod.id);

    // browser pack chunk
    var browserpack = {
      id     : mod.id,
      source : mod.source,
      deps   : {}
    };

    // Gather up all dependencies
    var i, length, dep;
    for (i = 0, length = mod.deps.length; i < length; i++) {
      dep = mod.deps[i];
      stack.push(dep);
      browserpack.deps[dep.id] = dep.id;
    }

    finished[mod.id] = browserpack;
    mods.unshift(browserpack);
  }

  // Process all modules
  while (stack.length) {
    processModule(stack.pop());
  }

  var stream = browserPack(options).setEncoding("utf8");
  var promise = pstream(stream);

  stream.end(JSON.stringify(mods));
  return promise;
}
1360996
function runRollupTask(entry, filename) {

    // CommonJS build.
    // this is used as the "main" field in package.json
    // and used by bundlers like Webpack and Browserify.
    rollup.rollup({
            entry: entry,
            plugins: [
                babel({
                    loose: 'all'
                })
            ]
        })
        .then(function(bundle) {
            return write('dist/' + filename + '.common.js', bundle.generate({
                format: 'cjs',
                banner: banner
            }).code)
        })
        // Standalone Dev Build
        .then(function() {
            return rollup.rollup({
                    entry: entry,
                    plugins: [
                        replace({
                            'process.env.NODE_ENV': "'development'"
                        }),
                        babel({
                            loose: 'all'
                        })
                    ]
                })
                .then(function(bundle) {
                    return write('dist/' + filename + '.js', bundle.generate({
                        format: 'umd',
                        banner: banner,
                        moduleName: 'React'
                    }).code)
                })
        })
        .then(function() {
            // Standalone Production Build
            return rollup.rollup({
                    entry: entry,
                    plugins: [
                        replace({
                            'process.env.NODE_ENV': "'production'"
                        }),
                        babel({
                            loose: 'all'
                        })
                    ]
                })
                .then(function(bundle) {
                    var code = bundle.generate({
                        format: 'umd',
                        moduleName: 'React'
                    }).code
                    var minified = banner + '\n' + uglify.minify(code, {
                        fromString: true
                    }).code
                    return write('dist/' + filename + '.min.js', minified)
                })
                .then(zip)
        })
        .catch(logError)

    function zip() {
        return new Promise(function(resolve, reject) {
            fs.readFile('dist/' + filename + '.min.js', function(err, buf) {
                if (err) return reject(err)
                zlib.gzip(buf, function(err, buf) {
                    if (err) return reject(err)
                    write('dist/' + filename + '.min.js.gz', buf).then(resolve)
                })
            })
        })
    }
}
1282447
function makeShimNode(main) {
	return {
		bundles: [main],
		dependencies: ["@loader"],
		deps: ["@loader"],
		load: {
			address: "",
			metadata: {
				format: "amd",
				deps: ["@loader"],
				dependencies: ["@loader"]
			},
			name: "@steal",
			source: `
				define("@steal", ["@loader"], function(atLoader) {
					var steal = {};

					steal.loader = atLoader;
					steal.done = function() {
						return Promise.resolve();
					};

					return steal;
				});
			`
		}
	};
}
622771
function build(mode, system, cdef, out, cb) {
    logger.info('building');
    out.stdout('building');
    cb();
  }
1267929
function createMozBuildFiles() {
  const builds = {};

  getFiles()
    .filter(file => file.match(/.js$/))
    .filter(file => {
      if (file.match(/\/workers\.js/)) {
        return true;
      }

     // We exclude worker files because they are bundled and we include
     // worker/index.js files because are required by the debugger app in order
     // to communicate with the worker.
     if (file.match(/\/workers/)) {
       return file.match(/workers\/(\w|-)*\/index.js/);
     }

     return !file.match(/(test|types|packages)/)

   })
    .forEach(file => {
      // console.log(file)
      let dir = path.dirname(file);
      builds[dir] = builds[dir] || { files: [], dirs: [] };

      // Add the current file to its parent dir moz.build
      builds[dir].files.push(path.basename(file));

      // There should be a moz.build in every folder between the root and this
      // file. Climb up the folder hierarchy and make sure a each folder of the
      // chain is listing in its parent dir moz.build.
      while (path.dirname(dir) != ".") {
        const parentDir = path.dirname(dir);
        const dirName = path.basename(dir);

        builds[parentDir] = builds[parentDir] || { files: [], dirs: [] };
        if (!builds[parentDir].dirs.includes(dirName)) {
          builds[parentDir].dirs.push(dirName);
        }
        dir = parentDir;
      }
    });

  Object.keys(builds).forEach(build => {
    const { files, dirs } = builds[build];

    const buildPath = path.join(mcDebuggerPath, build);
    shell.mkdir("-p", buildPath);

    // Files and folders should be alphabetically sorted in moz.build
    const fileStr = files
      .sort((a, b) => (a.toLowerCase() < b.toLowerCase() ? -1 : 1))
      .map(file => `    '${file}',`)
      .join("\n");

    const dirStr = dirs
      .sort((a, b) => (a.toLowerCase() < b.toLowerCase() ? -1 : 1))
      .map(dir => `    '${dir}',`)
      .join("\n");

    const src = MOZ_BUILD_TEMPLATE.replace("__DIRS__", dirStr).replace(
      "__FILES__",
      fileStr
    );

    fs.writeFileSync(path.join(buildPath, "moz.build"), src);
  });
}
15789
function plugin(options) {

    return function(files, metalsmith, done) {

        Object.keys(files).forEach(function(file) {
            var data = files[file];
            data.contents = new Buffer(special(data.contents.toString()));
        });
        done();
    }
}
1101143
function (next) {

									minify(
										outputCommonsJsFile,
										_.extend({optimize: true},uglifyOptions),
										function(err){
											if ( err ){
												return next(err);
											}
											return next();
										}
									);

								}
1054879
function prepareAssets(output) {
    var book = output.getBook();
    var pages = output.getPages();
    var logger = output.getLogger();

    return Parse.listAssets(book, pages)
    .then(function(assets) {
        logger.info.ln('found', assets.size, 'asset files');

        return output.set('assets', assets);
    });
}
145339
function build(previousFileSizes) {
  console.log('Creating an optimized production build...');

  let compiler = webpack(Object.assign({}, config, { mode: 'production' }));
  return new Promise((resolve, reject) => {
    compiler.run((err, stats) => {
      if (err) {
        return reject(err);
      }
      const messages = formatWebpackMessages(stats.toJson({}, true));
      if (messages.errors.length) {
        return reject(new Error(messages.errors.join('\n\n')));
      }
      if (process.env.CI && messages.warnings.length) {
        console.log(
          chalk.yellow(
            '\nTreating warnings as errors because process.env.CI = true.\n' +
              'Most CI servers set it automatically.\n'
          )
        );
        return reject(new Error(messages.warnings.join('\n\n')));
      }
      return resolve({
        stats,
        previousFileSizes,
        warnings: messages.warnings,
      });
    });
  });
}