Run compression for all specified platforms.
@return {undefined}
160466
function run() {
  platforms.forEach(function(platform) {
    var wwwPath;

    switch (platform) {
      case 'android':
        wwwPath = path.join(platformPath, platform, 'assets', 'www');
        if (!fs.existsSync(wwwPath)) {
          wwwPath = path.join(platformPath, platform, 'app', 'src', 'main', 'assets', 'www');
        }
        break;

      case 'ios':
      case 'browser':
      case 'wp8':
      case 'windows':
        wwwPath = path.join(platformPath, platform, 'www');
        break;

      default:
        console.log('this hook only supports android, ios, wp8, windows, and browser currently');
        return;
    }

    processFolders(wwwPath);
  });
}
88758
function () {
    var envJson = ko.utils.stringifyJson(this.app.getEnvironment()),
        datasJson = ko.utils.stringifyJson(this.datas, function replacer(key, value) {
          if (typeof value === "undefined" || value == null) {
            return '';
          }
          return value;
        }),
        compressType = '',
        compression = false
    if (window.trimServerEventData) {
        datasJson = window.trimServerEventData(datasJson);
    }
    if (this.compression) {
        if (!env.isIE8 && window.pako) {
            envJson = encodeBase64(window.pako.gzip(envJson));
            datasJson = encodeBase64(window.pako.gzip(datasJson));
            compression = true
            compressType = 'gzip'
        }
    }
    return {
        environment: envJson,
        dataTables: datasJson,
        compression: compression,
        compressType: compressType
    }
}
1340634
public function compress()
    {
        Service::$log->msg('Compression started');

        $cmd = $this->cmd . ' ' . $this->destination . ' ' . implode(' ', $this->sources);

        Service::$log->msg('Compression command: ' . $cmd);
        system($cmd);
        Service::$log->msg('Compression ended');

        Cleanup::addToQueue($this->destination, Cleanup::TYPE_FILE);

        return $this->destination;
    }
1008038
function gzip(input, options) {
  options = options || {};
  options.gzip = true;
  return deflate(input, options);
}
1016257
function compile (extension, content, options, fn) {
    // allow optional options argument
    if (_.isFunction(options)) {
      fn = options;
      options = {};
    }

    var config = _.clone(compile.configuration)
      , args = flags.slice(0)
      , buffer = ''
      , errors = ''
      , compressor;

    if (compile.configuration.type) {
      config.type = extension;
    }

    // generate the --key value options, both the key and the value should added
    // seperately to the `args` array or the child_process will chocke.
    Object.keys(config).filter(function filter (option) {
      return config[option];
    }).forEach(function format (option) {
      var bool = _.isBoolean(config[option]);

      if (!bool || config[option]) {
        args.push('--' + option);
        if (!bool) args.push(config[option]);
      }
    });

    // apply the configuration
    _.extend(config, options);

    // spawn the shit and set the correct encoding
    compressor = spawn(type, args);
    compressor.stdout.setEncoding('utf8');
    compressor.stderr.setEncoding('utf8');

    /**
     * Buffer up the results so we can concat them once the compression is
     * finished.
     *
     * @param {Buffer} chunk
     * @api private
     */

    compressor.stdout.on('data', function data (chunk) {
      buffer += chunk;
    });

    compressor.stderr.on('data', function data (err) {
      errors += err;
    });

    /**
     * The compressor has finished can we now process the data and see if it was
     * a success.
     *
     * @param {Number} code
     * @api private
     */

    compressor.on('close', function close (code) {
      // invalid states
      if (errors.length) return fn(new Error(errors));
      if (code !== 0) return fn(new Error('process exited with code ' + code));
      if (!buffer.length) return fn(new Error('no data returned ' + type + args));

      // correctly processed the data
      fn(null, buffer);
    });

    // write out the content that needs to be minified
    compressor.stdin.end(content);
  }
