<commit_before>'use strict';

var Promise = require('bluebird');
var exec = require('child_process').exec;
var fs = Promise.promisifyAll(require('fs'));
var git = require('git-rev');
var nconf = require('nconf');
var open = require('open');
var path = require('path');
var R = require('ramda');
var request = require('request-promise');
var WebdriverCSS = require('webdrivercss');
var WebdriverIO = require('webdriverio');

var uploads = [];

var client = {};

// The images tath were processed.
var processedRes = [];

// @todo: Get this info from the "uploads" variable.
var buildId;

var gitCommit;
var gitBranch;

git.long(function (str) {
  gitCommit = str;
});

git.branch(function (str) {
  gitBranch = str;
});

/**
 * Get the commit subject.
 */
var gitSubject = new Promise(function(resolve, reject) {
  exec('git log HEAD -1 --format=%s', function(err, stdout) {
    if(err) {
      reject(err);
    }
    else {
      resolve(stdout.replace('\n', ''));
    }
  });
});

/**
 * Get the directory prefix from the repository root.
 */
var gitPrefix = new Promise(function(resolve, reject) {
  exec('git rev-parse --show-prefix', function(err, stdout) {
    if(err) {
      reject(err);
    }
    else {
      resolve(stdout.replace('\n', ''));
    }
  });
});

var gitRepoName = new Promise(function(resolve, reject) {
  exec('git config --get remote.origin.url', function(err, stdout) {
    if(err) {
      reject(err);
    }
    else {
      // @todo: Be more careful with the assumptions about the URL
      var output = stdout
        .replace('\n', '')
        .replace('git@github.com:', '')
        .replace('https://github.com/', '')
        .replace('.git', '');

      resolve(output);
    }
  });
});

/**
 * Get config from file or environment.
 *
 * JSON file is in ~/.shoov.json
 *
 * @param str
 *   The config name.
 * @param defaultValue
 *   The default value.
 * @param bool addPrefix
 *   Determins if the "SHOOV_" prefix should be added to the variable. Defaults
 *   to TRUE.
 *
 *
 * @returns {*}
 */
var getConfig = function(str, defaultValue, addPrefix) {
  // Set config hierarchy.
  var configFile = process.env[(process.platform == 'win32') ? 'USERPROFILE' : 'HOME'] + '/.shoov.json';
  nconf
    .env()
    .file(configFile);

  addPrefix = addPrefix || true;

  var prefix = addPrefix ? 'SHOOV_' : '';

  var upperCase = prefix + str.toUpperCase();
  var confValue = nconf.get(str) || nconf.get(upperCase);
  return confValue || defaultValue;
};

/**
 * Upload the image.
 *
 * @param obj
 */
var uploadFailedImage = function(obj) {
  var accessToken = getConfig('access_token');
  if (!accessToken) {
    throw new Error('The Shoov access token is not defined, visit your account page.');
  }

  var backendUrl = getConfig('backend_url', 'https://dev-shoov.pantheon.io');
  var options = {
    url: backendUrl + '/api/screenshots-upload',
    headers: {
      'access-token': accessToken
    }
  };

  var gitData = {
    gitSubject: gitSubject,
    gitPrefix: gitPrefix,
    gitRepoName: gitRepoName
  };

  var uploadResponse = '';

  Promise.props(gitData)
    .then(function(gitData) {
      var req = request.post(options);
      req
        .on('error', function (err) {
          throw new Error(err);
        })
        .on('data', function(chunk) {
          uploadResponse += chunk;
        })
        .on('end', function() {
          var data = JSON.parse(uploadResponse).data[0];
          // Populate the build ID.
          buildId = buildId || data.build;

          if (getConfig('debug')) {
            // Show response.
            console.log(data);
          }
        })
        .on('response', function(response) {
          if (response.statusCode >= 500) {
            throw new Error('Backend error');
          }
          else if (response.statusCode !== 200) {
            throw new Error('Access token is incorrect or no longer valid, visit your account page');
          }
        });

      var form = req.form();

      var label = path.basename(obj.baselinePath, '.baseline.png').replace('.', ' ');
      form.append('label', label);

      form.append('baseline', fs.createReadStream(obj.baselinePath));
      form.append('regression', fs.createReadStream(obj.regressionPath));
      form.append('diff', fs.createReadStream(obj.diffPath));

      form.append('baseline_name', obj.baselinePath);
      form.append('git_commit', gitCommit);
      form.append('git_branch', gitBranch);
      form.append('git_subject', gitData.gitSubject);

      form.append('directory_prefix', gitData.gitPrefix);
      form.append('repository', gitData.gitRepoName);

      uploads.push(req);
    });

  throw new Error('Found regression in test');
};

var wdcssSetup = {

  /**
   * Init the client.
   */
  before: function(done, caps) {
    client = this.getClient(done, caps);
    WebdriverCSS.init(client);

    return client;
  },

  after: function(done) {
    return Promise
      .all(uploads)
      .then(function() {
        if (uploads.length) {
          var clientUrl = getConfig('client_url', 'http://shoov.gizra.com');
          var regressionUrl = clientUrl + '/#/screenshots/' + buildId;
          console.log('See regressions in: ' + regressionUrl);

          if (getConfig('open_link')) {
            open(regressionUrl)
          }
        }

        client.end(done);
      });
  },

  processResults: function(err, res) {
    if (err) {
      console.error(err);
    }

    // @todo: Convert to Ramda.
    // Keep only images that were not processed yet.
    var newRes = {};
    Object.keys(res).forEach(function(key) {
      if (processedRes.indexOf(key) == -1) {
        var val = res[key];
        newRes[key] = val;
        processedRes.push(key);
      }
    });

    var isNotWithinMisMatchTolerance = R.filter(R.where({isWithinMisMatchTolerance: false}));
    var uploadImages = R.mapObj(R.forEach(uploadFailedImage));
    var checkImages = R.compose(uploadImages, R.mapObj(isNotWithinMisMatchTolerance));

    checkImages(newRes);
  },

  getUploadedRequests: function() {
    return uploads;
  },

  /**
   * Get client.
   *
   * @param done
   *   Mocha's done callback.
   * @param capsConfig
   *   The capabilities configuration. If empty, default one will be used.
   */
  getClient : function (done, caps) {
    caps = caps || {};

    var capsProvided = !!Object.keys(caps).length;

    // We follow the naming conventions of the username and key, as proivded by
    // the different service providers.
    var sauceUserName = getConfig('sauce_username', false, false);
    var sauceAccessKey = getConfig('sauce_access_key', false, false);

    var browserStackUserName = getConfig('browserstack_username', false, false);
    var browserStackKey = getConfig('browserstack_key', false, false);

    if (sauceUserName && sauceAccessKey) {
      if (!capsProvided) {
        // Set default capabilities.
        caps['browserName'] = 'chrome';
        caps['platform'] = 'Linux';
        caps['version'] = '41.0';
        caps['screenResolution'] = '1024x768';
      }

      client = WebdriverIO.remote({
        desiredCapabilities: caps,
        host: 'ondemand.saucelabs.com',
        port: 80,
        user: sauceUserName,
        key: sauceAccessKey
      });
    }
    else if (browserStackUserName && browserStackKey) {
      if (!capsProvided) {
        // Set default capabilities.
        caps['browser'] = 'Chrome';
        caps['browser_version'] = '39.0';
        caps['os'] = 'OS X';
        caps['os_version'] = 'Yosemite';
        caps['resolution'] = '1024x768';
      }

      caps['browserstack.user'] = browserStackUserName;
      caps['browserstack.key'] = browserStackKey;
      caps['browserstack.debug'] = 'true';

      client = WebdriverIO.remote({
        desiredCapabilities: caps,
        host: 'hub.browserstack.com',
        port: 80
      });
    }
    else {
      client = WebdriverIO.remote({ desiredCapabilities: {browserName: 'phantomjs'} });
    }

    // Init the client.
    client.init(done);

    var width;
    var height;

    if (capsProvided && caps.resolution) {
      var size = caps.resolution.split('x');
      width = parseInt(size[0]);
      height = parseInt(size[1]);
    }

    width = width || 1024;
    height = height || 768;

    client.setViewportSize({
      width: width,
      height: height
    });

    return client;
  }
};

module.exports = wdcssSetup;
<commit_msg>Update client URL<commit_after>'use strict';

var Promise = require('bluebird');
var exec = require('child_process').exec;
var fs = Promise.promisifyAll(require('fs'));
var git = require('git-rev');
var nconf = require('nconf');
var open = require('open');
var path = require('path');
var R = require('ramda');
var request = require('request-promise');
var WebdriverCSS = require('webdrivercss');
var WebdriverIO = require('webdriverio');

var uploads = [];

var client = {};

// The images tath were processed.
var processedRes = [];

// @todo: Get this info from the "uploads" variable.
var buildId;

var gitCommit;
var gitBranch;

git.long(function (str) {
  gitCommit = str;
});

git.branch(function (str) {
  gitBranch = str;
});

/**
 * Get the commit subject.
 */
var gitSubject = new Promise(function(resolve, reject) {
  exec('git log HEAD -1 --format=%s', function(err, stdout) {
    if(err) {
      reject(err);
    }
    else {
      resolve(stdout.replace('\n', ''));
    }
  });
});

/**
 * Get the directory prefix from the repository root.
 */
var gitPrefix = new Promise(function(resolve, reject) {
  exec('git rev-parse --show-prefix', function(err, stdout) {
    if(err) {
      reject(err);
    }
    else {
      resolve(stdout.replace('\n', ''));
    }
  });
});

var gitRepoName = new Promise(function(resolve, reject) {
  exec('git config --get remote.origin.url', function(err, stdout) {
    if(err) {
      reject(err);
    }
    else {
      // @todo: Be more careful with the assumptions about the URL
      var output = stdout
        .replace('\n', '')
        .replace('git@github.com:', '')
        .replace('https://github.com/', '')
        .replace('.git', '');

      resolve(output);
    }
  });
});

/**
 * Get config from file or environment.
 *
 * JSON file is in ~/.shoov.json
 *
 * @param str
 *   The config name.
 * @param defaultValue
 *   The default value.
 * @param bool addPrefix
 *   Determins if the "SHOOV_" prefix should be added to the variable. Defaults
 *   to TRUE.
 *
 *
 * @returns {*}
 */
var getConfig = function(str, defaultValue, addPrefix) {
  // Set config hierarchy.
  var configFile = process.env[(process.platform == 'win32') ? 'USERPROFILE' : 'HOME'] + '/.shoov.json';
  nconf
    .env()
    .file(configFile);

  addPrefix = addPrefix || true;

  var prefix = addPrefix ? 'SHOOV_' : '';

  var upperCase = prefix + str.toUpperCase();
  var confValue = nconf.get(str) || nconf.get(upperCase);
  return confValue || defaultValue;
};

/**
 * Upload the image.
 *
 * @param obj
 */
var uploadFailedImage = function(obj) {
  var accessToken = getConfig('access_token');
  if (!accessToken) {
    throw new Error('The Shoov access token is not defined, visit your account page.');
  }

  var backendUrl = getConfig('backend_url', 'https://dev-shoov.pantheon.io');
  var options = {
    url: backendUrl + '/api/screenshots-upload',
    headers: {
      'access-token': accessToken
    }
  };

  var gitData = {
    gitSubject: gitSubject,
    gitPrefix: gitPrefix,
    gitRepoName: gitRepoName
  };

  var uploadResponse = '';

  Promise.props(gitData)
    .then(function(gitData) {
      var req = request.post(options);
      req
        .on('error', function (err) {
          throw new Error(err);
        })
        .on('data', function(chunk) {
          uploadResponse += chunk;
        })
        .on('end', function() {
          var data = JSON.parse(uploadResponse).data[0];
          // Populate the build ID.
          buildId = buildId || data.build;

          if (getConfig('debug')) {
            // Show response.
            console.log(data);
          }
        })
        .on('response', function(response) {
          if (response.statusCode >= 500) {
            throw new Error('Backend error');
          }
          else if (response.statusCode !== 200) {
            throw new Error('Access token is incorrect or no longer valid, visit your account page');
          }
        });

      var form = req.form();

      var label = path.basename(obj.baselinePath, '.baseline.png').replace('.', ' ');
      form.append('label', label);

      form.append('baseline', fs.createReadStream(obj.baselinePath));
      form.append('regression', fs.createReadStream(obj.regressionPath));
      form.append('diff', fs.createReadStream(obj.diffPath));

      form.append('baseline_name', obj.baselinePath);
      form.append('git_commit', gitCommit);
      form.append('git_branch', gitBranch);
      form.append('git_subject', gitData.gitSubject);

      form.append('directory_prefix', gitData.gitPrefix);
      form.append('repository', gitData.gitRepoName);

      uploads.push(req);
    });

  throw new Error('Found regression in test');
};

var wdcssSetup = {

  /**
   * Init the client.
   */
  before: function(done, caps) {
    client = this.getClient(done, caps);
    WebdriverCSS.init(client);

    return client;
  },

  after: function(done) {
    return Promise
      .all(uploads)
      .then(function() {
        if (uploads.length) {
          var clientUrl = getConfig('client_url', 'https://app.shoov.io');
          var regressionUrl = clientUrl + '/#/screenshots/' + buildId;
          console.log('See regressions in: ' + regressionUrl);

          if (getConfig('open_link')) {
            open(regressionUrl)
          }
        }

        client.end(done);
      });
  },

  processResults: function(err, res) {
    if (err) {
      console.error(err);
    }

    // @todo: Convert to Ramda.
    // Keep only images that were not processed yet.
    var newRes = {};
    Object.keys(res).forEach(function(key) {
      if (processedRes.indexOf(key) == -1) {
        var val = res[key];
        newRes[key] = val;
        processedRes.push(key);
      }
    });

    var isNotWithinMisMatchTolerance = R.filter(R.where({isWithinMisMatchTolerance: false}));
    var uploadImages = R.mapObj(R.forEach(uploadFailedImage));
    var checkImages = R.compose(uploadImages, R.mapObj(isNotWithinMisMatchTolerance));

    checkImages(newRes);
  },

  getUploadedRequests: function() {
    return uploads;
  },

  /**
   * Get client.
   *
   * @param done
   *   Mocha's done callback.
   * @param capsConfig
   *   The capabilities configuration. If empty, default one will be used.
   */
  getClient : function (done, caps) {
    caps = caps || {};

    var capsProvided = !!Object.keys(caps).length;

    // We follow the naming conventions of the username and key, as proivded by
    // the different service providers.
    var sauceUserName = getConfig('sauce_username', false, false);
    var sauceAccessKey = getConfig('sauce_access_key', false, false);

    var browserStackUserName = getConfig('browserstack_username', false, false);
    var browserStackKey = getConfig('browserstack_key', false, false);

    if (sauceUserName && sauceAccessKey) {
      if (!capsProvided) {
        // Set default capabilities.
        caps['browserName'] = 'chrome';
        caps['platform'] = 'Linux';
        caps['version'] = '41.0';
        caps['screenResolution'] = '1024x768';
      }

      client = WebdriverIO.remote({
        desiredCapabilities: caps,
        host: 'ondemand.saucelabs.com',
        port: 80,
        user: sauceUserName,
        key: sauceAccessKey
      });
    }
    else if (browserStackUserName && browserStackKey) {
      if (!capsProvided) {
        // Set default capabilities.
        caps['browser'] = 'Chrome';
        caps['browser_version'] = '39.0';
        caps['os'] = 'OS X';
        caps['os_version'] = 'Yosemite';
        caps['resolution'] = '1024x768';
      }

      caps['browserstack.user'] = browserStackUserName;
      caps['browserstack.key'] = browserStackKey;
      caps['browserstack.debug'] = 'true';

      client = WebdriverIO.remote({
        desiredCapabilities: caps,
        host: 'hub.browserstack.com',
        port: 80
      });
    }
    else {
      client = WebdriverIO.remote({ desiredCapabilities: {browserName: 'phantomjs'} });
    }

    // Init the client.
    client.init(done);

    var width;
    var height;

    if (capsProvided && caps.resolution) {
      var size = caps.resolution.split('x');
      width = parseInt(size[0]);
      height = parseInt(size[1]);
    }

    width = width || 1024;
    height = height || 768;

    client.setViewportSize({
      width: width,
      height: height
    });

    return client;
  }
};

module.exports = wdcssSetup;
<|endoftext|>


<commit_before>var express = require('express'),
    app = express();

app.set('port', (process.env.PORT || 5000));
app.use(express.static(__dirname + '/public'));

app.get('/', function(request, response) {
  response.send('Hello There!')
});

/*
* This is the main function that recieves post commands from Slack.
* They come in this format:
* {
*   "text": "pkmn battle me",
*   "user": "rvinluan",
*   "channel": "#pkmn_battles"
* }
* There's more stuff but that's all we care about.
* All error handling is bubbled up to this function and handled here.
* It doesn't distinguish between different types of errors, but it probably should.
*/
app.post('/commands', function(request, response){
  var commands = request.body.text.toLowerCase().split(" ");

  response.send(buildResponse("Now you're thinking with portals!"));
})

app.listen(app.get('port'), function() {
  console.log("Node app is running at localhost:" + app.get('port'))
})

//utility functions

/*
* Helper function to build the JSON to send back to Slack.
*/
function buildResponse(text) {
  var json = {
    "text": text,
    "username": "Craft Bot"
  }
  return JSON.stringify(json);
}<commit_msg>Get slack communication working<commit_after>var express = require('express'),
    app = express();

app.set('port', (process.env.PORT || 5000));
app.use(express.static(__dirname + '/public'));

app.get('/', function(request, response) {
  response.send('Hello There!')
});

/*
* This is the main function that recieves post commands from Slack.
* They come in this format:
* {
*   "text": "pkmn battle me",
*   "user": "rvinluan",
*   "channel": "#pkmn_battles"
* }
* There's more stuff but that's all we care about.
* All error handling is bubbled up to this function and handled here.
* It doesn't distinguish between different types of errors, but it probably should.
*/
app.post('/commands', function(request, response){
  response.send("Now you're thinking with portals!");
})

app.listen(app.get('port'), function() {
  console.log("Node app is running at localhost:" + app.get('port'))
})

//utility functions

/*
* Helper function to build the JSON to send back to Slack.
*/
function buildResponse(text) {
  var json = {
    "text": text,
    "username": "CraftBot"
  }
  return JSON.stringify(json);
}<|endoftext|>


<commit_before>'use strict';
var spawn = require('child_process').spawn;
var config = require('./config');
var TogglClient = require('toggl-api');
var rimraf = require('rimraf');
var toggl = new TogglClient({apiToken: config.apiKey});
var mo = require('moment');
var entries = {};
var mappings = config.mappings;
var totalDuration = 0;
module.exports = function(callback) {
  toggl.getTimeEntries(mo(1, 'h').format(), mo(19, 'h').format(), function(err, data) {
    if (err) {
      return callback(err);
    }
    var error = false;
    data.forEach(function(n) {
      if (error) {
        return;
      }
      var m = mappings[n.pid];
      if (!m) {
        console.log(n);
        error = new Error('No mapping for activity. Activity text was: ' + n.description);
        return;
      }
      if (!n.tags || !n.tags.length) {
        return callback(new Error('No tag supplied for activity: ' + n.description));
      }
      if (!config.activityMappings[n.tags[0]]) {
        return callback(new Error('No mapping found for toggl tag ' + n.tags[0]));
      }
      var key = '' + m.id + config.activityMappings[n.tags[0]];
      if (!entries[key]) {
        entries[key] = {
          id: m.id,
          name: m.name,
          activity: config.activityMappings[n.tags[0]],
          duration: 0,
          text: '',
          usedText: {}
        };
      }
      if (!entries[key].usedText[n.description]) {
        /* eslint-disable quotes */
        entries[key].text = n.description + "\n" + entries[key].text;
        /* eslint-enable quotes */
        entries[key].usedText[n.description] = true;
      }
      entries[key].duration = entries[key].duration + n.duration;
    });
    Object.keys(entries).forEach(function(n) {
      var item = entries[n];
      entries[n].duration = Number((Math.ceil((item.duration / 3600) * 4) / 4).toFixed(2));
      totalDuration = totalDuration + entries[n].duration;
    });
    if (error) {
      callback(error);
      return;
    }
    // Spawn a process with this as arguments.
    var p = spawn('casperjs', ['casper/poster.js', JSON.stringify({
      entries: entries,
      user: config.texUser,
      pass: config.texPass,
      duration: totalDuration
    })]);
    var output = [];
    p.stdout.on('data', function(data) {
      output.push(data.toString());
    });
    p.stderr.on('data', function(d) {
      output.push('err: ' + d.toString());
    });
    p.on('close', function(c) {
      if (c !== 0) {
        /* eslint-disable quotes */
        process.stderr.write(output.join("\n"));
        callback(new Error('Problematic run detected'));
        /* eslint-enable quotes */
      }
      else {
        rimraf(__dirname + '/shots/*.png', callback);
      }
    });

  });
};
<commit_msg>Remove empty log lines. Pass in baseUrl config to casper.<commit_after>'use strict';
var spawn = require('child_process').spawn;
var config = require('./config');
var TogglClient = require('toggl-api');
var rimraf = require('rimraf');
var toggl = new TogglClient({apiToken: config.apiKey});
var mo = require('moment');
var entries = {};
var mappings = config.mappings;
var totalDuration = 0;
module.exports = function(callback) {
  toggl.getTimeEntries(mo(1, 'h').format(), mo(19, 'h').format(), function(err, data) {
    if (err) {
      return callback(err);
    }
    var error = false;
    data.forEach(function(n) {
      if (error) {
        return;
      }
      var m = mappings[n.pid];
      if (!m) {
        console.log(n);
        error = new Error('No mapping for activity. Activity text was: ' + n.description);
        return;
      }
      if (!n.tags || !n.tags.length) {
        return callback(new Error('No tag supplied for activity: ' + n.description));
      }
      if (!config.activityMappings[n.tags[0]]) {
        return callback(new Error('No mapping found for toggl tag ' + n.tags[0]));
      }
      var key = '' + m.id + config.activityMappings[n.tags[0]];
      if (!entries[key]) {
        entries[key] = {
          id: m.id,
          name: m.name,
          activity: config.activityMappings[n.tags[0]],
          duration: 0,
          text: '',
          usedText: {}
        };
      }
      if (!entries[key].usedText[n.description]) {
        /* eslint-disable quotes */
        entries[key].text = n.description + "\n" + entries[key].text;
        /* eslint-enable quotes */
        entries[key].usedText[n.description] = true;
      }
      entries[key].duration = entries[key].duration + n.duration;
    });
    Object.keys(entries).forEach(function(n) {
      var item = entries[n];
      entries[n].duration = Number((Math.ceil((item.duration / 3600) * 4) / 4).toFixed(2));
      totalDuration = totalDuration + entries[n].duration;
    });
    if (error) {
      callback(error);
      return;
    }
    // Spawn a process with this as arguments.
    var p = spawn('casperjs', ['casper/poster.js', JSON.stringify({
      entries: entries,
      user: config.texUser,
      pass: config.texPass,
      duration: totalDuration,
      baseUrl: config.baseUrl
    })]);
    var output = [];
    p.stdout.on('data', function(data) {
      var stdOutString = data.toString().trim();
      if (!stdOutString || !stdOutString.length) {
        return;
      }
      output.push(stdOutString);
    });
    p.stderr.on('data', function(d) {
      var stdErrString = d.toString().trim();
      if (!stdErrString || !stdErrString.length) {
        return;
      }
      output.push('err: ' + d.toString());
    });
    p.on('close', function(c) {
      if (c !== 0) {
        /* eslint-disable quotes */
        process.stderr.write(output.join("\n"));
        callback(new Error('Problematic run detected'));
        /* eslint-enable quotes */
      }
      else {
        rimraf(__dirname + '/shots/*.png', callback);
      }
    });

  });
};
<|endoftext|>