850377
function run(ctx) {
  var projectRoot = ctx.opts.projectRoot;
  var iosProjectFilePath = path.join(projectRoot, 'platforms', 'ios');
  var configXmlHelper = new ConfigXmlHelper(ctx);
  var newProjectName = configXmlHelper.getProjectName();

  var oldProjectName = getOldProjectName(iosProjectFilePath);

  // if name has not changed - do nothing
  if (oldProjectName.length && oldProjectName === newProjectName) {
    return;
  }

  console.log('Project name has changed. Renaming .entitlements file.');

  // if it does - rename it
  var oldEntitlementsFilePath = path.join(iosProjectFilePath, oldProjectName, 'Resources', oldProjectName + '.entitlements');
  var newEntitlementsFilePath = path.join(iosProjectFilePath, oldProjectName, 'Resources', newProjectName + '.entitlements');

  try {
    fs.renameSync(oldEntitlementsFilePath, newEntitlementsFilePath);
  } catch (err) {
    console.warn('Failed to rename .entitlements file.');
    console.warn(err);
  }
}
344935
function() {
    this.versionMajor = undefined;
    this.versionMinor = undefined;
    this.dataCipherUuid = undefined;
    this.compression = undefined;
    this.masterSeed = undefined;
    this.transformSeed = undefined;
    this.keyEncryptionRounds = undefined;
    this.encryptionIV = undefined;
    this.protectedStreamKey = undefined;
    this.streamStartBytes = undefined;
    this.crsAlgorithm = undefined;
    this.endPos = undefined;
    this.kdfParameters = undefined;
    this.publicCustomData = undefined;
    Object.preventExtensions(this);
}
1043811
function shouldCompress (req, res) {
  var type = res.getHeader('Content-Type')

  if (type === undefined || !compressible(type)) {
    debug('%s not compressible', type)
    return false
  }

  return true
}
1112631
function runClean(options) {
    const platforms = detectPorting(options.platform);
    if (platforms.length <= 0) {
        return Promise.resolve();
    } else {
        platforms.forEach((platform) => {
            if ('dev' === platform) {
                // app/porting
                const dev_porting_dir = path.join(__dirname, '..', config.dir.src, config.dir.porting);
                Object.keys(config.built_cleanee).forEach((key) => {
                    del.sync(config.built_cleanee[key], { cwd: dev_porting_dir });
                });
            } else {
                // platforms/<platform>/porting
                const platform_porting_dir = path.join(__dirname, '../platforms', platform, config.dir.porting);
                Object.keys(config.built_cleanee).forEach((key) => {
                    del.sync(config.built_cleanee[key], { cwd: platform_porting_dir });
                });
                // platforms/<platform>/platform_www/porting
                const platform_www_porting_dir = path.join(__dirname, '../platforms', platform, 'platform_www', config.dir.porting);
                del.sync(platform_www_porting_dir);
            }
        });
    }
}
597840
function Compressor() {
    var self = this;
    var regexps = [/[\n\r\t]+/g, /\s{2,}/g];

    /**
     * Remover of the html comment blocks
     * @param html
     * @returns {*}
     * @private
     */
    function _clearHTMLComments(html) {
        var cStart = '<!--',
            cEnd = '-->',
            beg = html.indexOf(cStart),
            end = 0;

        while (beg !== -1) {
            end = html.indexOf(cEnd, beg + 4);

            if (end === -1) {
                break;
            }

            var comment = html.substring(beg, end + 3);

            if (comment.indexOf("[if") !== -1 || comment.indexOf("![endif]") !== -1) { // skip
                beg = html.indexOf(cStart, end + 3);
                continue;
            }

            html = html.replace(comment, "");
            beg = html.indexOf(cStart, end + 3);
        }

        return html;
    }

    // ---- ---- ---- ---- ----

    /**
     * Compressor of the html string
     * @param {String} html
     * @returns {*}
     */
    self.compressHTML = function(html) {
        if (html === null || html === "")
            return html;

        html = _clearHTMLComments(html);

        var tags = ["script", "textarea", "pre", "code"],
            id = new Date().getTime() + "#",
            cache = {},
            index = 0;

        tags.forEach(function(tag, i) {
            var tagS = '<' + tag,
                tagE = '</' + tag + '>',
                start = html.indexOf(tagS),
                end = 0,
                len = tagE.length;

            while (start !== -1) {
                end = html.indexOf(tagE, start);
                if (end === -1) {
                    break;
                }

                var key = id + (index++),
                    value = html.substring(start, end + len);

                if (i === 0) {
                    end = value.indexOf(">");
                    len = value.indexOf('type="text/template"');
                    if (len < end && len !== -1) {
                        break;
                    }
                    len = value.indexOf('type="text/html"');
                    if (len < end && len !== -1) {
                        break;
                    }
                }
                cache[key] = value;
                html = html.replace(value, key);
                start = html.indexOf(tagS, start + tagS.length);
            }
        });

        regexps.forEach(function(regexp) {
            html = html.replace(regexp, "");
        });

        Object.keys(cache).forEach(function(key) {
            html = html.replace(key, cache[key]);
        });

        return html;
    };

    // api ----
    return self;
}
1121483
def compressed
      @compressed ||= case @type
      when 'css'
        Sass::Engine.new(joined, :syntax => :scss, :cache => false, :style => :compressed).render rescue joined
      when 'js'
        Uglifier.compile(joined, :mangle => false, :comments => :none) rescue joined
      end
    end
754048
protected function maybeCompressJsCode($js)
    {
        if (($benchmark = !empty($this->options['benchmark']) && $this->options['benchmark'] === 'details')) {
            $time = microtime(true);
        }
        $js = (string) $js; // Force string value.

        if (isset($this->options['compress_js_code'])) {
            if (!$this->options['compress_js_code']) {
                $disabled = true; // Disabled flag.
            }
        }
        if (!$js || !empty($disabled)) {
            goto finale; // Nothing to do.
        }
        if (strlen($js) > 1000000) {
            // Exclude VERY large files. Too time-consuming.
            // Should really be compressed ahead-of-time anyway.
            goto finale; // Don't compress HUGE files.
        }
        try { // Catch JS compression-related exceptions.
            if (!($compressed_js = \WebSharks\JsMinifier\Core::compress($js))) {
                // `E_USER_NOTICE` to avoid a show-stopping problem.
                trigger_error('JS compression failure.', E_USER_NOTICE);
            } else {
                $js = $compressed_js;
            } // Use compressed JS file.
        } catch (\Exception $exception) {
            trigger_error($exception->getMessage(), E_USER_NOTICE);
        }
        finale: // Target point; finale/return value.

        if ($js) {
            $js = trim($js);
        }
        if ($benchmark && !empty($time) && $js && empty($disabled)) {
            $this->benchmark->addTime(
                __FUNCTION__,
                $time, // Caller, start time, task performed.
                sprintf('compressing JS w/ checksum: `%1$s`', md5($js))
            );
        }
        return $js;
    }