<commit_before>var _ = require('lodash');
var webpack = require('webpack');
var extend = require('util')._extend;
var os = require('os');
var path = require('path');
var MemoryFS = require('memory-fs');
var fs = new MemoryFS();

var TMP_PATH = os.tmpdir();

var renderer = function(data, options, callback) {

  var userConfig = extend(
    hexo.theme.config.webpack || {},
    hexo.config.webpack || {}
  );

  var cwd = process.cwd();

  //
  // Convert config of the entry to object.
  //
  var entry = (function(entry) {
    if (_.isString(entry)) entry = [entry];
    if (_.isArray(entry)) {
      entry = entry.map(function(x){ return path.join(cwd, x); });
      return _.zipObject(entry.map(function(x){
        return path.basename(x, path.extname(x));
      }), entry);
    }
    return _.mapValues(entry, function(x){ return path.join(cwd, x); });
  })(userConfig.entry);

  //
  // If this file is not a webpack entry simply return the file.
  //
  if (!_.includes(entry, data.path)) {
    return callback(null, data.text);
  }

  //
  // Copy config then extend it with some defaults.
  //
  var config = extend({}, userConfig);

  config = extend(config, {
    entry: entry,
    output: {
      entry: data.path,
      path: TMP_PATH,
      filename: path.basename(data.path)
    }
  });

  //
  // Setup compiler to use in-memory file system then run it.
  //
  var compiler = webpack(config);
  compiler.outputFileSystem = fs;

  compiler.run(function(err, stats) {
    var output = compiler.options.output;
    var outputPath = path.join(output.path, output.filename);

    if (stats.toJson().errors.length > 0) {
      hexo.log.log(stats.toString());
      return callback(stats.toJson().errors, 'Webpack Error.');
    }

    contents = fs.readFileSync(outputPath).toString();
    return callback(null, contents);
  });

};

hexo.extend.renderer.register('js', 'js', renderer);
<commit_msg>Multiple Entries with the same filename fix<commit_after>var _ = require('lodash');
var webpack = require('webpack');
var extend = require('util')._extend;
var os = require('os');
var path = require('path');
var MemoryFS = require('memory-fs');
var fs = new MemoryFS();

var TMP_PATH = os.tmpdir();

var renderer = function(data, options, callback) {

  var userConfig = extend(
    hexo.theme.config.webpack || {},
    hexo.config.webpack || {}
  );

  var cwd = process.cwd();

  //
  // Convert config of the entry to object.
  //
  var entry = (function(entry) {
    if (_.isString(entry)) entry = [entry];
    if (_.isArray(entry)) {
      entry = entry.map(function(x){ return path.join(cwd, x); });
      return _.zipObject(entry, entry);
    }
    return _.mapValues(entry, function(x){ return path.join(cwd, x); });
  })(userConfig.entry);

  //
  // If this file is not a webpack entry simply return the file.
  //
  if (!_.includes(entry, data.path)) {
    return callback(null, data.text);
  }

  //
  // Copy config then extend it with some defaults.
  //
  var config = extend({}, userConfig);

  config = extend(config, {
    entry: entry,
    output: {
      entry: data.path,
      path: TMP_PATH,
      filename: path.basename(data.path)
    }
  });

  //
  // Setup compiler to use in-memory file system then run it.
  //
  var compiler = webpack(config);
  compiler.outputFileSystem = fs;

  compiler.run(function(err, stats) {
    var output = compiler.options.output;
    var outputPath = path.join(output.path, output.filename);

    if (stats.toJson().errors.length > 0) {
      hexo.log.log(stats.toString());
      return callback(stats.toJson().errors, 'Webpack Error.');
    }

    contents = fs.readFileSync(outputPath).toString();
    return callback(null, contents);
  });

};

hexo.extend.renderer.register('js', 'js', renderer);
<|endoftext|>


<commit_before>/**
 * fis.baidu.com
 */

var ts = require('typescript');
var util = require('util');

var ModuleKind = ts.ModuleKind;
var JsxEmit = ts.JsxEmit;
var ScriptTarget = ts.ScriptTarget;

function transpileModule(content, transpileOptions, file) {
  var options = transpileOptions.compilerOptions;

  options.isolatedModules = true;
  options.allowNonTsExtensions = true;
  options.noLib = true;
  options.noResolve = true;

  var newLine = ts.getNewLineCharacter(options);
  var inputFileName = file.isJsXLike ? file.realpath.replace(/\.[^\.]+$/, '.tsx') : file.realpath.replace(/\.jsx$/, '.tsx');
  var sourceFile = ts.createSourceFile(inputFileName, content, options.target);
  var sourceMapText, outputText;

  if (file.isMod) {
    sourceFile.moduleName = file.moduleId || file.id;
  }

  var compilerHost = {
    getSourceFile: function (fileName) {
      if (fileName === ts.normalizeSlashes(inputFileName)) {
        return sourceFile;
      }

      var info = fis.uri(fileName, file.dirname);

      if (info.file) {
        var f = info.file;
        var sf = ts.createSourceFile(f.isJsXLike ? f.realpath.replace(/\.[^\.]+$/, '.tsx') : f.realpath.replace(/\.jsx$/, '.tsx'), f.getContent(), options.target);

        if (f.isMod) {
          sf.moduleName = f.moduleId || f.id;
        }

        return sf;
      }

      return undefined;
    },
    writeFile: function (name, text, writeByteOrderMark) {
      if (ts.fileExtensionIs(name, ".map")) {
        ts.Debug.assert(sourceMapText === undefined, "Unexpected multiple source map outputs for the file '" + name + "'");
        sourceMapText = text;
      }
      else {
        ts.Debug.assert(outputText === undefined, "Unexpected multiple outputs for the file: " + name);
        outputText = text;
      }
    },
    getDefaultLibFileName: function () { return "lib.d.ts"; },
    useCaseSensitiveFileNames: function () { return false; },
    getCanonicalFileName: function (fileName) { return fileName; },
    getCurrentDirectory: function () { return ""; },
    getNewLine: function () { return newLine; },
    fileExists: function (fileName) {
      return fis.util.exists(fileName);
    },
    readFile: function (fileName) { return ""; }
  };

  var program = ts.createProgram([inputFileName], options, compilerHost);
  var diagnostics;
  var noticeDiagnostics;

  if (transpileOptions.reportDiagnostics) {
      diagnostics = [];
      ts.addRange(diagnostics, program.getSyntacticDiagnostics(sourceFile));
      ts.addRange(diagnostics, program.getOptionsDiagnostics());

      noticeDiagnostics = [];
      ts.addRange(noticeDiagnostics, program.getSemanticDiagnostics(sourceFile));
  }

  program.emit();

  return {
    outputText: outputText,
    diagnostics: diagnostics,
    noticeDiagnostics: noticeDiagnostics,
    sourceMapText: sourceMapText
  };
}