613288
function zip_deflate_start(level) {
    var i;

    if (!level)
        level = zip_DEFAULT_LEVEL;
    else if (level < 1)
        level = 1;
    else if (level > 9)
        level = 9;

    zip_compr_level = level;
    zip_initflag = false;
    zip_eofile = false;
    if (zip_outbuf != null)
        return;

    zip_free_queue = zip_qhead = zip_qtail = null;
    zip_outbuf = new Array(zip_OUTBUFSIZ);
    zip_window = new Array(zip_window_size);
    zip_d_buf = new Array(zip_DIST_BUFSIZE);
    zip_l_buf = new Array(zip_INBUFSIZ + zip_INBUF_EXTRA);
    zip_prev = new Array(1 << zip_BITS);
    zip_dyn_ltree = new Array(zip_HEAP_SIZE);
    for (i = 0; i < zip_HEAP_SIZE; i++)
        zip_dyn_ltree[i] = new zip_DeflateCT();
    zip_dyn_dtree = new Array(2 * zip_D_CODES + 1);
    for (i = 0; i < 2 * zip_D_CODES + 1; i++)
        zip_dyn_dtree[i] = new zip_DeflateCT();
    zip_static_ltree = new Array(zip_L_CODES + 2);
    for (i = 0; i < zip_L_CODES + 2; i++)
        zip_static_ltree[i] = new zip_DeflateCT();
    zip_static_dtree = new Array(zip_D_CODES);
    for (i = 0; i < zip_D_CODES; i++)
        zip_static_dtree[i] = new zip_DeflateCT();
    zip_bl_tree = new Array(2 * zip_BL_CODES + 1);
    for (i = 0; i < 2 * zip_BL_CODES + 1; i++)
        zip_bl_tree[i] = new zip_DeflateCT();
    zip_l_desc = new zip_DeflateTreeDesc();
    zip_d_desc = new zip_DeflateTreeDesc();
    zip_bl_desc = new zip_DeflateTreeDesc();
    zip_bl_count = new Array(zip_MAX_BITS + 1);
    zip_heap = new Array(2 * zip_L_CODES + 1);
    zip_depth = new Array(2 * zip_L_CODES + 1);
    zip_length_code = new Array(zip_MAX_MATCH - zip_MIN_MATCH + 1);
    zip_dist_code = new Array(512);
    zip_base_length = new Array(zip_LENGTH_CODES);
    zip_base_dist = new Array(zip_D_CODES);
    zip_flag_buf = new Array(parseInt(zip_LIT_BUFSIZE / 8));
}
1232090
function run () {
  var midSequence = this.middlewares.reverse()
  var initialNext = this.next.bind()
  var req = this.req
  var res = this.res
  var nestedCallSequence

  // create the call sequence
  nestedCallSequence = midSequence.reduce(middlewareReducer, initialNext)
  // call it
  nestedCallSequence.call()

  /**
   * Reduce the middleware sequence to a nested middleware handler sequence
   * @function
   * @inner
   * @private
   * @param {Function} callSequence intermediate resulting call sequence
   * @param {Function} middleware the current middleware
   * @returns {Function} the new intermediate resulting call sequence
   */
  function middlewareReducer (callSequence, middleware) {
    return function nextHandler (err) {
      // if the previous middleware passed an error argument
      if (err !== undefined) {
        if (isErrorHandler(middleware)) {
          // call the current middleware if it is an error handler middleware
          middleware(err, req, res, callSequence)
        } else {
          // else skip the current middleware and call the intermediate sequence
          callSequence(err)
        }
      } else {
        // if no error argument is passed
        if (isErrorHandler(middleware)) {
          // skip the current middleware if it is an errorHandler
          callSequence()
        } else {
          // else call it
          middleware(req, res, callSequence)
        }
      }
    }
  }
}
387229
function(o) {
    o = o || {};
    if (o.base64 === true && (o.binary === null || o.binary === undefined)) {
        o.binary = true;
    }
    o = extend(o, defaults);
    o.date = o.date || new Date();
    if (o.compression !== null) o.compression = o.compression.toUpperCase();

    return o;
}
157890
function custom(platforms, platform) {
    var plat;
    var id;
    var uri;
    var url;
    var version;
    var subdir;
    var platdir;
    var download_dir;
    var tmp_dir;
    var lib_dir;
    var isUri;
    if (!(platform in platforms)) {
        return Q.reject(new Error('judpack library "' + platform + '" not recognized.'));
    }

    plat = _.extend({}, stubplatform, platforms[platform]);
    version = plat.version;
    // Older tools can still provide uri (as opposed to url) as part of extra
    // config to create, it should override the default url provided in
    // platfroms.js
    url = plat.uri || plat.url;
    id = plat.id;
    subdir = plat.subdirectory;
    platdir = plat.altplatform || platform;
    // Return early for already-cached remote URL, or for local URLs.
    uri = URL.parse(url);
    isUri = uri.protocol && uri.protocol[1] != ':'; // second part of conditional is for awesome windows support. fuuu windows
    if (isUri) {
        download_dir = path.join(util.libDirectory, platdir, id, version);
        lib_dir = path.join(download_dir, subdir);
        if (fs.existsSync(download_dir)) {
            events.emit('verbose', id + ' library for "' + platform + '" already exists. No need to download. Continuing.');
            return Q(lib_dir);
        }
    } else {
        // Local path.
        lib_dir = path.join(url, subdir);
        return Q(lib_dir);
    }

    return HooksRunner.fire('before_library_download', {
        platform:platform,
        url:url,
        id:id,
        version:version
    }).then(function() {
        var uri = URL.parse(url);
        var d = Q.defer();
        npm.load(function(err) {
            // Check if NPM proxy settings are set. If so, include them in the request() call.
            var proxy;
            if (uri.protocol == 'https:') {
                proxy = npm.config.get('https-proxy');
            } else if (uri.protocol == 'http:') {
                proxy = npm.config.get('proxy');
            }
            var strictSSL = npm.config.get('strict-ssl');

            // Create a tmp dir. Using /tmp is a problem because it's often on a different partition and sehll.mv()
            // fails in this case with "EXDEV, cross-device link not permitted".
            var tmp_subidr = 'tmp_' + id + '_' + process.pid + '_' + (new Date()).valueOf();
            tmp_dir = path.join(util.libDirectory, 'tmp', tmp_subidr);
            shell.rm('-rf', tmp_dir);
            shell.mkdir('-p', tmp_dir);

            var size = 0;
            var request_options = {url:url};
            if (proxy) {
                request_options.proxy = proxy;
            }
            if (typeof strictSSL == 'boolean') {
                request_options.strictSSL = strictSSL;
            }
            events.emit('verbose', 'Requesting ' + JSON.stringify(request_options) + '...');
            events.emit('log', 'Downloading ' + id + ' library for ' + platform + '...');
            var req = request.get(request_options, function(err, res, body) {
                if (err) {
                    shell.rm('-rf', tmp_dir);
                    d.reject(err);
                } else if (res.statusCode != 200) {
                    shell.rm('-rf', tmp_dir);
                    d.reject(new Error('HTTP error ' + res.statusCode + ' retrieving version ' + version + ' of ' + id + ' for ' + platform));
                } else {
                    size = body.length;
                }
            });
            req.pipe(zlib.createUnzip())
            .on('error', function(err) {
                // Sometimes if the URL is bad (most likely unavailable version), and git-wip-us.apache.org is
                // particularly slow at responding, we hit an error because of bad data piped to zlib.createUnzip()
                // before we hit the request.get() callback above (with a 404 error). Handle that gracefully. It is
                // likely that we will end up calling d.reject() for an HTTP error in the request() callback above, but
                // in case not, reject with a useful error here.
                d.reject(new Error('Unable to fetch platform ' + platform + '@' + version + ': Error: version not found.'));
            })
            .pipe(tar.Extract({path:tmp_dir}))
            .on('error', function(err) {
                shell.rm('-rf', tmp_dir);
                d.reject(err);
            })
            .on('end', function() {
                events.emit('verbose', 'Downloaded, unzipped and extracted ' + size + ' byte response.');
                events.emit('log', 'Download complete');
                var entries = fs.readdirSync(tmp_dir);
                var entry = path.join(tmp_dir, entries[0]);
                shell.mkdir('-p', download_dir);
                shell.mv('-f', path.join(entry, '*'), download_dir);
                shell.rm('-rf', tmp_dir);
                d.resolve(HooksRunner.fire('after_library_download', {
                    platform:platform,
                    url:url,
                    id:id,
                    version:version,
                    path: lib_dir,
                    size:size,
                    symlink:false
                }));
            });
        });
        return d.promise.then(function () { return lib_dir; });
    });
}
149125
function compressDistributionPackage() {
  const src = [
    path.join(__dirname, 'build/**'),
    path.join(__dirname, 'LICENSE'),
    path.join(__dirname, 'CHANGELOG.md'),
    path.join(__dirname, 'bindings/*/esm/**'),
    path.join(__dirname, 'bindings/*/dist/**'),
    '!' + path.join(__dirname, 'build/docs/**'),
    '!' + path.join(__dirname, 'build/docs'),
  ];

  return gulp.src(src)
    .pipe($.zip('onsenui.zip'))
    .pipe(gulp.dest(path.join(__dirname, 'build')));
}