module.exports = function (content, file, opts) {

  // 用 html 语言处理一遍。
  if (fis.compile.partial && file.ext === '.tsx' || file.ext === '.jsx' || file.isJsXLike) {
    content = fis.compile.partial(content, file, {
      ext: '.html',
      isHtmlLike: true
    });
  }

  var conf = fis.util.clone(opts);

  if (!conf.sourceMap) {
    conf.inlineSources = false;
  }

  var result = transpileModule(content, {
    compilerOptions: conf,
    fileName: file.realpath,
    reportDiagnostics: true,
    moduleName: undefined
  }, file);

  result.diagnostics.forEach(function(e) {
    if(!e.file){
        return;
    }
    let { line, character } = e.file.getLineAndCharacterOfPosition(e.start);
    let message = ts.flattenDiagnosticMessageText(e.messageText, '\n');
    var msg = util.format('Syntax Error: %s in [%s:%s]', message, line+1, character+1);
    throw new Error(msg);
  });
  result.noticeDiagnostics.forEach((e)=>{
    if(!e.file){
        return;
    }
    let { line, character } = e.file.getLineAndCharacterOfPosition(e.start);
    let message = ts.flattenDiagnosticMessageText(e.messageText, '\n');
    var msg = util.format('Notice Syntax Error: %s in [%s:%s]', message, line+1, character+1);
    console.log(msg);
  });

  if (result.sourceMapText) {
    var mapping = fis.file.wrap(file.dirname + '/' + file.filename + file.rExt + '.map');

    // 修改 source 文件名。
    var sourceMapObj = JSON.parse(result.sourceMapText);
    sourceMapObj.sources = [file.subpath];
    result.sourceMapText = JSON.stringify(sourceMapObj, null, 4);

    mapping.setContent(result.sourceMapText);
    var url = mapping.getUrl(fis.compile.settings.hash, fis.compile.settings.domain);

    result.outputText = result.outputText.replace(/\n?\s*\/\/#\ssourceMappingURL=.*?(?:\n|$)/g, '');
    result.outputText += '\n//# sourceMappingURL=' +  url + '\n';

    file.extras = file.extras || {};
    file.extras.derived = file.extras.derived || [];
    file.extras.derived.push(mapping);
  }

  return result.outputText || '';
};

module.exports.defaultOptions = {
  // 1: JsxEmit.Preserve
  // 2: JsxEmit.React
  jsx: JsxEmit.React,

  // 1: ModuleKind.CommonJS
  // 2: ModuleKind.AMD
  // 3: ModuleKind.UMD
  // 4: ModuleKind.System
  module: ModuleKind.CommonJS,

  // 0: ScriptTarget.ES3
  // 1: ScriptTarget.ES5
  // 2: ScriptTarget.ES6
  target: ScriptTarget.ES5,
  noImplicitAny: false,
  outDir: "built",
  rootDir: fis.project.getProjectPath(),
  sourceMap: false,
  inlineSources: true,
  emitDecoratorMetadata: true,
  experimentalDecorators: true
};
<commit_msg>修改es6语法，兼容node 0.x版本<commit_after>/**
 * fis.baidu.com
 */

var ts = require('typescript');
var util = require('util');

var ModuleKind = ts.ModuleKind;
var JsxEmit = ts.JsxEmit;
var ScriptTarget = ts.ScriptTarget;

function transpileModule(content, transpileOptions, file) {
  var options = transpileOptions.compilerOptions;

  options.isolatedModules = true;
  options.allowNonTsExtensions = true;
  options.noLib = true;
  options.noResolve = true;

  var newLine = ts.getNewLineCharacter(options);
  var inputFileName = file.isJsXLike ? file.realpath.replace(/\.[^\.]+$/, '.tsx') : file.realpath.replace(/\.jsx$/, '.tsx');
  var sourceFile = ts.createSourceFile(inputFileName, content, options.target);
  var sourceMapText, outputText;

  if (file.isMod) {
    sourceFile.moduleName = file.moduleId || file.id;
  }

  var compilerHost = {
    getSourceFile: function (fileName) {
      if (fileName === ts.normalizeSlashes(inputFileName)) {
        return sourceFile;
      }

      var info = fis.uri(fileName, file.dirname);

      if (info.file) {
        var f = info.file;
        var sf = ts.createSourceFile(f.isJsXLike ? f.realpath.replace(/\.[^\.]+$/, '.tsx') : f.realpath.replace(/\.jsx$/, '.tsx'), f.getContent(), options.target);

        if (f.isMod) {
          sf.moduleName = f.moduleId || f.id;
        }

        return sf;
      }

      return undefined;
    },
    writeFile: function (name, text, writeByteOrderMark) {
      if (ts.fileExtensionIs(name, ".map")) {
        ts.Debug.assert(sourceMapText === undefined, "Unexpected multiple source map outputs for the file '" + name + "'");
        sourceMapText = text;
      }
      else {
        ts.Debug.assert(outputText === undefined, "Unexpected multiple outputs for the file: " + name);
        outputText = text;
      }
    },
    getDefaultLibFileName: function () { return "lib.d.ts"; },
    useCaseSensitiveFileNames: function () { return false; },
    getCanonicalFileName: function (fileName) { return fileName; },
    getCurrentDirectory: function () { return ""; },
    getNewLine: function () { return newLine; },
    fileExists: function (fileName) {
      return fis.util.exists(fileName);
    },
    readFile: function (fileName) { return ""; }
  };

  var program = ts.createProgram([inputFileName], options, compilerHost);
  var diagnostics;
  var noticeDiagnostics;

  if (transpileOptions.reportDiagnostics) {
      diagnostics = [];
      ts.addRange(diagnostics, program.getSyntacticDiagnostics(sourceFile));
      ts.addRange(diagnostics, program.getOptionsDiagnostics());

      noticeDiagnostics = [];
      ts.addRange(noticeDiagnostics, program.getSemanticDiagnostics(sourceFile));
  }

  program.emit();

  return {
    outputText: outputText,
    diagnostics: diagnostics,
    noticeDiagnostics: noticeDiagnostics,
    sourceMapText: sourceMapText
  };
}

module.exports = function (content, file, opts) {

  // 用 html 语言处理一遍。
  if (fis.compile.partial && file.ext === '.tsx' || file.ext === '.jsx' || file.isJsXLike) {
    content = fis.compile.partial(content, file, {
      ext: '.html',
      isHtmlLike: true
    });
  }

  var conf = fis.util.clone(opts);

  if (!conf.sourceMap) {
    conf.inlineSources = false;
  }

  var result = transpileModule(content, {
    compilerOptions: conf,
    fileName: file.realpath,
    reportDiagnostics: true,
    moduleName: undefined
  }, file);

  result.diagnostics.forEach(function(e) {
    if(!e.file){
        return;
    }
    var lineAndCharacterObj = e.file.getLineAndCharacterOfPosition(e.start);
    var line = lineAndCharacterObj.line;
    var character = lineAndCharacterObj.character;
    var message = ts.flattenDiagnosticMessageText(e.messageText, '\n');
    var msg = util.format('Syntax Error: %s in [%s:%s]', message, line+1, character+1);
    throw new Error(msg);
  });
  result.noticeDiagnostics.forEach(function(e) {
    if(!e.file){
        return;
    }
    var lineAndCharacterObj = e.file.getLineAndCharacterOfPosition(e.start);
    var line = lineAndCharacterObj.line;
    var character = lineAndCharacterObj.character;
    var message = ts.flattenDiagnosticMessageText(e.messageText, '\n');
    var msg = util.format('Notice Syntax Error: %s in [%s:%s]', message, line+1, character+1);
    console.log(msg);
  });

  if (result.sourceMapText) {
    var mapping = fis.file.wrap(file.dirname + '/' + file.filename + file.rExt + '.map');

    // 修改 source 文件名。
    var sourceMapObj = JSON.parse(result.sourceMapText);
    sourceMapObj.sources = [file.subpath];
    result.sourceMapText = JSON.stringify(sourceMapObj, null, 4);

    mapping.setContent(result.sourceMapText);
    var url = mapping.getUrl(fis.compile.settings.hash, fis.compile.settings.domain);

    result.outputText = result.outputText.replace(/\n?\s*\/\/#\ssourceMappingURL=.*?(?:\n|$)/g, '');
    result.outputText += '\n//# sourceMappingURL=' +  url + '\n';

    file.extras = file.extras || {};
    file.extras.derived = file.extras.derived || [];
    file.extras.derived.push(mapping);
  }

  return result.outputText || '';
};

module.exports.defaultOptions = {
  // 1: JsxEmit.Preserve
  // 2: JsxEmit.React
  jsx: JsxEmit.React,

  // 1: ModuleKind.CommonJS
  // 2: ModuleKind.AMD
  // 3: ModuleKind.UMD
  // 4: ModuleKind.System
  module: ModuleKind.CommonJS,

  // 0: ScriptTarget.ES3
  // 1: ScriptTarget.ES5
  // 2: ScriptTarget.ES6
  target: ScriptTarget.ES5,
  noImplicitAny: false,
  outDir: "built",
  rootDir: fis.project.getProjectPath(),
  sourceMap: false,
  inlineSources: true,
  emitDecoratorMetadata: true,
  experimentalDecorators: true
};
<|endoftext|>


<commit_before>
(function (root, factory) {

  'use strict';

  if (typeof define === 'function' && define.amd) {
    // AMD. Register as an anonymous module.
    define([], factory);
  } else if (typeof exports === 'object') {
    // Node. Does not work with strict CommonJS, but
    // only CommonJS-like environments that support module.exports,
    // like Node.
    module.exports = factory();
  } else {
    // Browser globals (root is window)
    root.returnExports = factory();
  }

}(this, function () {

  var library = {};

  /* jshint ignore:start */

  (function(target) {

    var undef;

    function isFunction(f) {
      return typeof f == 'function';
    }
    function isObject(f) {
      return typeof f == 'object';
    }
    function defer(callback) {
      if (typeof process != 'undefined' && process['nextTick'])
        process['nextTick'](callback);
      else
        setTimeout(callback, 0);
    }

    target[0][target[1]] = function pinkySwear(extend) {
      var state;           // undefined/null = pending, true = fulfilled, false = rejected
      var values = [];     // an array of values as arguments for the then() handlers
      var deferred = [];   // functions to call when set() is invoked

      var set = function(newState, newValues) {
        if (state == null && newState != null) {
          state = newState;
          values = newValues;
          if (deferred.length)
            defer(function() {
              for (var i = 0; i < deferred.length; i++)
                deferred[i]();
            });
        }
        return state;
      };

      set['then'] = function (onFulfilled, onRejected) {
        var promise2 = pinkySwear(extend);
        var callCallbacks = function() {
            try {
              var f = (state ? onFulfilled : onRejected);
              if (isFunction(f)) {
                function resolve(x) {
                  var then, cbCalled = 0;
                  try {
                    if (x && (isObject(x) || isFunction(x)) && isFunction(then = x['then'])) {
                      if (x === promise2)
                        throw new TypeError();
                      then['call'](x,
                        function() { if (!cbCalled++) resolve.apply(undef,arguments); } ,
                        function(value){ if (!cbCalled++) promise2(false,[value]);});
                    }
                    else
                      promise2(true, arguments);
                  }
                  catch(e) {
                    if (!cbCalled++)
                      promise2(false, [e]);
                  }
                }
                resolve(f.apply(undef, values || []));
              }
              else
                promise2(state, values);
          }
          catch (e) {
            promise2(false, [e]);
          }
        };
        if (state != null)
          defer(callCallbacks);
        else
          deferred.push(callCallbacks);
        return promise2;
      };
          if(extend){
              set = extend(set);
          }
      return set;
    };
  })([library, 'pinkySwear']);
  /* jshint ignore:end */

  var nextTick = function(fn) {

    if (process && process.nextTick) {
      process.nextTick(fn);
    } else {
      setTimeout(fn, 0);
    }

  };

  var handleError = function(promise, onComplete) {

    return function(err) {

      if (onComplete && typeof onComplete === 'function') {

        nextTick(function() {
          onComplete(err);
          promise(err === null, err ? [err] : undefined);
        });

      } else {
        promise(err === null, err ? [err] : undefined);
      }

    };

  };

  var pinkySwear = library.pinkySwear;

  /**
   * Fireproofs an existing Firebase reference, giving it magic promise powers.
   * @name Fireproof
   * @constructor
   * @param {Firebase} firebaseRef A Firebase reference object.
   * @property then A promise shortcut for .once('value'),
   * except for references created by .push(), where it resolves on success
   * and rejects on failure of the property object.
   * @example
   * var fp = new Fireproof(new Firebase('https://test.firebaseio.com/something'));
   * fp.then(function(snap) { console.log(snap.val()); });
   */
  function Fireproof(firebaseRef, promise) {

    this._ref = firebaseRef;
    if (promise && promise.then) {
      this.then = promise.then.bind(promise);
    } else {

      this.then = function(ok, fail) {

        return this.once('value', function() {})
        .then(ok || null, fail || null);

      };

    }

  }

  /* FIXME(goldibex): Find out the reason for this demonry.
   * For reasons completely incomprehensible to me, some type of race condition
   * is possible if multiple Fireproof references attempt authentication at the
   * same time, the result of which is one or more of the promises will never
   * resolve.
   * Accordingly, it is necessary that we wrap authentication actions in a
   * global lock. This is accomplished using setInterval. No, I don't like it
   * any more than you do.
   */
  var authing = false;

  /**
   * Delegates Firebase#auth.
   * @method Fireproof#auth
   * @param {string} authToken Firebase authentication token.
   * @param {function=} onComplete Callback on initial completion.
   * @param {function=} onCancel Callback if we ever get disconnected.
   * @returns {Promise} Resolves on success, rejects on failure.
   */
  Fireproof.prototype.auth = function(authToken, onComplete, onCancel) {

    var promise = pinkySwear(),
      self = this;

    var authIntervalId = setInterval(function() {

      if (!authing) {

        authing = true;
        self._ref.auth(authToken, function(err, info) {

          authing = false;
          clearInterval(authIntervalId);
          if (err !== null) {
            promise(false, [err]);
          } else {
            promise(true, [info]);
          }

          if (typeof onComplete === 'function') {
            nextTick(function() {
              onComplete(err, info);
            });
          }

        }, onCancel);

      }

    }, 1);

    return promise;

  };

  /**
   * Delegates Firebase#unauth.
   * @method Fireproof#unauth
   */
  Fireproof.prototype.unauth = function() {
    this._ref.unauth();
  };

  /**
   * Delegates Firebase#child, wrapping the child in fireproofing.
   * @method Fireproof#child
   * @param {string} childPath The subpath to refer to.
   * @returns {Fireproof} A reference to the child path.
   */
  Fireproof.prototype.child = function(childPath) {
    return new Fireproof(this._ref.child(childPath));
  };

  /**
   * Delegates Firebase#parent.
   * @method Fireproof#parent
   * @returns {Fireproof} A ref to the parent path, or null if there is none.
   */
  Fireproof.prototype.parent = function() {

    if (this._ref.parent() === null) {
      return null;
    } else {
      return new Fireproof(this._ref.parent());
    }

  };

  /**
   * Delegates Firebase#root.
   * @method Fireproof#root
   * @returns {Fireproof} A ref to the root.
   */
  Fireproof.prototype.root = function() {
    return new Fireproof(this._ref.root());
  };

  /**
   * Delegates Firebase#name.
   * @method Fireproof#name
   * @returns {string} The last component of this reference object's path.
   */
  Fireproof.prototype.name = function() {
    return this._ref.name();
  };

  /**
   * Delegates Firebase#toString.
   * @method Fireproof#toString
   * @returns {string} The full URL of this reference object.
   */
  Fireproof.prototype.toString = function() {
    return this._ref.toString();
  };

  /**
   * Delegates Firebase#set.
   * @method Fireproof#set
   * @param {object} value The value to set this path to.
   * @param {function=} onComplete Callback when the operation is done.
   * @returns {Promise} Resolves on success, rejects on failure.
   * @example
   * fireproofRef.set('something')
   * .then(function()) {
   *   console.log('set was successful!');
   * }, function(err) {
   *   console.error('error while setting:', err);
   * });
   */
  Fireproof.prototype.set = function(value, onComplete) {

    var promise = pinkySwear();

    this._ref.set(value, handleError(promise, onComplete));

    return promise;

  };

  /**
   * Delegates Firebase#update.
   * @method Fireproof#update
   * @param {object} value An object with keys and values to update.
   * @param {function=} onComplete Callback when the operation is done.
   * @returns {Promise} Resolves on success, rejects on failure.
   */
  Fireproof.prototype.update = function(value, onComplete) {

    var promise = pinkySwear();

    this._ref.update(value, handleError(promise, onComplete));

    return promise;

  };

  /**
   * Delegates Firebase#remove.
   * @method Fireproof#remove
   * @param {function=} onComplete Callback when the operation is done.
   * @returns {Promise} Resolves on success, rejects on failure.
   */
  Fireproof.prototype.remove = function(onComplete) {

    var promise = pinkySwear();

    this._ref.remove(handleError(promise, onComplete));

    return promise;

  };

  /**
   * Delegates Firebase#push.
   * @method Fireproof#push
   * @param {object} value An object with keys and values to update.
   * @param {function=} onComplete Callback when the operation is done.
   * @returns {Promise} Resolves on success, rejects on failure.
   */
  Fireproof.prototype.push = function(value, onComplete) {

    var promise = pinkySwear();

    var rv = new Fireproof(
      this._ref.push(value, handleError(promise, onComplete)),
      promise
    );

    return rv;

  };

  /**
   * Delegates Firebase#setWithPriority.
   * @method Fireproof#setWithPriority
   * @param {object} value The value to set this path to.
   * @param {object} priority The priority to set this path to.
   * @param {function=} onComplete Callback when the operation is done.
   * @returns {Promise} Resolves on success, rejects on failure.
   */
  Fireproof.prototype.setWithPriority = function(value, priority, onComplete) {

    var promise = pinkySwear();

    this._ref.setWithPriority(value, priority, handleError(promise, onComplete));

    return promise;

  };

  /**
   * Delegates Firebase#setPriority.
   * @method Fireproof#setPriority
   * @param {object} priority The priority to set this path to.
   * @param {function=} onComplete Callback when the operation is done.
   * @returns {Promise} Resolves on success, rejects on failure.
   */
  Fireproof.prototype.setPriority = function(priority, onComplete) {

    var promise = pinkySwear();

    this._ref.setPriority(priority, handleError(promise, onComplete));

    return promise;

  };

  /**
   * Delegates Firebase#transaction.
   * @method Fireproof#transaction
   * @param {function} updateFunction
   * @param {function} onComplete
   * @param {boolean=} applyLocally
   * @returns {Promise} Resolves on success, rejects on failure.
   */
  Fireproof.prototype.transaction = function(updateFunction, onComplete, applyLocally) {

    var promise = pinkySwear();

    this._ref.transaction(updateFunction, function(err, committed, snap) {

      nextTick(function() {
        onComplete(err, committed, snap);

        if (err) {
          promise(false, [err]);
        } else {
          promise(true, [committed, snap]);
        }

      });

    }, applyLocally);

    return promise;

  };

  /**
   * Delegates Firebase#on.
   * @method Fireproof#on
   * @param {string} eventType
   * @param {function} callback
   * @param {function=} cancelCallback
   * @param {object=} context
   * @returns {function} Your callback parameter wrapped in fireproofing. Use
   * this return value, not your own copy of callback, to call .off(). It also
   * functions as a promise that resolves on success and rejects on failure.
   */
  Fireproof.prototype.on = function(eventType, callback, cancelCallback, context) {

    var promise = pinkySwear();

    if (typeof callback !== 'function') {
      callback = function() {};
    }

    if (typeof cancelCallback !== 'function') {
      cancelCallback = function() {};
    }

    var callbackHandler = function(snap, prev) {

      nextTick(function() {
        callback(snap, prev);
        promise(true, [snap, prev]);
      });

    }.bind(this);

    callbackHandler.then = promise.then.bind(promise);

    this._ref.on(eventType, callbackHandler, function(err) {

      nextTick(function() {
        cancelCallback(err);
        promise(false, [err]);
      });

    }, context);

    return callbackHandler;

  };

  /**
   * Delegates Firebase#off.
   * @method Fireproof#off
   * @param {string} eventType
   * @param {function=} callback
   * @param {object=} context
   */
  Fireproof.prototype.off = function(eventType, callback, context) {

    this._ref.off(eventType, callback, context);

  };

  /**
   * Delegates Firebase#once.
   * @method Fireproof#once
   * @param {object} eventType
   * @param {function} successCallback
   * @param {function=} failureCallback
   * @param {object=} context
   * @returns {Promise} Resolves on success and rejects on failure.
   */
  Fireproof.prototype.once = function(eventType, successCallback, failureCallback, context) {

    var promise = pinkySwear();

    if (typeof successCallback !== 'function') {
      successCallback = function() {};
    }

    if (typeof failureCallback !== 'function') {
      failureCallback = function() {};
    }

    this._ref.once(eventType, function(snap) {

      promise(true, [snap]);
      nextTick(function() {
        successCallback(snap);
      });

    }, function(err) {

      promise(false, [err]);
      nextTick(function() {
        failureCallback(err);
      });

    }, context);

    return promise;

  };

  /**
   * Delegates Firebase#limit.
   * @method Fireproof#limit
   * @param {Number} limit
   * @returns {Fireproof}
   */
  Fireproof.prototype.limit = function(limit) {
    return new Fireproof(this._ref.limit(limit));
  };

  /**
   * Delegates Firebase#startAt.
   * @method Fireproof#startAt
   * @param {object} priority
   * @param {string} name
   * @returns {Fireproof}
   */
  Fireproof.prototype.startAt = function(priority, name) {
    return new Fireproof(this._ref.startAt(priority, name));
  };

  /**
   * Delegates Firebase#endAt.
   * @method Fireproof#endAt
   * @param {object} priority
   * @param {string} name
   * @returns {Fireproof}
   */
  Fireproof.prototype.endAt = function(priority, name) {
    return new Fireproof(this._ref.endAt(priority, name));
  };

  /**
   * Delegates Firebase#equalTo.
   * @method Fireproof#equalTo
   * @param {object} priority
   * @param {string} name
   * @returns {Fireproof}
   */
  Fireproof.prototype.equalTo = function(priority, name) {
    return new Fireproof(this._ref.equalTo(priority, name));
  };

  /**
   * Delegates Firebase#ref.
   * @method Fireproof#ref
   * @returns {Fireproof}
   */
  Fireproof.prototype.ref = function() {
    return new Fireproof(this._ref());
  };

  return Fireproof;

}));
<commit_msg>Fixed ref<commit_after>
(function (root, factory) {

  'use strict';

  if (typeof define === 'function' && define.amd) {
    // AMD. Register as an anonymous module.
    define([], factory);
  } else if (typeof exports === 'object') {
    // Node. Does not work with strict CommonJS, but
    // only CommonJS-like environments that support module.exports,
    // like Node.
    module.exports = factory();
  } else {
    // Browser globals (root is window)
    root.returnExports = factory();
  }

}(this, function () {

  var library = {};

  /* jshint ignore:start */

  (function(target) {

    var undef;

    function isFunction(f) {
      return typeof f == 'function';
    }
    function isObject(f) {
      return typeof f == 'object';
    }
    function defer(callback) {
      if (typeof process != 'undefined' && process['nextTick'])
        process['nextTick'](callback);
      else
        setTimeout(callback, 0);
    }

    target[0][target[1]] = function pinkySwear(extend) {
      var state;           // undefined/null = pending, true = fulfilled, false = rejected
      var values = [];     // an array of values as arguments for the then() handlers
      var deferred = [];   // functions to call when set() is invoked

      var set = function(newState, newValues) {
        if (state == null && newState != null) {
          state = newState;
          values = newValues;
          if (deferred.length)
            defer(function() {
              for (var i = 0; i < deferred.length; i++)
                deferred[i]();
            });
        }
        return state;
      };

      set['then'] = function (onFulfilled, onRejected) {
        var promise2 = pinkySwear(extend);
        var callCallbacks = function() {
            try {
              var f = (state ? onFulfilled : onRejected);
              if (isFunction(f)) {
                function resolve(x) {
                  var then, cbCalled = 0;
                  try {
                    if (x && (isObject(x) || isFunction(x)) && isFunction(then = x['then'])) {
                      if (x === promise2)
                        throw new TypeError();
                      then['call'](x,
                        function() { if (!cbCalled++) resolve.apply(undef,arguments); } ,
                        function(value){ if (!cbCalled++) promise2(false,[value]);});
                    }
                    else
                      promise2(true, arguments);
                  }
                  catch(e) {
                    if (!cbCalled++)
                      promise2(false, [e]);
                  }
                }
                resolve(f.apply(undef, values || []));
              }
              else
                promise2(state, values);
          }
          catch (e) {
            promise2(false, [e]);
          }
        };
        if (state != null)
          defer(callCallbacks);
        else
          deferred.push(callCallbacks);
        return promise2;
      };
          if(extend){
              set = extend(set);
          }
      return set;
    };
  })([library, 'pinkySwear']);
  /* jshint ignore:end */

  var nextTick = function(fn) {

    if (process && process.nextTick) {
      process.nextTick(fn);
    } else {
      setTimeout(fn, 0);
    }

  };

  var handleError = function(promise, onComplete) {

    return function(err) {

      if (onComplete && typeof onComplete === 'function') {

        nextTick(function() {
          onComplete(err);
          promise(err === null, err ? [err] : undefined);
        });

      } else {
        promise(err === null, err ? [err] : undefined);
      }

    };

  };

  var pinkySwear = library.pinkySwear;

  /**
   * Fireproofs an existing Firebase reference, giving it magic promise powers.
   * @name Fireproof
   * @constructor
   * @param {Firebase} firebaseRef A Firebase reference object.
   * @property then A promise shortcut for .once('value'),
   * except for references created by .push(), where it resolves on success
   * and rejects on failure of the property object.
   * @example
   * var fp = new Fireproof(new Firebase('https://test.firebaseio.com/something'));
   * fp.then(function(snap) { console.log(snap.val()); });
   */
  function Fireproof(firebaseRef, promise) {

    this._ref = firebaseRef;
    if (promise && promise.then) {
      this.then = promise.then.bind(promise);
    } else {

      this.then = function(ok, fail) {

        return this.once('value', function() {})
        .then(ok || null, fail || null);

      };

    }

  }

  /* FIXME(goldibex): Find out the reason for this demonry.
   * For reasons completely incomprehensible to me, some type of race condition
   * is possible if multiple Fireproof references attempt authentication at the
   * same time, the result of which is one or more of the promises will never
   * resolve.
   * Accordingly, it is necessary that we wrap authentication actions in a
   * global lock. This is accomplished using setInterval. No, I don't like it
   * any more than you do.
   */
  var authing = false;

  /**
   * Delegates Firebase#auth.
   * @method Fireproof#auth
   * @param {string} authToken Firebase authentication token.
   * @param {function=} onComplete Callback on initial completion.
   * @param {function=} onCancel Callback if we ever get disconnected.
   * @returns {Promise} Resolves on success, rejects on failure.
   */
  Fireproof.prototype.auth = function(authToken, onComplete, onCancel) {

    var promise = pinkySwear(),
      self = this;

    var authIntervalId = setInterval(function() {

      if (!authing) {

        authing = true;
        self._ref.auth(authToken, function(err, info) {

          authing = false;
          clearInterval(authIntervalId);
          if (err !== null) {
            promise(false, [err]);
          } else {
            promise(true, [info]);
          }

          if (typeof onComplete === 'function') {
            nextTick(function() {
              onComplete(err, info);
            });
          }

        }, onCancel);

      }

    }, 1);

    return promise;

  };

  /**
   * Delegates Firebase#unauth.
   * @method Fireproof#unauth
   */
  Fireproof.prototype.unauth = function() {
    this._ref.unauth();
  };

  /**
   * Delegates Firebase#child, wrapping the child in fireproofing.
   * @method Fireproof#child
   * @param {string} childPath The subpath to refer to.
   * @returns {Fireproof} A reference to the child path.
   */
  Fireproof.prototype.child = function(childPath) {
    return new Fireproof(this._ref.child(childPath));
  };

  /**
   * Delegates Firebase#parent.
   * @method Fireproof#parent
   * @returns {Fireproof} A ref to the parent path, or null if there is none.
   */
  Fireproof.prototype.parent = function() {

    if (this._ref.parent() === null) {
      return null;
    } else {
      return new Fireproof(this._ref.parent());
    }

  };

  /**
   * Delegates Firebase#root.
   * @method Fireproof#root
   * @returns {Fireproof} A ref to the root.
   */
  Fireproof.prototype.root = function() {
    return new Fireproof(this._ref.root());
  };

  /**
   * Delegates Firebase#name.
   * @method Fireproof#name
   * @returns {string} The last component of this reference object's path.
   */
  Fireproof.prototype.name = function() {
    return this._ref.name();
  };

  /**
   * Delegates Firebase#toString.
   * @method Fireproof#toString
   * @returns {string} The full URL of this reference object.
   */
  Fireproof.prototype.toString = function() {
    return this._ref.toString();
  };

  /**
   * Delegates Firebase#set.
   * @method Fireproof#set
   * @param {object} value The value to set this path to.
   * @param {function=} onComplete Callback when the operation is done.
   * @returns {Promise} Resolves on success, rejects on failure.
   * @example
   * fireproofRef.set('something')
   * .then(function()) {
   *   console.log('set was successful!');
   * }, function(err) {
   *   console.error('error while setting:', err);
   * });
   */
  Fireproof.prototype.set = function(value, onComplete) {

    var promise = pinkySwear();

    this._ref.set(value, handleError(promise, onComplete));

    return promise;

  };

  /**
   * Delegates Firebase#update.
   * @method Fireproof#update
   * @param {object} value An object with keys and values to update.
   * @param {function=} onComplete Callback when the operation is done.
   * @returns {Promise} Resolves on success, rejects on failure.
   */
  Fireproof.prototype.update = function(value, onComplete) {

    var promise = pinkySwear();

    this._ref.update(value, handleError(promise, onComplete));

    return promise;

  };

  /**
   * Delegates Firebase#remove.
   * @method Fireproof#remove
   * @param {function=} onComplete Callback when the operation is done.
   * @returns {Promise} Resolves on success, rejects on failure.
   */
  Fireproof.prototype.remove = function(onComplete) {

    var promise = pinkySwear();

    this._ref.remove(handleError(promise, onComplete));

    return promise;

  };

  /**
   * Delegates Firebase#push.
   * @method Fireproof#push
   * @param {object} value An object with keys and values to update.
   * @param {function=} onComplete Callback when the operation is done.
   * @returns {Promise} Resolves on success, rejects on failure.
   */
  Fireproof.prototype.push = function(value, onComplete) {

    var promise = pinkySwear();

    var rv = new Fireproof(
      this._ref.push(value, handleError(promise, onComplete)),
      promise
    );

    return rv;

  };

  /**
   * Delegates Firebase#setWithPriority.
   * @method Fireproof#setWithPriority
   * @param {object} value The value to set this path to.
   * @param {object} priority The priority to set this path to.
   * @param {function=} onComplete Callback when the operation is done.
   * @returns {Promise} Resolves on success, rejects on failure.
   */
  Fireproof.prototype.setWithPriority = function(value, priority, onComplete) {

    var promise = pinkySwear();

    this._ref.setWithPriority(value, priority, handleError(promise, onComplete));

    return promise;

  };

  /**
   * Delegates Firebase#setPriority.
   * @method Fireproof#setPriority
   * @param {object} priority The priority to set this path to.
   * @param {function=} onComplete Callback when the operation is done.
   * @returns {Promise} Resolves on success, rejects on failure.
   */
  Fireproof.prototype.setPriority = function(priority, onComplete) {

    var promise = pinkySwear();

    this._ref.setPriority(priority, handleError(promise, onComplete));

    return promise;

  };

  /**
   * Delegates Firebase#transaction.
   * @method Fireproof#transaction
   * @param {function} updateFunction
   * @param {function} onComplete
   * @param {boolean=} applyLocally
   * @returns {Promise} Resolves on success, rejects on failure.
   */
  Fireproof.prototype.transaction = function(updateFunction, onComplete, applyLocally) {

    var promise = pinkySwear();

    this._ref.transaction(updateFunction, function(err, committed, snap) {

      nextTick(function() {
        onComplete(err, committed, snap);

        if (err) {
          promise(false, [err]);
        } else {
          promise(true, [committed, snap]);
        }

      });

    }, applyLocally);

    return promise;

  };

  /**
   * Delegates Firebase#on.
   * @method Fireproof#on
   * @param {string} eventType
   * @param {function} callback
   * @param {function=} cancelCallback
   * @param {object=} context
   * @returns {function} Your callback parameter wrapped in fireproofing. Use
   * this return value, not your own copy of callback, to call .off(). It also
   * functions as a promise that resolves on success and rejects on failure.
   */
  Fireproof.prototype.on = function(eventType, callback, cancelCallback, context) {

    var promise = pinkySwear();

    if (typeof callback !== 'function') {
      callback = function() {};
    }

    if (typeof cancelCallback !== 'function') {
      cancelCallback = function() {};
    }

    var callbackHandler = function(snap, prev) {

      nextTick(function() {
        callback(snap, prev);
        promise(true, [snap, prev]);
      });

    }.bind(this);

    callbackHandler.then = promise.then.bind(promise);

    this._ref.on(eventType, callbackHandler, function(err) {

      nextTick(function() {
        cancelCallback(err);
        promise(false, [err]);
      });

    }, context);

    return callbackHandler;

  };

  /**
   * Delegates Firebase#off.
   * @method Fireproof#off
   * @param {string} eventType
   * @param {function=} callback
   * @param {object=} context
   */
  Fireproof.prototype.off = function(eventType, callback, context) {

    this._ref.off(eventType, callback, context);

  };

  /**
   * Delegates Firebase#once.
   * @method Fireproof#once
   * @param {object} eventType
   * @param {function} successCallback
   * @param {function=} failureCallback
   * @param {object=} context
   * @returns {Promise} Resolves on success and rejects on failure.
   */
  Fireproof.prototype.once = function(eventType, successCallback, failureCallback, context) {

    var promise = pinkySwear();

    if (typeof successCallback !== 'function') {
      successCallback = function() {};
    }

    if (typeof failureCallback !== 'function') {
      failureCallback = function() {};
    }

    this._ref.once(eventType, function(snap) {

      promise(true, [snap]);
      nextTick(function() {
        successCallback(snap);
      });

    }, function(err) {

      promise(false, [err]);
      nextTick(function() {
        failureCallback(err);
      });

    }, context);

    return promise;

  };

  /**
   * Delegates Firebase#limit.
   * @method Fireproof#limit
   * @param {Number} limit
   * @returns {Fireproof}
   */
  Fireproof.prototype.limit = function(limit) {
    return new Fireproof(this._ref.limit(limit));
  };

  /**
   * Delegates Firebase#startAt.
   * @method Fireproof#startAt
   * @param {object} priority
   * @param {string} name
   * @returns {Fireproof}
   */
  Fireproof.prototype.startAt = function(priority, name) {
    return new Fireproof(this._ref.startAt(priority, name));
  };

  /**
   * Delegates Firebase#endAt.
   * @method Fireproof#endAt
   * @param {object} priority
   * @param {string} name
   * @returns {Fireproof}
   */
  Fireproof.prototype.endAt = function(priority, name) {
    return new Fireproof(this._ref.endAt(priority, name));
  };

  /**
   * Delegates Firebase#equalTo.
   * @method Fireproof#equalTo
   * @param {object} priority
   * @param {string} name
   * @returns {Fireproof}
   */
  Fireproof.prototype.equalTo = function(priority, name) {
    return new Fireproof(this._ref.equalTo(priority, name));
  };

  /**
   * Delegates Firebase#ref.
   * @method Fireproof#ref
   * @returns {Fireproof}
   */
  Fireproof.prototype.ref = function() {
    return new Fireproof(this._ref.ref());
  };

  return Fireproof;

}));
<|endoftext|>


<commit_before>function urlParams() {
  var params = {};
  var pairs = location.search.substring(1).split('&');
  for(var i = 0; pairs[i]; i++) {
    var kv = pairs[i].split('=');
    params[kv[0]] = decodeURIComponent(kv[1]);
  }
  return params;
}

var DEFAULT_TEXTS = ['○', '×'];
var DEFAULT_COLORS = ['white', 'white', 'green', 'black', 'red'];
var DEFAULT_BACKGROUND_COLORS = ['red', 'blue', 'white', 'yellow', 'white'];

function createPage(params, i) {
  var page = {
    text:            DEFAULT_TEXTS[i],
    color:           DEFAULT_COLORS[i % DEFAULT_COLORS.length],
    backgroundColor: DEFAULT_BACKGROUND_COLORS[i % DEFAULT_BACKGROUND_COLORS.length]
  };

  var key = 'page' + i;
  if (!(key in params)) {
    if (i < DEFAULT_TEXTS.length) {
      return page;
    } else {
      return null;
    }
  }

  var words = params[key].split(',');
  page['text']            = words[0] ? words[0] : page['text'];
  page['color']           = words[1] ? words[1] : page['color'];
  page['backgroundColor'] = words[2] ? words[2] : page['backgroundColor'];
  return page;
}

function createPages(params) {
  var pages = [];
  for (var i = 0; i < 10; i++) {
    var page = createPage(params, i);
    if (!page) {
      return pages;
    }
    pages.push(page);
  }
  return pages;
}

function resize() {
  var bodyWidth  = $('body').width();
  var bodyHeight = $('body').height();

  $('div.text_wrapper span').each(function() {
    var width  = $(this).width();
    var height = $(this).height();
    var fontSize = $(this).data('fontSize');
    fontSize *= Math.min(bodyWidth / width, bodyHeight / height);
    $(this).css('fontSize', fontSize + 'px');
    $(this).data('fontSize', fontSize);
  });
}

function init() {
  var params = urlParams();
  var pages = createPages(params);
  for (var i = 0; i < pages.length; i++) {
    var text = $('' + pages[i].text + '');
    text.css('fontSize', '10px');
    text.data('fontSize', 10)
    var text_wrapper = $('

');
    var section = $('

');
    section.css('color', pages[i].color);
    section.css('backgroundColor', pages[i].backgroundColor);

    text_wrapper.append(text);
    section.append(text_wrapper);
    $('#pagepiling').append(section);
  }
}

$(function() {
  init();
  resize();
  $('#pagepiling').pagepiling({});
});

$(window).on("orientationchange resize", resize);

<commit_msg>resize line-height<commit_after>function urlParams() {
  var params = {};
  var pairs = location.search.substring(1).split('&');
  for(var i = 0; pairs[i]; i++) {
    var kv = pairs[i].split('=');
    params[kv[0]] = decodeURIComponent(kv[1]);
  }
  return params;
}

var DEFAULT_TEXTS = ['○', '×'];
var DEFAULT_COLORS = ['white', 'white', 'green', 'black', 'red'];
var DEFAULT_BACKGROUND_COLORS = ['red', 'blue', 'white', 'yellow', 'white'];

function createPage(params, i) {
  var page = {
    text:            DEFAULT_TEXTS[i],
    color:           DEFAULT_COLORS[i % DEFAULT_COLORS.length],
    backgroundColor: DEFAULT_BACKGROUND_COLORS[i % DEFAULT_BACKGROUND_COLORS.length]
  };

  var key = 'page' + i;
  if (!(key in params)) {
    if (i < DEFAULT_TEXTS.length) {
      return page;
    } else {
      return null;
    }
  }

  var words = params[key].split(',');
  page['text']            = words[0] ? words[0] : page['text'];
  page['color']           = words[1] ? words[1] : page['color'];
  page['backgroundColor'] = words[2] ? words[2] : page['backgroundColor'];
  return page;
}

function createPages(params) {
  var pages = [];
  for (var i = 0; i < 10; i++) {
    var page = createPage(params, i);
    if (!page) {
      return pages;
    }
    pages.push(page);
  }
  return pages;
}

function resize() {
  var bodyWidth  = $('body').width();
  var bodyHeight = $('body').height();

  $('div.text_wrapper span').each(function() {
    var width  = $(this).width();
    var height = $(this).height();
    var fontSize = $(this).data('fontSize');
    fontSize *= Math.min(bodyWidth / width, bodyHeight / height);
    $(this).css('fontSize', fontSize + 'px');
    $(this).css('lineHeight', fontSize + 'px');
    $(this).data('fontSize', fontSize);
  });
}

function init() {
  var params = urlParams();
  var pages = createPages(params);
  for (var i = 0; i < pages.length; i++) {
    var text = $('' + pages[i].text + '');
    text.css('fontSize', '10px');
    text.css('lineHeight', '10px');
    text.data('fontSize', 10)
    var text_wrapper = $('

');
    var section = $('

');
    section.css('color', pages[i].color);
    section.css('backgroundColor', pages[i].backgroundColor);

    text_wrapper.append(text);
    section.append(text_wrapper);
    $('#pagepiling').append(section);
  }
}

$(function() {
  init();
  resize();
  $('#pagepiling').pagepiling({});
});

$(window).on("orientationchange resize", resize);

<|endoftext|>


<commit_before>/*
 * mockserver
 * http://mock-server.com
 *
 * Copyright (c) 2014 James Bloom
 * Licensed under the Apache License, Version 2.0
 */

module.exports = (function () {

    var mockServer;
    var artifactoryHost = 'oss.sonatype.org';
    var artifactoryPath = '/content/repositories/releases/org/mock-server/mockserver-netty/';

    var Q = require('q');
    var http = require('http');

    function defer() {
        var promise = (global.protractor ? protractor.promise : Q);
        var deferred = promise.defer();

        if (deferred.fulfill && !deferred.resolve) {
            deferred.resolve = deferred.fulfill;
        }
        return deferred;
    }

    function checkStarted(request, retries, promise, verbose) {
        var deferred = promise || defer();

        var req = http.request(request);
        req.setTimeout(2000);

        req.once('response', function (response) {
            var body = '';

            response.on('data', function (chunk) {
                body += chunk;
            });

            response.on('end', function () {
                deferred.resolve({
                    statusCode: response.statusCode,
                    body: body
                });
            });
        });

        req.once('error', function (error) {
            if (retries > 0) {
                setTimeout(function () {
                    verbose && console.log("waiting for MockServer to start retries remaining: " + retries);
                    checkStarted(request, retries - 1, promise, verbose);
                }, 100);
            } else {
                verbose && console.log("MockServer failed to start");
                deferred.reject(error);
            }
        });

        req.end();

        return deferred.promise;
    }

    function checkStopped(request, retries, promise, verbose) {
        var deferred = promise || defer();

        var req = http.request(request);

        req.once('response', function (response) {
            var body = '';

            response.on('data', function (chunk) {
                body += chunk;
            });

            response.on('end', function () {
                if (retries > 0) {
                    verbose && console.log("waiting for MockServer to stop retries remaining: " + retries);
                    setTimeout(function () {
                        checkStopped(request, retries - 1, promise, verbose)
                    }, 100);
                } else {
                    verbose && console.log("MockServer failed to stop");
                    deferred.reject();
                }
            });
        });

        req.once('error', function () {
            deferred.resolve();
        });

        req.end();

        return deferred.promise;
    }

    function sendRequest(request) {
        var deferred = defer();

        var callback = function (response) {
            var body = '';

            if (response.statusCode === 400 || response.statusCode === 404) {
                deferred.reject(response.statusCode);
            }

            response.on('data', function (chunk) {
                body += chunk;
            });

            response.on('end', function () {
                deferred.resolve({
                    statusCode: response.statusCode,
                    headers: response.headers,
                    body: body
                });
            });
        };

        var req = http.request(request, callback);
        req.end();

        return deferred.promise;
    }

    function start_mockserver(options) {
        var port;
        var deferred = defer();

        if (options && (options.serverPort || options.proxyPort)) {
            if (options.artifactoryHost) {
                artifactoryHost = options.artifactoryHost;
            }

            if (options.artifactoryPath) {
                artifactoryPath = options.artifactoryPath;
            }

            var startupRetries = 100; // wait for 10 seconds

            // double check the jar has already been downloaded
            require('./downloadJar').downloadJar('3.10.6', artifactoryHost, artifactoryPath).then(function () {

                var spawn = require('child_process').spawn;
                var glob = require('glob');
                var commandLineOptions = ['-Dfile.encoding=UTF-8'];
                if (options.trace) {
                    commandLineOptions.push('-Dmockserver.logLevel=TRACE');
                } else if (options.verbose) {
                    commandLineOptions.push('-Dmockserver.logLevel=INFO');
                } else {
                    commandLineOptions.push('-Dmockserver.logLevel=WARN');
                }
                if (options.javaDebugPort) {
                    commandLineOptions.push('-agentlib:jdwp=transport=dt_socket,server=y,suspend=y,address=' + options.javaDebugPort);
                    startupRetries = 500;
                }
                if (options.systemProperties) {
                    commandLineOptions.push(options.systemProperties);
                }
                commandLineOptions.push('-jar');
                commandLineOptions.push(glob.sync('**/mockserver-netty-*-jar-with-dependencies.jar'));
                if (options.serverPort) {
                    commandLineOptions.push("-serverPort");
                    commandLineOptions.push(options.serverPort);
                    port = port || options.serverPort;
                }
                if (options.proxyPort) {
                    commandLineOptions.push("-proxyPort");
                    commandLineOptions.push(options.proxyPort);
                    port = port || options.proxyPort;
                }
                if (options.proxyRemotePort) {
                    commandLineOptions.push("-proxyRemotePort");
                    commandLineOptions.push(options.proxyRemotePort);
                }
                if (options.proxyRemoteHost) {
                    commandLineOptions.push("-proxyRemoteHost");
                    commandLineOptions.push(options.proxyRemoteHost);
                }
                if (options.verbose) {
                    console.log('Running \'java ' + commandLineOptions.join(' ') + '\'');
                }
                mockServer = spawn('java', commandLineOptions, {
                    stdio: ['ignore', (options.verbose ? process.stdout : 'ignore'), process.stderr]
                });

            }).then(function () {
                return checkStarted({
                    method: 'PUT',
                    host: "localhost",
                    path: "/reset",
                    port: port
                }, startupRetries, deferred, options.verbose);
            }, function (error) {
                deferred.reject(error);
            });
        } else {
            deferred.reject("Please specify \"serverPort\" or \"proxyPort\" or both, for example: \"start_mockserver({ serverPort: 1080, proxyPort: 1090 })\"");
        }

        return deferred.promise;
    }

    function stop_mockserver(options) {
        var port;
        var deferred = defer();

        if (options && (options.serverPort || options.proxyPort)) {
            if (options.serverPort) {
                port = port || options.serverPort;
            }
            if (options.proxyPort) {
                port = port || options.proxyPort;
            }
            if (options.verbose) {
                console.log('Using port \'' + port + '\' to stop MockServer and MockServer Proxy');
            }
            sendRequest({
                method: 'PUT',
                host: "localhost",
                path: "/stop",
                port: port
            }).then(function () {
                mockServer && mockServer.kill();
                checkStopped({
                    method: 'PUT',
                    host: "localhost",
                    path: "/reset",
                    port: port
                }, 100, deferred, options && options.verbose); // wait for 10 seconds
            });
        } else {
            deferred.reject("Please specify \"serverPort\" or \"proxyPort\" or both, for example: \"stop_mockserver({ serverPort: 1080, proxyPort: 1090 })\"");
        }
        return deferred.promise;
    }

    return {
        start_mockserver: start_mockserver,
        stop_mockserver: stop_mockserver
    };
})();
<commit_msg>adding shutdown hook for node to jvm<commit_after>/*
 * mockserver
 * http://mock-server.com
 *
 * Copyright (c) 2014 James Bloom
 * Licensed under the Apache License, Version 2.0
 */

module.exports = (function () {

    var mockServer;
    var artifactoryHost = 'oss.sonatype.org';
    var artifactoryPath = '/content/repositories/releases/org/mock-server/mockserver-netty/';

    var Q = require('q');
    var http = require('http');

    function defer() {
        var promise = (global.protractor ? protractor.promise : Q);
        var deferred = promise.defer();

        if (deferred.fulfill && !deferred.resolve) {
            deferred.resolve = deferred.fulfill;
        }
        return deferred;
    }

    function checkStarted(request, retries, promise, verbose) {
        var deferred = promise || defer();

        var req = http.request(request);
        req.setTimeout(2000);

        req.once('response', function (response) {
            var body = '';

            response.on('data', function (chunk) {
                body += chunk;
            });

            response.on('end', function () {
                deferred.resolve({
                    statusCode: response.statusCode,
                    body: body
                });
            });
        });

        req.once('error', function (error) {
            if (retries > 0) {
                setTimeout(function () {
                    verbose && console.log("waiting for MockServer to start retries remaining: " + retries);
                    checkStarted(request, retries - 1, promise, verbose);
                }, 100);
            } else {
                verbose && console.log("MockServer failed to start");
                deferred.reject(error);
            }
        });

        req.end();

        return deferred.promise;
    }

    function checkStopped(request, retries, promise, verbose) {
        var deferred = promise || defer();

        var req = http.request(request);

        req.once('response', function (response) {
            var body = '';

            response.on('data', function (chunk) {
                body += chunk;
            });

            response.on('end', function () {
                if (retries > 0) {
                    verbose && console.log("waiting for MockServer to stop retries remaining: " + retries);
                    setTimeout(function () {
                        checkStopped(request, retries - 1, promise, verbose)
                    }, 100);
                } else {
                    verbose && console.log("MockServer failed to stop");
                    deferred.reject();
                }
            });
        });

        req.once('error', function () {
            deferred.resolve();
        });

        req.end();

        return deferred.promise;
    }

    function sendRequest(request) {
        var deferred = defer();

        var callback = function (response) {
            var body = '';

            if (response.statusCode === 400 || response.statusCode === 404) {
                deferred.reject(response.statusCode);
            }

            response.on('data', function (chunk) {
                body += chunk;
            });

            response.on('end', function () {
                deferred.resolve({
                    statusCode: response.statusCode,
                    headers: response.headers,
                    body: body
                });
            });
        };

        var req = http.request(request, callback);

        req.once('error', function (err) {
            deferred.reject(err);
        });

        req.end();

        return deferred.promise;
    }

    function start_mockserver(options) {
        var port;
        var deferred = defer();

        if (options && (options.serverPort || options.proxyPort)) {
            if (options.artifactoryHost) {
                artifactoryHost = options.artifactoryHost;
            }

            if (options.artifactoryPath) {
                artifactoryPath = options.artifactoryPath;
            }

            var startupRetries = 100; // wait for 10 seconds

            // double check the jar has already been downloaded
            require('./downloadJar').downloadJar('3.10.6', artifactoryHost, artifactoryPath).then(function () {

                var spawn = require('child_process').spawn;
                var glob = require('glob');
                var commandLineOptions = ['-Dfile.encoding=UTF-8'];
                if (options.trace) {
                    commandLineOptions.push('-Dmockserver.logLevel=TRACE');
                } else if (options.verbose) {
                    commandLineOptions.push('-Dmockserver.logLevel=INFO');
                } else {
                    commandLineOptions.push('-Dmockserver.logLevel=WARN');
                }
                if (options.javaDebugPort) {
                    commandLineOptions.push('-agentlib:jdwp=transport=dt_socket,server=y,suspend=y,address=' + options.javaDebugPort);
                    startupRetries = 500;
                }
                if (options.systemProperties) {
                    commandLineOptions.push(options.systemProperties);
                }
                commandLineOptions.push('-jar');
                commandLineOptions.push(glob.sync('**/mockserver-netty-*-jar-with-dependencies.jar'));
                if (options.serverPort) {
                    commandLineOptions.push("-serverPort");
                    commandLineOptions.push(options.serverPort);
                    port = port || options.serverPort;
                }
                if (options.proxyPort) {
                    commandLineOptions.push("-proxyPort");
                    commandLineOptions.push(options.proxyPort);
                    port = port || options.proxyPort;
                }
                if (options.proxyRemotePort) {
                    commandLineOptions.push("-proxyRemotePort");
                    commandLineOptions.push(options.proxyRemotePort);
                }
                if (options.proxyRemoteHost) {
                    commandLineOptions.push("-proxyRemoteHost");
                    commandLineOptions.push(options.proxyRemoteHost);
                }
                if (options.verbose) {
                    console.log('Running \'java ' + commandLineOptions.join(' ') + '\'');
                }
                if (!options.runForked) {
                    function exitHandler(config, err) {
                        return stop_mockserver(config.options).then(function () {
                            if (config.exit) process.exit();
                            if (err) console.log(err.stack);
                        });
                    }

                    // stop mockserver when ctrl+c event fired
                    process.on('SIGINT', exitHandler.bind(null, {exit: false, options: options}));

                    // stop mockserver when kill used
                    process.on('SIGTERM', exitHandler.bind(null, {exit: true, options: options}));

                    // stop mockserver for uncaught exceptions
                    process.on('uncaughtException', exitHandler.bind(null, {exit: false, options: options}));
                }
                mockServer = spawn('java', commandLineOptions, {
                    stdio: ['ignore', (options.verbose ? process.stdout : 'ignore'), process.stderr]
                });

            }).then(function () {
                return checkStarted({
                    method: 'PUT',
                    host: "localhost",
                    path: "/reset",
                    port: port
                }, startupRetries, deferred, options.verbose);
            }, function (error) {
                deferred.reject(error);
            });
        } else {
            deferred.reject("Please specify \"serverPort\" or \"proxyPort\" or both, for example: \"start_mockserver({ serverPort: 1080, proxyPort: 1090 })\"");
        }

        return deferred.promise;
    }

    function stop_mockserver(options) {
        var port;
        var deferred = defer();

        if (options && (options.serverPort || options.proxyPort)) {
            if (options.serverPort) {
                port = port || options.serverPort;
            }
            if (options.proxyPort) {
                port = port || options.proxyPort;
            }
            if (options.verbose) {
                console.log('Using port \'' + port + '\' to stop MockServer and MockServer Proxy');
            }
            sendRequest({
                method: 'PUT',
                host: "localhost",
                path: "/stop",
                port: port
            }).then(
                function () {
                    mockServer && mockServer.kill();
                    checkStopped({
                        method: 'PUT',
                        host: "localhost",
                        path: "/reset",
                        port: port
                    }, 100, deferred, options && options.verbose); // wait for 10 seconds
                },
                function (err) {
                    if (err && err.code === "ECONNREFUSED") {
                        deferred.resolve();
                    } else {
                        deferred.reject(err);
                    }
                }
            );

        } else {
            deferred.reject("Please specify \"serverPort\" or \"proxyPort\" or both, for example: \"stop_mockserver({ serverPort: 1080, proxyPort: 1090 })\"");
        }
        return deferred.promise;
    }

    return {
        start_mockserver: start_mockserver,
        stop_mockserver: stop_mockserver
    };
})();
<|endoftext|>


<commit_before>
var http = require('http');

if (http.METHODS) {
  module.exports = http.METHODS.map(function(method){
    return method.toLowerCase();
  });

  return;
}

module.exports = [
  'get',
  'post',
  'put',
  'head',
  'delete',
  'options',
  'trace',
  'copy',
  'lock',
  'mkcol',
  'move',
  'propfind',
  'proppatch',
  'unlock',
  'report',
  'mkactivity',
  'checkout',
  'merge',
  'm-search',
  'notify',
  'subscribe',
  'unsubscribe',
  'patch',
  'search'
];
<commit_msg>add PURGE<commit_after>
var http = require('http');

if (http.METHODS) {
  module.exports = http.METHODS.map(function(method){
    return method.toLowerCase();
  });

  return;
}

module.exports = [
  'get',
  'post',
  'put',
  'head',
  'delete',
  'options',
  'trace',
  'copy',
  'lock',
  'mkcol',
  'move',
  'purge',
  'propfind',
  'proppatch',
  'unlock',
  'report',
  'mkactivity',
  'checkout',
  'merge',
  'm-search',
  'notify',
  'subscribe',
  'unsubscribe',
  'patch',
  'search'
];
<|endoftext|>


<commit_before><<<<<<< HEAD
var readline = require('readline');

var rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});

process.stdout.write('\u001b[;H\u001b[2J');

rl.setPrompt('\x1b[32mSelect[#]\x1b[32m>\x1b[0m ');
rl.prompt();

var numbers = new Array;
//var options = ['first', 'second', 'third'];
var options;

//renderOptions();
var cb = {};

rl.on('line', function (entry) {
	var entry = parseInt(entry);

	if (numbers.indexOf(entry) === -1 && !(isNaN(entry))) {
		numbers.push(entry);
	} else if (isNaN(entry)) {
		process.stdout.clearLine();
		process.stdout.cursorTo(0);
		rl.setPrompt('>');
		rl.close();
		cb(numbers.map(function(obj){return obj - 1}));
		process.exit(0)

	} else {
		numbers.splice(numbers.indexOf(entry), 1);
	}

    process.stdout.write('\x1b[;H\x1b[2J');

	  renderOptions(options);

    console.log('Selected: ', numbers);
    rl.prompt();

    //if (entry === '') {
	//process.exit(0);
    //}

});

function starter(list, callback) {

	if (!(this instanceof starter)) {
		return new starter(list, callback);
	}

	//this.list = list;
  renderOptions(list);
  options = list;
  cb = callback;

}

renderOptions = function(options) {
	console.log("");
	console.log("Just hit enter to finish selection")
    for (i=0; i < options.length; i++) {
		var isSelected = false;

		for (j = 0; j < numbers.length; j++) {

			if (options[numbers[j]-1] === options[i]) {
				isSelected = true
			}

			if (isSelected) {
				process.stdout.write('\x1b[32m');
			} else {
				process.stdout.write('\x1b[0m');
			}

		}
			console.log('Option ', i+1, options[i]);
			process.stdout.write('\x1b[0m');
		}
}

module.exports = starter;
=======
var readline = require('readline'),
    rl = readline.createInterface(process.stdin, process.stdout);

rl.setPrompt('OHAI> ');
rl.prompt();

rl.on('line', function(line) {
  switch(line.trim()) {
    case 'hello':
      console.log('world!');
      break;
    default:
      console.log('Say what? I might have heard `' + line.trim() + '`');
      break;
  }
  rl.prompt();
}).on('close', function() {
  console.log('Have a great day!');
  process.exit(0);
});

exports.promptStart = function (promptName) {
	rl.setPrompt(promptName);
	rl.prompt();
}
>>>>>>> origin/master
<commit_msg>Update index.js<commit_after>var readline = require('readline');

var rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});

process.stdout.write('\u001b[;H\u001b[2J');

rl.setPrompt('\x1b[32mSelect[#]\x1b[32m>\x1b[0m ');
rl.prompt();

var numbers = new Array;
var options;

var cb = {};

rl.on('line', function (entry) {
	var entry = parseInt(entry);

	if (numbers.indexOf(entry) === -1 && !(isNaN(entry))) {
		numbers.push(entry);
	} else if (isNaN(entry)) {
		process.stdout.clearLine();
		process.stdout.cursorTo(0);
		rl.setPrompt('>');
		rl.close();
		cb(numbers.map(function(obj){return obj - 1}));
		process.exit(0)

	} else {
		numbers.splice(numbers.indexOf(entry), 1);
	}

    process.stdout.write('\x1b[;H\x1b[2J');

    renderOptions(options);

    console.log('Selected: ', numbers);
    rl.prompt();

    //if (entry === '') {
	//process.exit(0);
    //}

});

function starter(list, callback) {

	if (!(this instanceof starter)) {
		return new starter(list, callback);
	}

  renderOptions(list);
  options = list;
  cb = callback;

}

renderOptions = function(options) {
	console.log("");
	console.log("Just hit enter to finish selection")
    for (i=0; i < options.length; i++) {
		var isSelected = false;

		for (j = 0; j < numbers.length; j++) {

			if (options[numbers[j]-1] === options[i]) {
				isSelected = true
			}

			if (isSelected) {
				process.stdout.write('\x1b[32m');
			} else {
				process.stdout.write('\x1b[0m');
			}

		}
			console.log('Option ', i+1, options[i]);
			process.stdout.write('\x1b[0m');
		}
}

module.exports = starter;
var readline = require('readline'),
    rl = readline.createInterface(process.stdin, process.stdout);

rl.setPrompt('OHAI> ');
rl.prompt();

rl.on('line', function(line) {
  switch(line.trim()) {
    case 'hello':
      console.log('world!');
      break;
    default:
      console.log('Say what? I might have heard `' + line.trim() + '`');
      break;
  }
  rl.prompt();
}).on('close', function() {
  console.log('Have a great day!');
  process.exit(0);
});

exports.promptStart = function (promptName) {
	rl.setPrompt(promptName);
	rl.prompt();
}

<|endoftext|>