<commit_before>/**
 * var connectionPool = new ConnectionPool({
 *                            tag:             'droonga',
 *                            defaultDataset:  'example',
 *                            hostNames:       ['127.0.0.1', ...],
 *                            port:            24224,
 *                            receiveHostName: '127.0.0.1',
 *                            receivePort:     10030
 *                          });
 */

var exec = require('child_process').exec,
    path = require('path'),
    Q    = require('q');

var Connection = require('./connection').Connection;
var ConsoleLogger = require('../console-logger').ConsoleLogger;
var SerfAgent = require('../serf/agent');

function ConnectionPool(params) {
  this._params = params || {};

  this._logger = this._params.logger || new ConsoleLogger();

  this._hostNames = [];
  this._connections = {};

  this.hostNames = this._params.hostNames ||
                    this._params.hostName ||
                    Connection.DEFAULT_FLUENT_HOST_NAME;

  this._initialHostNames = this._hostNames.slice(0);
}

ConnectionPool.prototype = {
  get hostNames() {
    return this._hostNames;
  },
  set hostNames(hostNames) {
    if (!Array.isArray(hostNames))
      hostNames = [hostNames];

    var uniqueHostNames = {};
    hostNames.forEach(function(hostName) {
      if (hostName in uniqueHostNames) {
        return false;
      }
      else {
        uniqueHostNames[hostName] = true;
        return true;
      }
    });
    var newHostNames = Object.keys(uniqueHostNames);

    this._hostNames.forEach(function(hostName) {
      if (newHostNames.indexOf(hostName) > -1)
        return;

      this.closeFor(hostName);
    }, this);

    this._hostNames = newHostNames;
    this.nextIndex = Math.floor(Math.random() * this._hostNames.length);

    if (this._hostNames.length == 0)
      throw new Error('ConnectionPool: you must give one or more host name(s)!');

    return this._hostNames;
  },

  get: function() {
    var hostName = this.hostNames[this.nextIndex];

    this.nextIndex++;
    if (this.nextIndex == this.hostNames.length)
      this.nextIndex = 0;

    return this.getConnectionFor(hostName);
  },

  getConnectionFor: function(hostName) {
    if (this._connections[hostName])
      return this._connections[hostName];;

    var klass = this._params.connectionClass || Connection;
    return this._connections[hostName] = new klass({
      tag:             this._params.tag,
      defaultDataset:  this._params.defaultDataset,
      hostName:        hostName,
      port:            this._params.port,
      receiveHostName: this._params.receiveHostName,
      receivePort:     this._params.receivePort,
      logger:          this._logger
    });
  },

  closeAll: function() {
    this._hostNames.forEach(this.closeFor, this);
  },

  closeFor: function(hostName) {
    var connection = this._connections[hostName];
    if (!connection)
      return;
    connection.close();
    delete this._connections[hostName];
  },

  get count() {
    return this._hostNames.length;
  },

  getEnginesFromCluster: function(retryCount) {
    if (this._watching)
      return this.getEnginesFromClusterMember(this._serf.rpcAddress);

    retryCount = retryCount || 0;
    var hostName = this._hostNames[retryCount];
    if (!hostName)
      return Q.Promise((function(resolve, reject, notify) {
        var error = new Error('all cluster members are unaccessible.');
        this._logger.error(error);
        reject(error);
      }).bind(this));

    return this.getEnginesFromClusterMember(hostName)
                 .then(function(engines) {
                   return engines;
                 })
                 .catch((function(error) {
                   this._logger.error('Failed to get the list of droonga-engine hosts from the cluster member ' + hostName + '.');
                   this._logger.error(error);
                   return this.getEnginesFromCluster(retryCount + 1);
                 }).bind(this));
  },
  getEnginesFromClusterMember: function(rpcAddress) {
    return Q.Promise((function(resolve, reject, notify) {
      if (!rpcAddress)
        reject(new Error('no RPC address is given'));

      // Because node-rpc has no API to disconnect from the RPC host,
      // we should use it in a separate expendable process.
      var commandPath = path.join(__dirname, '..', '..', 'bin',
                          'express-droonga-report-live-engine-hosts');
      var commandLine = [
        commandPath,
          '--rpc-address=' + rpcAddress,
          '--droonga-engine-port=' + this._params.port,
          '--tag=' + this._params.tag,
          '--priority-hosts=' + this._initialHostNames.join(',')
      ].join(' ');
      exec(commandLine, function(error, stdin, stdout) {
        if (error)
          return reject(error);
        var result = JSON.parse(stdin.trim());
        this._logger.debug('express-droonga-report-live-engine-hosts:');
        this._logger.debug(result);
        resolve(result.liveEngineNodes);
      });
    }).bind(this));
  },
  reJoinToInitialCluster: function() {
    return Q.Promise((function(resolve, reject, notify) {
      // Because node-rpc has no API to disconnect from the RPC host,
      // we should use it in a separate expendable process.
      var commandPath = path.join(__dirname, '..', '..', 'bin',
                          'express-droonga-join-to-cluster');
      var commandLine = [
        commandPath,
          '--rpc-address=' + this._serf.rpcAddress,
          '--droonga-engine-port=' + this._params.port,
          '--tag=' + this._params.tag,
          '--hosts=' + this._initialHostNames.join(',')
      ].join(' ');
      exec(commandLine, function(error, stdin, stdout) {
        if (error)
          return reject(error);
        resolve();
      });
    }).bind(this));
  },

  updateHostNamesFromCluster: function() {
    return this.getEnginesFromCluster()
                 .then((function(engines) {
                   this.clusterId = engines[0].Tags.cluster_id;
                   var hostNames = engines.map(function(engine) {
                     return engine.HostName;
                   });
                   this.hostNames = hostNames;
                   this._logger.info('List of droonga-engine hosts is successfully initialized from the cluster.');
                   this._logger.info('cluster id: '+this.clusterId);
                   this._logger.info(hostNames);
                   return hostNames;
                 }).bind(this))
                 .catch(function(error) {
                   this._logger.error('Failed to initialize the list of droonga-engine hosts from the cluster.');
                   this._logger.error(error);
                 });
  },

  startWatchClusterChanges: function() {
    return Q.Promise((function(resolve, reject, notify) {
      if (this._watching)
        return resolve();
      this._serf = new SerfAgent({
        serf:         this._params.serf,
        hostName:     this._params.receiveHostName,
        otherMembers: this.hostNames,
        logger:       this._logger
      });
      this._serf.start()
        .then((function() {
          this._logger.info('Start to watch changes in the cluster.');
          this._watching = true;
          this._serf.on('member-change', (function() {
            this._logger.info('Serf cluster member is changed.');
            if (this._updateHostNamesTimer)
              return;
            this._updateHostNamesTimer = setTimeout((function() {
              this._updateHostNamesTimer = null;
              this.updateHostNamesFromCluster()
                .then((function() {
                  if (this._hostNames.length == 0) {
                    return this.reJoinToInitialCluster();
                  }
                }).bind(this));
            }).bind(this), 500);
          }).bind(this));
          resolve();
        }).bind(this))
        .catch(function(error) {
          this._logger.error('Failed to start watching of changes in the cluster.');
          this._logger.error(error);
          reject(error);
        });
    }).bind(this));
  },

  endWatchClusterChanges: function() {
    return Q.Promise((function(resolve, reject, notify) {
      if (!this._watching)
        return resolve();
      this._serf.shutdown()
                  .then((function() {
                    delete this._serf;
                    this._watching = false;
                    resolve();
                  }).bind(this));
    }).bind(this));
  },

  startSyncHostNamesFromCluster: function() {
    this._defaultHostNames = this._hostNames.slice(0);
    return this.updateHostNamesFromCluster()
                 .then(this.startWatchClusterChanges.bind(this));
  },

  stopSyncHostNamesFromCluster: function() {
    return this.endWatchClusterChanges();
  }
};

exports.ConnectionPool = ConnectionPool;
<commit_msg>Output errors in sub commands to the log<commit_after>/**
 * var connectionPool = new ConnectionPool({
 *                            tag:             'droonga',
 *                            defaultDataset:  'example',
 *                            hostNames:       ['127.0.0.1', ...],
 *                            port:            24224,
 *                            receiveHostName: '127.0.0.1',
 *                            receivePort:     10030
 *                          });
 */

var exec = require('child_process').exec,
    path = require('path'),
    Q    = require('q');

var Connection = require('./connection').Connection;
var ConsoleLogger = require('../console-logger').ConsoleLogger;
var SerfAgent = require('../serf/agent');

function ConnectionPool(params) {
  this._params = params || {};

  this._logger = this._params.logger || new ConsoleLogger();

  this._hostNames = [];
  this._connections = {};

  this.hostNames = this._params.hostNames ||
                    this._params.hostName ||
                    Connection.DEFAULT_FLUENT_HOST_NAME;

  this._initialHostNames = this._hostNames.slice(0);
}

ConnectionPool.prototype = {
  get hostNames() {
    return this._hostNames;
  },
  set hostNames(hostNames) {
    if (!Array.isArray(hostNames))
      hostNames = [hostNames];

    var uniqueHostNames = {};
    hostNames.forEach(function(hostName) {
      if (hostName in uniqueHostNames) {
        return false;
      }
      else {
        uniqueHostNames[hostName] = true;
        return true;
      }
    });
    var newHostNames = Object.keys(uniqueHostNames);

    this._hostNames.forEach(function(hostName) {
      if (newHostNames.indexOf(hostName) > -1)
        return;

      this.closeFor(hostName);
    }, this);

    this._hostNames = newHostNames;
    this.nextIndex = Math.floor(Math.random() * this._hostNames.length);

    if (this._hostNames.length == 0)
      throw new Error('ConnectionPool: you must give one or more host name(s)!');

    return this._hostNames;
  },

  get: function() {
    var hostName = this.hostNames[this.nextIndex];

    this.nextIndex++;
    if (this.nextIndex == this.hostNames.length)
      this.nextIndex = 0;

    return this.getConnectionFor(hostName);
  },

  getConnectionFor: function(hostName) {
    if (this._connections[hostName])
      return this._connections[hostName];;

    var klass = this._params.connectionClass || Connection;
    return this._connections[hostName] = new klass({
      tag:             this._params.tag,
      defaultDataset:  this._params.defaultDataset,
      hostName:        hostName,
      port:            this._params.port,
      receiveHostName: this._params.receiveHostName,
      receivePort:     this._params.receivePort,
      logger:          this._logger
    });
  },

  closeAll: function() {
    this._hostNames.forEach(this.closeFor, this);
  },

  closeFor: function(hostName) {
    var connection = this._connections[hostName];
    if (!connection)
      return;
    connection.close();
    delete this._connections[hostName];
  },

  get count() {
    return this._hostNames.length;
  },

  getEnginesFromCluster: function(retryCount) {
    if (this._watching)
      return this.getEnginesFromClusterMember(this._serf.rpcAddress);

    retryCount = retryCount || 0;
    var hostName = this._hostNames[retryCount];
    if (!hostName)
      return Q.Promise((function(resolve, reject, notify) {
        var error = new Error('all cluster members are unaccessible.');
        this._logger.error(error);
        reject(error);
      }).bind(this));

    return this.getEnginesFromClusterMember(hostName)
                 .then(function(engines) {
                   return engines;
                 })
                 .catch((function(error) {
                   this._logger.error('Failed to get the list of droonga-engine hosts from the cluster member ' + hostName + '.');
                   this._logger.error(error);
                   return this.getEnginesFromCluster(retryCount + 1);
                 }).bind(this));
  },
  getEnginesFromClusterMember: function(rpcAddress) {
    return Q.Promise((function(resolve, reject, notify) {
      if (!rpcAddress)
        reject(new Error('no RPC address is given'));

      // Because node-rpc has no API to disconnect from the RPC host,
      // we should use it in a separate expendable process.
      var commandPath = path.join(__dirname, '..', '..', 'bin',
                          'express-droonga-report-live-engine-hosts');
      var commandLine = [
        commandPath,
          '--rpc-address=' + rpcAddress,
          '--droonga-engine-port=' + this._params.port,
          '--tag=' + this._params.tag,
          '--priority-hosts=' + this._initialHostNames.join(',')
      ].join(' ');
      exec(commandLine, function(error, stdin, stdout) {
        if (error) {
          this._logger.error('express-droonga-report-live-engine-hosts:');
          this._logger.error(stdin.trim());
          return reject(error);
        }
        var result = JSON.parse(stdin.trim());
        this._logger.debug('express-droonga-report-live-engine-hosts:');
        this._logger.debug(result);
        resolve(result.liveEngineNodes);
      });
    }).bind(this));
  },
  reJoinToInitialCluster: function() {
    return Q.Promise((function(resolve, reject, notify) {
      // Because node-rpc has no API to disconnect from the RPC host,
      // we should use it in a separate expendable process.
      var commandPath = path.join(__dirname, '..', '..', 'bin',
                          'express-droonga-join-to-cluster');
      var commandLine = [
        commandPath,
          '--rpc-address=' + this._serf.rpcAddress,
          '--droonga-engine-port=' + this._params.port,
          '--tag=' + this._params.tag,
          '--hosts=' + this._initialHostNames.join(',')
      ].join(' ');
      exec(commandLine, function(error, stdin, stdout) {
        if (error) {
          this._logger.error('express-droonga-join-to-cluster:');
          this._logger.error(stdin.trim());
          return reject(error);
        }
        resolve();
      });
    }).bind(this));
  },

  updateHostNamesFromCluster: function() {
    return this.getEnginesFromCluster()
                 .then((function(engines) {
                   this.clusterId = engines[0].Tags.cluster_id;
                   var hostNames = engines.map(function(engine) {
                     return engine.HostName;
                   });
                   this.hostNames = hostNames;
                   this._logger.info('List of droonga-engine hosts is successfully initialized from the cluster.');
                   this._logger.info('cluster id: '+this.clusterId);
                   this._logger.info(hostNames);
                   return hostNames;
                 }).bind(this))
                 .catch(function(error) {
                   this._logger.error('Failed to initialize the list of droonga-engine hosts from the cluster.');
                   this._logger.error(error);
                 });
  },

  startWatchClusterChanges: function() {
    return Q.Promise((function(resolve, reject, notify) {
      if (this._watching)
        return resolve();
      this._serf = new SerfAgent({
        serf:         this._params.serf,
        hostName:     this._params.receiveHostName,
        otherMembers: this.hostNames,
        logger:       this._logger
      });
      this._serf.start()
        .then((function() {
          this._logger.info('Start to watch changes in the cluster.');
          this._watching = true;
          this._serf.on('member-change', (function() {
            this._logger.info('Serf cluster member is changed.');
            if (this._updateHostNamesTimer)
              return;
            this._updateHostNamesTimer = setTimeout((function() {
              this._updateHostNamesTimer = null;
              this.updateHostNamesFromCluster()
                .then((function() {
                  if (this._hostNames.length == 0) {
                    return this.reJoinToInitialCluster();
                  }
                }).bind(this));
            }).bind(this), 500);
          }).bind(this));
          resolve();
        }).bind(this))
        .catch(function(error) {
          this._logger.error('Failed to start watching of changes in the cluster.');
          this._logger.error(error);
          reject(error);
        });
    }).bind(this));
  },

  endWatchClusterChanges: function() {
    return Q.Promise((function(resolve, reject, notify) {
      if (!this._watching)
        return resolve();
      this._serf.shutdown()
                  .then((function() {
                    delete this._serf;
                    this._watching = false;
                    resolve();
                  }).bind(this));
    }).bind(this));
  },

  startSyncHostNamesFromCluster: function() {
    this._defaultHostNames = this._hostNames.slice(0);
    return this.updateHostNamesFromCluster()
                 .then(this.startWatchClusterChanges.bind(this));
  },

  stopSyncHostNamesFromCluster: function() {
    return this.endWatchClusterChanges();
  }
};

exports.ConnectionPool = ConnectionPool;
<|endoftext|>


<commit_before>import openWindowCommand from './commands/openWindowCommand';
import replyToCreatorCommand from './commands/replyToCreatorCommand';
import replyToDateCommand from './commands/replyToDateCommand';
import replyToGitCommand from './commands/replyToGitCommand';

const bootstrap = commandRepository => {
  commandRepository.register([
    openWindowCommand,
    replyToCreatorCommand,
    replyToDateCommand,
    replyToGitCommand,
  ]);
};

export default { bootstrap };
<commit_msg>fix(commandBootstrapper): código desnecessário<commit_after><|endoftext|>


<commit_before>/**
 * var connectionPool = new ConnectionPool({
 *                            tag:             'droonga',
 *                            defaultDataset:  'example',
 *                            hostNames:       ['127.0.0.1', ...],
 *                            port:            24224,
 *                            receiveHostName: '127.0.0.1',
 *                            receivePort:     10030
 *                          });
 */

var Connection = require('./connection').Connection;
var ConsoleLogger = require('../console-logger').ConsoleLogger;
var Catalog = require('../catalog').Catalog;

function ConnectionPool(params) {
  this._params = params || {};

  if (!this._params.logger)
    this._params.logger = new ConsoleLogger();

  this._hostNames = [];
  this._connections = {};

  this.hostNames = this._params.hostNames ||
                    this._params.hostName ||
                    Connection.DEFAULT_FLUENT_HOST_NAME;
}

ConnectionPool.prototype = {
  get hostNames() {
    return this._hostNames;
  },
  set hostNames(hostNames) {
    if (!Array.isArray(hostNames))
      hostNames = [hostNames];

    var uniqueHostNames = {};
    hostNames.forEach(function(hostName) {
      if (hostName in uniqueHostNames) {
        return false;
      }
      else {
        uniqueHostNames[hostName] = true;
        return true;
      }
    });
    var newHostNames = Object.keys(uniqueHostNames);

    this._hostNames.forEach(function(hostName) {
      if (newHostNames.indexOf(hostName) > -1)
        return;

      this.closeFor(hostName);
    }, this);

    this._hostNames = newHostNames;
    this.nextIndex = Math.floor(Math.random() * this._hostNames.length);

    if (this._hostNames.length == 0)
      throw new Error('ConnectionPool: you must give one or more host name(s)!');

    return this._hostNames;
  },

  get: function() {
    var hostName = this.hostNames[this.nextIndex];

    this.nextIndex++;
    if (this.nextIndex == this.hostNames.length)
      this.nextIndex = 0;

    return this.getConnectionFor(hostName);
  },

  getConnectionFor: function(hostName) {
    if (this._connections[hostName])
      return this._connections[hostName];;

    var klass = this._params.connectionClass || Connection;
    return this._connections[hostName] = new klass({
      tag:             this._params.tag,
      defaultDataset:  this._params.defaultDataset,
      hostName:        hostName,
      port:            this._params.port,
      receiveHostName: this._params.receiveHostName,
      receivePort:     this._params.receivePort
    });
  },

  closeAll: function() {
    this._hostNames.forEach(this.closeFor, this);
  },

  closeFor: function(hostName) {
    var connection = this._connections[hostName];
    if (!connection)
      return;
    connection.close();
    delete this._connections[hostName];
  },

  get count() {
    return this._hostNames.length;
  },

  updateHostNamesFromCatalog: function() {
    return this.getHostNamesFromCatalog()
                 .then((function(hostNames) {
                   this.hostNames = hostNames;
                   return hostNames;
                 }).bind(this));
  },

  getHostNamesFromCatalog: function() {
    return this.fetchCatalog()
                 .then(function(catalog) {
                   return catalog.allHostNames;
                 });
  },

  fetchCatalog: function() {
    return this.get().thenableEmitMessage('catalog.fetch')
                       .then(this._handleFetchedCatalog.bind(this));
  },
  _handleFetchedCatalog: function(result) {
    this._params.logger.trace('ConnectionPool: fetchCatalog: fetched result');
    this._params.logger.trace(result);
    if (result.errorCode) {
      this._params.logger.error(new Error('ConnectionPool: failed to fetch catalog'));
      return;
    }
    var catalog = result.response.body;
    return new Catalog(catalog);
  }
};

exports.ConnectionPool = ConnectionPool;
<commit_msg>Use "debug" instead of "trace" for the log level<commit_after>/**
 * var connectionPool = new ConnectionPool({
 *                            tag:             'droonga',
 *                            defaultDataset:  'example',
 *                            hostNames:       ['127.0.0.1', ...],
 *                            port:            24224,
 *                            receiveHostName: '127.0.0.1',
 *                            receivePort:     10030
 *                          });
 */

var Connection = require('./connection').Connection;
var ConsoleLogger = require('../console-logger').ConsoleLogger;
var Catalog = require('../catalog').Catalog;

function ConnectionPool(params) {
  this._params = params || {};

  if (!this._params.logger)
    this._params.logger = new ConsoleLogger();

  this._hostNames = [];
  this._connections = {};

  this.hostNames = this._params.hostNames ||
                    this._params.hostName ||
                    Connection.DEFAULT_FLUENT_HOST_NAME;
}

ConnectionPool.prototype = {
  get hostNames() {
    return this._hostNames;
  },
  set hostNames(hostNames) {
    if (!Array.isArray(hostNames))
      hostNames = [hostNames];

    var uniqueHostNames = {};
    hostNames.forEach(function(hostName) {
      if (hostName in uniqueHostNames) {
        return false;
      }
      else {
        uniqueHostNames[hostName] = true;
        return true;
      }
    });
    var newHostNames = Object.keys(uniqueHostNames);

    this._hostNames.forEach(function(hostName) {
      if (newHostNames.indexOf(hostName) > -1)
        return;

      this.closeFor(hostName);
    }, this);

    this._hostNames = newHostNames;
    this.nextIndex = Math.floor(Math.random() * this._hostNames.length);

    if (this._hostNames.length == 0)
      throw new Error('ConnectionPool: you must give one or more host name(s)!');

    return this._hostNames;
  },

  get: function() {
    var hostName = this.hostNames[this.nextIndex];

    this.nextIndex++;
    if (this.nextIndex == this.hostNames.length)
      this.nextIndex = 0;

    return this.getConnectionFor(hostName);
  },

  getConnectionFor: function(hostName) {
    if (this._connections[hostName])
      return this._connections[hostName];;

    var klass = this._params.connectionClass || Connection;
    return this._connections[hostName] = new klass({
      tag:             this._params.tag,
      defaultDataset:  this._params.defaultDataset,
      hostName:        hostName,
      port:            this._params.port,
      receiveHostName: this._params.receiveHostName,
      receivePort:     this._params.receivePort
    });
  },

  closeAll: function() {
    this._hostNames.forEach(this.closeFor, this);
  },

  closeFor: function(hostName) {
    var connection = this._connections[hostName];
    if (!connection)
      return;
    connection.close();
    delete this._connections[hostName];
  },

  get count() {
    return this._hostNames.length;
  },

  updateHostNamesFromCatalog: function() {
    return this.getHostNamesFromCatalog()
                 .then((function(hostNames) {
                   this.hostNames = hostNames;
                   return hostNames;
                 }).bind(this));
  },

  getHostNamesFromCatalog: function() {
    return this.fetchCatalog()
                 .then(function(catalog) {
                   return catalog.allHostNames;
                 });
  },

  fetchCatalog: function() {
    return this.get().thenableEmitMessage('catalog.fetch')
                       .then(this._handleFetchedCatalog.bind(this));
  },
  _handleFetchedCatalog: function(result) {
    this._params.logger.debug('ConnectionPool: fetchCatalog: fetched result');
    this._params.logger.debug(result);
    if (result.errorCode) {
      this._params.logger.error(new Error('ConnectionPool: failed to fetch catalog'));
      return;
    }
    var catalog = result.response.body;
    return new Catalog(catalog);
  }
};

exports.ConnectionPool = ConnectionPool;
<|endoftext|>


<commit_before>let fs = require('fs')
let path = require('path')
let execSync = require('child_process').execSync
let packageJson = require('./package.json')

const LIB_DIR = path.resolve('lib')

const CMD = process.argv.slice(2).join(' ')

const MAIN_JS_FILE = 'main.js'
const MAIN_JS_DATA = [
  'require = require("esm")(module/*, options*/)',
  'module.exports = require("./index.js")'
].join('\n')

// files to cleanup to avoid packing
const CLEANUP_FILES = [
  'node_modules',
  'package-lock.json'
]

// .npmignore
const NPM_IGNORE = [
  '.*',
  '*.tgz',
  'node_modules',
  'package-lock.json'
]

function cleanup() {
  CLEANUP_FILES.forEach(f => fs.rmdirSync(path.join(LIB_DIR, f), { recursive: true }))
}

/**
 * Prepares the lib directory for distributting
 */
function prepare() {

  // ensure directory exists
  if (!fs.existsSync(LIB_DIR)) {
    console.error("Directory", LIB_DIR, "does not exist")
    process.exit(1)
  }

  console.log("Preparing", LIB_DIR)

  cleanup()

  // write ignore file
  fs.writeFileSync(path.join(LIB_DIR, '.npmignore'), NPM_IGNORE.join('\n'))

  // copy all the allowed files to the lib directory
  packageJson.files = packageJson.files.reduce((files, p) => {
    if (!p.match(/(lib|index\.js)/)) {
      fs.copyFileSync(path.resolve(p), path.join(LIB_DIR, p))
      files.push(p)
    }
    return files
  }, [
    '**/*.js',
    '**/*.ts'
  ])

  // write main entry files using esm
  fs.writeFileSync(path.join(LIB_DIR, MAIN_JS_FILE), MAIN_JS_DATA)

  // override entry files
  packageJson.main = MAIN_JS_FILE
  packageJson.module = 'index.js'
  packageJson.typings = 'index.d.ts'

  // clear all scripts
  packageJson.scripts = {}
  packageJson.devDependencies = {}

  let data = JSON.stringify(packageJson, null, 2)

  // write new package.json for lib
  fs.writeFileSync(path.join(LIB_DIR, 'package.json'), data)

  console.log("Prepared", LIB_DIR)
}

function main() {
  prepare()

  if (CMD) {
    // execute within lib dir
    let npm_cmd = "npm " + CMD

    console.log("\nExecuting command:", npm_cmd, "\n")

    // execute command
    execSync(npm_cmd, { cwd: LIB_DIR, env: process.env, stdio: 'inherit' })

    console.log("\nCompleted command\n")

    // if we created a tar file, copy to parent directory
    let tarball = packageJson.name + '-' + packageJson.version + '.tgz'
    let tarballPath = path.join(LIB_DIR, tarball)
    if (fs.existsSync(tarballPath)) {
      console.log("Copying", tarball, "to correct folder")
      fs.renameSync(tarballPath, path.join(path.dirname(LIB_DIR), tarball))
    }
  }

  cleanup()
}

main()<commit_msg>Fix prepare.js to create lib directory on startup<commit_after>let fs = require('fs')
let path = require('path')
let execSync = require('child_process').execSync
let packageJson = require('./package.json')

const LIB_DIR = path.resolve('lib')

const CMD = process.argv.slice(2).join(' ')

const MAIN_JS_FILE = 'main.js'
const MAIN_JS_DATA = [
  'require = require("esm")(module/*, options*/)',
  'module.exports = require("./index.js")'
].join('\n')

// files to cleanup to avoid packing
const CLEANUP_FILES = [
  'node_modules',
  'package-lock.json'
]

// .npmignore
const NPM_IGNORE = [
  '.*',
  '*.tgz',
  'node_modules',
  'package-lock.json'
]

function cleanup() {
  CLEANUP_FILES.forEach(f => fs.rmdirSync(path.join(LIB_DIR, f), { recursive: true }))
}

/**
 * Prepares the lib directory for distributting
 */
function prepare() {

  // ensure directory exists
  if (!fs.existsSync(LIB_DIR)) fs.mkdirSync(LIB_DIR)

  console.log("Preparing", LIB_DIR)

  cleanup()

  // write ignore file
  fs.writeFileSync(path.join(LIB_DIR, '.npmignore'), NPM_IGNORE.join('\n'))

  // copy all the allowed files to the lib directory
  packageJson.files = packageJson.files.reduce((files, p) => {
    if (!p.match(/(lib|index\.js)/)) {
      fs.copyFileSync(path.resolve(p), path.join(LIB_DIR, p))
      files.push(p)
    }
    return files
  }, [
    '**/*.js',
    '**/*.ts'
  ])

  // write main entry files using esm
  fs.writeFileSync(path.join(LIB_DIR, MAIN_JS_FILE), MAIN_JS_DATA)

  // override entry files
  packageJson.main = MAIN_JS_FILE
  packageJson.module = 'index.js'
  packageJson.typings = 'index.d.ts'

  // clear all scripts
  packageJson.scripts = {}
  packageJson.devDependencies = {}

  let data = JSON.stringify(packageJson, null, 2)

  // write new package.json for lib
  fs.writeFileSync(path.join(LIB_DIR, 'package.json'), data)

  console.log("Prepared", LIB_DIR)
}

function main() {
  prepare()

  if (CMD) {
    // execute within lib dir
    let npm_cmd = "npm " + CMD

    console.log("\nExecuting command:", npm_cmd, "\n")

    // execute command
    execSync(npm_cmd, { cwd: LIB_DIR, env: process.env, stdio: 'inherit' })

    console.log("\nCompleted command\n")

    // if we created a tar file, copy to parent directory
    let tarball = packageJson.name + '-' + packageJson.version + '.tgz'
    let tarballPath = path.join(LIB_DIR, tarball)
    if (fs.existsSync(tarballPath)) {
      console.log("Copying", tarball, "to correct folder")
      fs.renameSync(tarballPath, path.join(path.dirname(LIB_DIR), tarball))
    }
  }

  cleanup()
}

main()<|endoftext|>


<commit_before>// @flow

import * as React from 'react';
import _ from 'lodash';
import cx from 'classnames';
import SearchPage from 'app/components/Search/SearchPage';
import type { SearchResult } from 'app/reducers/search';
import styles from './Abacard.css';

// $FlowFixMe
import goodSound from '../../../../assets/good-sound.mp3';
import type { EventRegistration } from 'app/models';
type State = {
  showCompleted: boolean
};
type Props = {
  registered: Array<EventRegistration>,
  event: {
    totalCapacity: number
  },
  clearSearch: () => void,
  handleSelect: SearchResult => Promise<void>,
  location: Object,
  onQueryChanged: string => void,
  results: Array<SearchResult>,
  searching: boolean
};

class Abacard extends React.Component<Props, State> {
  input: ?HTMLInputElement;
  state = {
    showCompleted: false
  };

  showCompleted = () => {
    this.setState({ showCompleted: true });
    setTimeout(() => this.setState({ showCompleted: false }), 2000);
  };

  handleSelect = (result: SearchResult) => {
    this.props.clearSearch();
    return this.props
      .handleSelect(result)
      .then(
        () => {
          const sound = new window.Audio(goodSound);
          sound.play();
          this.showCompleted();
        },
        err => {
          const payload = _.get(err, 'payload.response.jsonData');
          if (payload && payload.errorCode === 'not_registered') {
            alert('Bruker er ikke påmeldt på eventet!');
          } else if (payload && payload.errorCode === 'already_present') {
            alert('Bruker er allerede satt som tilstede.');
          } else {
            alert(
              `Det oppsto en uventet feil: ${JSON.stringify(payload || err)}`
            );
          }
        }
      )
      .then(() => {
        if (this.input) {
          this.input.focus();
        }
      });
  };

  render() {
    const {
      registered,
      event: { totalCapacity }
    } = this.props;
    const registerCount = registered.filter(
      reg => reg.presence === 'PRESENT' && reg.pool
    ).length;

    return (

            Tusen takk! Kos deg{' '}

              😀

        <SearchPage
          {...this.props}
          placeholder="Skriv inn brukernavn eller navn"
          handleSelect={this.handleSelect}
          inputRef={input => {
            this.input = input;
          }}
        />

          {registerCount}/{totalCapacity} har møtt opp

    );
  }
}

export default Abacard;
<commit_msg>Abachard<commit_after>// @flow

import * as React from 'react';
import _ from 'lodash';
import cx from 'classnames';
import SearchPage from 'app/components/Search/SearchPage';
import type { SearchResult } from 'app/reducers/search';
import styles from './Abacard.css';

// $FlowFixMe
import goodSound from '../../../../assets/good-sound.mp3';
import type { EventRegistration } from 'app/models';
type State = {
  showCompleted: boolean
};
type Props = {
  registered: Array<EventRegistration>,
  event: {
    totalCapacity: number
  },
  clearSearch: () => void,
  handleSelect: SearchResult => Promise<void>,
  location: Object,
  onQueryChanged: string => void,
  results: Array<SearchResult>,
  searching: boolean
};

class Abacard extends React.Component<Props, State> {
  input: ?HTMLInputElement;
  state = {
    showCompleted: false
  };

  showCompleted = () => {
    this.setState({ showCompleted: true });
    setTimeout(() => this.setState({ showCompleted: false }), 2000);
  };

  handleSelect = (result: SearchResult) => {
    this.props.clearSearch();
    return this.props
      .handleSelect(result)
      .then(
        () => {
          const sound = new window.Audio(goodSound);
          sound.play();
          this.showCompleted();
        },
        err => {
          const payload = _.get(err, 'payload.response.jsonData');
          if (payload && payload.errorCode === 'not_registered') {
            alert('Bruker er ikke påmeldt på eventet!');
          } else if (payload && payload.errorCode === 'already_present') {
            alert(payload.error);
          } else {
            alert(
              `Det oppsto en uventet feil: ${JSON.stringify(payload || err)}`
            );
          }
        }
      )
      .then(() => {
        if (this.input) {
          this.input.focus();
        }
      });
  };

  render() {
    const {
      registered,
      event: { totalCapacity }
    } = this.props;
    const registerCount = registered.filter(
      reg => reg.presence === 'PRESENT' && reg.pool
    ).length;

    return (

            Tusen takk! Kos deg{' '}

              😀

        <SearchPage
          {...this.props}
          placeholder="Skriv inn brukernavn eller navn"
          handleSelect={this.handleSelect}
          inputRef={input => {
            this.input = input;
          }}
        />

          {registerCount}/{totalCapacity} har møtt opp

    );
  }
}

export default Abacard;
<|endoftext|>


<commit_before>/* Copyright 2013 the Melange authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
melange.templates.inherit(
  function (_self, context) {
    jQuery("select, input:radio, input:file, input:checkbox").uniform();
    tinyMCE.init(melange.tinyMceConfig(["melange-description-textarea",
                                       "accepted_orgs_msg"]));
    melange.autocomplete.makeAutoComplete("org_admin_agreement");
    melange.autocomplete.makeAutoComplete("mentor_agreement");
    melange.autocomplete.makeAutoComplete("student_agreement");
    melange.autocomplete.makeAutoComplete("about_page");
    melange.autocomplete.makeAutoComplete("events_page");
    melange.autocomplete.makeAutoComplete("connect_with_us_page");
    melange.autocomplete.makeAutoComplete("help_page");
    melange.autocomplete.makeAutoComplete("privacy_policy");
  }
);
<commit_msg>TinyMCE is not used for setting program description.<commit_after>/* Copyright 2013 the Melange authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
melange.templates.inherit(
  function (_self, context) {
    jQuery("select, input:radio, input:file, input:checkbox").uniform();
    tinyMCE.init(melange.tinyMceConfig(["accepted_orgs_msg"]));
    melange.autocomplete.makeAutoComplete("org_admin_agreement");
    melange.autocomplete.makeAutoComplete("mentor_agreement");
    melange.autocomplete.makeAutoComplete("student_agreement");
    melange.autocomplete.makeAutoComplete("about_page");
    melange.autocomplete.makeAutoComplete("events_page");
    melange.autocomplete.makeAutoComplete("connect_with_us_page");
    melange.autocomplete.makeAutoComplete("help_page");
    melange.autocomplete.makeAutoComplete("privacy_policy");
  }
);
<|endoftext|>


<commit_before>/**
 * Main Process - 自动更新
 *
 * @file OSXUpdater.js
 * @author mudio(job.mudio@gmail.com)
 */

/* eslint no-underscore-dangle: [2, { "allowAfterThis": true }], no-unused-vars: 0 */

import debug from 'debug';
import * as os from 'os';
import request from 'request';
import {app, autoUpdater} from 'electron';

import {
    UPDATE_ERROR,
    UPDATE_CHECKING,
    UPDATE_AVAILABLE,
    UPDATE_DOWNLOADED,
    UPDATE_NOT_AVAILABLE
} from '../bce/actions/updater';

const logger = debug('bce-client:updater');
const UPDATE_SERVER_HOST = 'bceclient.duapp.com';

export default class OSXUpdater {
    constructor(window) {
        this._window = window;
    }

    notify(title, message) {
        this._window.webContents.send('notify', title, message);
    }

    checkForUpdates() {
        const platform = os.platform();
        const feedURL = `http://${UPDATE_SERVER_HOST}/update/${platform}/${app.getVersion()}`;

        autoUpdater.on('update-available', () => this.notify(UPDATE_AVAILABLE));
        autoUpdater.on(
            'update-downloaded',
            (event, releaseNotes, releaseName) => this.notify(UPDATE_DOWNLOADED, {releaseName})
        );
        autoUpdater.on('error', error => {
            logger(error.message);

            request(feedURL, (err, response, body) => {
                if (err) {
                    logger(err.message);
                    return this.notify(UPDATE_ERROR, {error: err.message});
                }

                if (response.statusCode === 200) {
                    const {name, url} = JSON.parse(body);
                    return this.notify(UPDATE_ERROR, {releaseName: name, url});
                }
            });
        });
        autoUpdater.on('checking-for-update', () => this.notify(UPDATE_CHECKING));
        autoUpdater.on('update-not-available', () => this.notify(UPDATE_NOT_AVAILABLE));
        autoUpdater.setFeedURL(feedURL);
        autoUpdater.checkForUpdates();
    }
}

<commit_msg>fix #42 fix window纯净版更新提醒链接错误<commit_after>/**
 * Main Process - 自动更新
 *
 * @file OSXUpdater.js
 * @author mudio(job.mudio@gmail.com)
 */

/* eslint no-underscore-dangle: [2, { "allowAfterThis": true }], no-unused-vars: 0 */

import debug from 'debug';
import * as os from 'os';
import request from 'request';
import {app, autoUpdater} from 'electron';

import {
    UPDATE_ERROR,
    UPDATE_CHECKING,
    UPDATE_AVAILABLE,
    UPDATE_DOWNLOADED,
    UPDATE_NOT_AVAILABLE
} from '../bce/actions/updater';

const logger = debug('bce-client:updater');
const UPDATE_SERVER_HOST = 'bceclient.duapp.com';

export default class OSXUpdater {
    constructor(window) {
        this._window = window;
    }

    notify(title, message) {
        this._window.webContents.send('notify', title, message);
    }

    checkForUpdates() {
        const platform = os.platform();
        const feedURL = `http://${UPDATE_SERVER_HOST}/update/${platform}/${app.getVersion()}`;

        autoUpdater.on('update-available', () => this.notify(UPDATE_AVAILABLE));
        autoUpdater.on(
            'update-downloaded',
            (event, releaseNotes, releaseName) => this.notify(UPDATE_DOWNLOADED, {releaseName})
        );
        autoUpdater.on('error', error => {
            logger(error.message);

            request(feedURL, (err, response, body) => {
                if (err) {
                    logger(err.message);
                    return this.notify(UPDATE_ERROR, {error: err.message});
                }

                if (response.statusCode === 200) {
                    const {name, url} = JSON.parse(body);
                    return this.notify(UPDATE_ERROR, {
                        releaseName: name,
                        url: 'https://cloud.baidu.com/doc/BOS/BOSCLI.html#BOS.E6.A1.8C.E9.9D.A2'
                    });
                }
            });
        });
        autoUpdater.on('checking-for-update', () => this.notify(UPDATE_CHECKING));
        autoUpdater.on('update-not-available', () => this.notify(UPDATE_NOT_AVAILABLE));
        autoUpdater.setFeedURL(feedURL);
        autoUpdater.checkForUpdates();
    }
}

<|endoftext|>


<commit_before>/**
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @format
 */

/* globals Headers, Request, Response */

'use strict';

const whatwg = require('whatwg-fetch');

if (whatwg && whatwg.fetch) {
  module.exports = whatwg;
} else {
  module.exports = {fetch, Headers, Request, Response};
}
<commit_msg>Use fetch as a polyfill<commit_after>/**
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @format
 */

/* globals Headers, Request, Response */

'use strict';

// side-effectful require() to put fetch,
// Headers, Request, Response in global scope
require('whatwg-fetch');

module.exports = {fetch, Headers, Request, Response};
<|endoftext|>


<commit_before>const fs = require('fs')
const path = require('path')
const shallowEqual = require('shallow-equal/arrays')
const config = require('../config')

const expectedDistFiles = [
  'vue-treeselect.js',
  'vue-treeselect.js.map',
  'vue-treeselect.css',
  'vue-treeselect.css.map',
  'vue-treeselect.min.js',
  'vue-treeselect.min.css',
]
const actualFiles = fs.readdirSync(config.bundle.assetsRoot)
if (!shallowEqual(expectedDistFiles.sort(), actualFiles.sort())) {
  throw new Error('Built files are not as expected.')
}

function readFile(fileName) {
  return fs.readFileSync(path.join(config.bundle.assetsRoot, fileName))
}

function shouldReplaceEnvOrNot(expected, fileName) {
  const source = readFile(fileName)
  const actual = !source.includes('process.env.NODE_ENV')
  if (expected !== actual) {
    throw new Error('The bundle file was not built correctly.')
  }
}
shouldReplaceEnvOrNot(false, 'vue-treeselect.js')
shouldReplaceEnvOrNot(true, 'vue-treeselect.min.js')

function shouldReplaceCssEasings(fileName) {
  const source = readFile(fileName)
  return source.includes('cubic-bezier(')
}
shouldReplaceCssEasings('vue-treeselect.css')
shouldReplaceCssEasings('vue-treeselect.min.css')
<commit_msg>fix bundle verification<commit_after>const fs = require('fs')
const path = require('path')
const shallowEqual = require('shallow-equal/arrays')
const config = require('../config')

const expectedDistFiles = [
  'vue-treeselect.js',
  'vue-treeselect.js.map',
  'vue-treeselect.css',
  'vue-treeselect.css.map',
  'vue-treeselect.min.js',
  'vue-treeselect.min.css',
]
const actualFiles = fs.readdirSync(config.bundle.assetsRoot)
if (!shallowEqual(expectedDistFiles.sort(), actualFiles.sort())) {
  throw new Error('Built files are not as expected.')
}

function readFile(fileName) {
  return fs.readFileSync(path.join(config.bundle.assetsRoot, fileName))
}

function shouldReplaceEnvOrNot(expected, fileName) {
  const source = readFile(fileName)
  const actual = !source.includes('process.env.NODE_ENV')
  if (expected !== actual) {
    throw new Error('The bundle file was not built correctly.')
  }
}
shouldReplaceEnvOrNot(false, 'vue-treeselect.js')
shouldReplaceEnvOrNot(true, 'vue-treeselect.min.js')

function shouldReplaceCssEasings(fileName) {
  const source = readFile(fileName)
  if (!source.includes('cubic-bezier(')) {
    throw new Error('The bundle file was not built correctly.')
  }
}
shouldReplaceCssEasings('vue-treeselect.css')
shouldReplaceCssEasings('vue-treeselect.min.css')
<|endoftext|>


<commit_before>var jshint = require('jshint').JSHINT;
var options = require("./options/lint-options.js");
var exclude = require("./options/lint-exclude.js");

module.exports.onFileContent = function (callback, config, fileObject) {
    var result;
    if (exclude.isExcluded(fileObject.path)) {
        fileObject.content = "\n\n" + fileObject.path
                + " excluded from jshint\n--------------------------------------------------------------------\n\n";
    } else {
        result = jshint(fileObject.content, options, {});

        fileObject.content = "\n\n" + fileObject.path
                + " jshint results\n=========================================\n\n";

        if (!result) {
            jshint.errors.forEach(function (result) {
                if (result) {
                    fileObject.content += '[E] line ' + result.line + ', col ' + result.character + ', ' + result.reason
                            + "\n";
                    if (!config.errors) {
                        config.errors = 1;
                    } else {
                        config.errors++;
                    }
                }
            });
        }
    }

    callback();
};

module.exports.onEnd = function (callback, config) {
    if (config.errors) {
        logger.logError("JShint found " + config.errors + " errors in the code! Please check "
                + Object.keys(config.packages)[0] + " for the complete logs");
        // disabled to continue with the build regardless of JSHint warnings:
        process.exit(1);
    } else {
        callback();
    }
};
<commit_msg>Improving readability of JSHint visitor output<commit_after>var jshint = require('jshint').JSHINT;
var options = require("./options/lint-options.js");
var exclude = require("./options/lint-exclude.js");

module.exports.onFileContent = function (callback, config, fileObject) {
    var valid;
    if (exclude.isExcluded(fileObject.path)) {
        fileObject.content = "[SKIP] " + fileObject.path + " excluded from jshint\n";
    } else {
        valid = jshint(fileObject.content, options, {});

        if (valid) {
            fileObject.content = "[OK]   " + fileObject.path + "\n";
        } else {
            fileObject.content = "\n[FAIL] " + fileObject.path + "\n=========================================\n";
            jshint.errors.forEach(function (result) {
                if (result) {
                    fileObject.content += '  [E] line ' + result.line + ', col ' + result.character + ', '
                            + result.reason + "\n";
                    if (!config.errors) {
                        config.errors = 1;
                    } else {
                        config.errors++;
                    }
                }
            });
            fileObject.content += "\n";
        }
    }

    callback();
};

module.exports.onEnd = function (callback, config) {
    if (config.errors) {
        logger.logError("JShint found " + config.errors + " errors in the code! Please check "
                + Object.keys(config.packages)[0] + " for the complete logs");
        // disabled to continue with the build regardless of JSHint warnings:
        process.exit(1);
    } else {
        callback();
    }
};
<|endoftext|>


<commit_before>/* jshint node: true */
'use strict';

require(__dirname + '/../setup');

var mongoose = require('mongoose');

mongoose.connect(process.env.MONGO_DEV_CONNECTION_STRING);
mongoose.connection.on('error', function (err) {
	if (err) {
		console.log(err);
	}
});

var buildUserBase = require(__dirname + '/buildUserBase.js');
var buildRequestBase = require(__dirname + '/buildRequestBase.js');
var clearDatabase = require(__dirname + '/clearDatabase.js');

clearDatabase(function (err) {
	if (err) {
		console.error(err);
	} else {
		buildUserBase(function (err) {
			if (err) {
				console.error(err);
			} else {
				buildRequestBase({}, function (err) {
					if (err) {
						console.error(err);
					} else {
						mongoose.connection.close();
					}
				});
			}
		});
	}
});
<commit_msg>Updated build script to use mongoConnection<commit_after>/* jshint node: true */
'use strict';

require(__dirname + '/../setup');

var mongoose = require('mongoose');
var mongoConnection = require(__dirname + '/../config/mongoConnection');

mongoose.connect(mongoConnection.getConnectionString());
mongoose.connection.on('error', function (err) {
	if (err) {
		console.log(err);
	}
});

var buildUserBase = require(__dirname + '/buildUserBase.js');
var buildRequestBase = require(__dirname + '/buildRequestBase.js');
var clearDatabase = require(__dirname + '/clearDatabase.js');

clearDatabase(function (err) {
	if (err) {
		console.error(err);
	} else {
		buildUserBase(function (err) {
			if (err) {
				console.error(err);
			} else {
				buildRequestBase({}, function (err) {
					if (err) {
						console.error(err);
					} else {
						mongoose.connection.close();
					}
				});
			}
		});
	}
});
<|endoftext|>


<commit_before>var async = require('async')

module.exports = function(req, res) {
  var client = require('redis-url').connect(require('./red'))

  function handleKeys(err, keys) {
    if (err) {
      return res.send(500)
    }

    async.map(keys, function(k, cb) {
      client.ttl(k, function(err, ttl) {
        cb(err, {url: k, ttl: ttl})
      })
    }, function(err, results) {
      if (err) {
        res.send(500)
      } else {
        res.send(results)
      }
    })
  }

  client.keys('*', handleKeys)
}
<commit_msg>Cache list only makes one client<commit_after>var async = require('async')
var client = require('redis-url').connect(require('./red'))

module.exports = function(req, res) {

  function handleKeys(err, keys) {
    if (err) {
      return res.send(500)
    }

    async.map(keys, function(k, cb) {
      client.ttl(k, function(err, ttl) {
        cb(err, {url: k, ttl: ttl})
      })
    }, function(err, results) {
      if (err) {
        res.send(500)
      } else {
        res.send(results)
      }
    })
  }

  client.keys('*', handleKeys)
}
<|endoftext|>


<commit_before>// Copyright (c) 2007-2008 gocept gmbh & co. kg
// See also LICENSE.txt
// $Id$

connect(MochiKit.DragAndDrop.Draggables, 'start', function(draggable) {
    // Generic handler for displaying the drag pane for draggables
    log("Dragging", draggable);
    var drag_pane_url = draggable.element.drag_pane_url;
    if (drag_pane_url == undefined) {
        try {
            var base_url = getFirstElementByTagAndClassName(
             'span', 'URL', draggable.element).textContent;
            drag_pane_url  = base_url + '/@@drag-pane.html';
        } catch (e) {
        }
    }
    if (drag_pane_url == undefined) {
        return;
    }

    var div = getElement('drag-pane');
    if (div) {
        div.parentNode.removeChild(div);
    }
    div = document.createElement('div');
    div.id = 'drag-pane';
    div.dragged_element = draggable.element;

    var content = getElement('body');

    content.appendChild(div);
    draggable.element = div;
    draggable.offset = [0, 0];

    log("Requesting", drag_pane_url);
    var d = doSimpleXMLHttpRequest(drag_pane_url);
    d.addCallbacks(
        function(result) {
            div.innerHTML = result.responseText;
            var unique_id = getElementsByTagAndClassName(
                'div', 'UniqueId', div)[0].textContent;
            div.uniqueId = unique_id;
            return result;
        });
});

connect(MochiKit.DragAndDrop.Draggables, 'end', function(draggable) {
    // Generic handler for hiding the drag pane after dragging ended.
    var element = draggable.element;
    var dragged_element = element.dragged_element;
    if (dragged_element == undefined) return;
    draggable.element = dragged_element;
    MochiKit.Visual.switchOff(element);
});

zeit.cms.TableSorter = Class.extend({
    // Infrastructure to sort tables
    // Reorders the table on the browser.

    construct: function(class_name) {
        var othis = this;
        var table = getFirstElementByTagAndClassName('table', class_name);
        forEach(table.rows, function(row) {
            if (row.cells[0].nodeName == 'TD') {
                new Draggable(row, {
                    ghosting: true
                });
            }

            new Droppable(row, {
                ondrop: function (element) {
                    var tbody = element.parentNode;
                    var before = null;
                    if (row.cells[0].nodeName == 'TH') {
                        before = tbody.firstChild;
                    } else {
                        before = row.nextSibling;
                    }
                    if (before) {
                        tbody.insertBefore(element, before);
                    } else {
                        tbody.appendChild(element);
                    }
                    othis.dropped(element);
                },
                hoverclass: 'tablesort-hover',
            });
        });

    },

    dropped: function(element) {
        // pass
    },
});

var ObjectReferenceWidget = Class.extend({
    // Widget for referencing one object via unique id.
    //
    // This is also thought to be used multiple times in one formlib field,
    // e.g. for Tuple fields.

    construct: function(element, default_browsing_url, type_filter, show_popup) {
        this.element = $(element);
        this.default_browsing_url = default_browsing_url;
        this.type_filter = type_filter;
        this.input = getFirstElementByTagAndClassName(
            'input', 'object-reference', this.element);

        var othis = this;
        new Droppable(this.element, {
            hoverclass: 'drop-widget-hover',
            ondrop: function(element, last_active_element, event) {
                    othis.handleDrop(element);
            },
        });
        connect(element, 'onclick', this, 'handleClick');

        // this saves a click and shows the object browser initially
        if (show_popup)
            this.browseObjects();
    },

    handleDrop: function(element) {
        this.selectObject(element.uniqueId);
    },

    handleClick: function(event) {
        var target = event.target();
        var action;
        var argument;
        if (target.nodeName == 'INPUT' && target.type == 'button') {
            var action = target.getAttribute('name');
        } else if (target.nodeName == 'A') {
            action = "handleNewUrl";
            argument = target.href;
        } else if (target.nodeName == 'TD') {
            var tr = target.parentNode;
            var url_node = getFirstElementByTagAndClassName(
                'span', 'uniqueId', tr);
            if (url_node) {
                action = 'handleObjectSelected';
                argument = url_node.textContent;
            }
        }

        if (action) {
            event.stop();
            var func = bind(action, this);
            func(argument);
        }
    },

    handleNewUrl: function(url) {
        var scroll_state = new ScrollStateRestorer('popup-navtree');
        scroll_state.rememberScrollState();
        this.loadContentFromUrl(url);
    },

    handleObjectSelected: function(unique_id) {
        this.lightbox.close();
        this.selectObject(unique_id);
    },

    browseObjects: function() {
        this.lightbox = new gocept.Lightbox($('body'));
        this.loadContentFromUrl(this.default_browsing_url);
    },

    selectObject: function(unique_id) {
        this.input.value = unique_id;
    },

    loadContentFromUrl: function(url) {
        var d = this.lightbox.load_url(
            url + '/@@get_object_browser',
            {type_filter: this.type_filter});
        var othis = this;
        d.addCallback(function(result) {
            var url = getFirstElementByTagAndClassName(
                'div', 'tree-view-url', othis.lightbox.content_box).innerHTML;
            var navtree = new Tree(url, 'popup-navtree');
            var scroll_state = new ScrollStateRestorer('popup-navtree');
            scroll_state.restoreScrollState();
            return result;
        });
        return d;
    },
});

var ObjectSequenceWidgetBase = Class.extend({

    construct: function(widget_id) {
        var othis = this;
        this.widget_id = widget_id;
        this.element = getElement(widget_id);
        this.ul_element = getFirstElementByTagAndClassName(
            'ul', null, this.element)
        this.initialize();
        connect(this.element, 'onclick', this, 'handleClick');
    },

    initialize: function() {
        var othis = this;
        while (this.ul_element.firstChild != null) {
            removeElement(this.ul_element.firstChild);
        }
        var amount = Number(this.getCountField().value);
        forEach(range(amount), function(i) {
            //var value_name = this.widget_id + '.' + i;
            var title = othis.getTitleField(i).value;
            appendChildNodes(
                othis.ul_element,
                othis.renderElement(i, title));
        });
    },

    renderElement: function(index, title) {
        return LI({'class': 'element', 'index': index},
                  title,
                  IMG({'action': 'delete',
                       'index': index,
                       'src': '/@@/zeit.cms/icons/delete.png'}));
    },

    increaseCount: function() {
        var count_field = this.getCountField()
        var count = Number(count_field.value);
        count_field.value = count + 1;
        return count_field.value;
    },

    decreaseCount: function() {
        var count_field = this.getCountField()
        var count = Number(count_field.value);
        count_field.value = count - 1;
        return count_field.value;
    },

    getCountField: function() {
        return getElement(this.widget_id + '.count')
    },

    getValueField: function(index) {
        return getElement(this.getValueFieldName(index));
    },

    getValueFieldName: function(index) {
        return this.widget_id + '.' + index;
    },

    getTitleField: function(index) {
        return getElement(this.getTitleFieldName(index));
    },

    getTitleFieldName: function(index) {
        return this.widget_id + '.title.' + index;
    },

    add: function(value, title) {
        var next_id = this.increaseCount() - 1;

        var id_field_name = this.getValueFieldName(next_id);
        var title_field_name = this.getTitleFieldName(next_id);

        appendChildNodes(
            this.element,
            INPUT({'type': 'hidden',
                   'name': id_field_name,
                   'id': id_field_name,
                   'value': value}),
            INPUT({'type': 'hidden',
                   'name': title_field_name,
                   'id': title_field_name,
                   'value': title}));
        this.initialize();
    },

    delete: function(index) {
        var othis = this;

        removeElement(this.getValueField(index));
        removeElement(this.getTitleField(index));

        var count_field = this.getCountField();
        var amount = Number(count_field.value)
        var new_index = 0;
        forEach(range(amount), function(iteration_index) {
            var value_field = othis.getValueField(iteration_index)
            var title_field = othis.getTitleField(iteration_index)
            if (value_field == null) {
                return;
            }

            value_field_name = othis.getValueFieldName(new_index);
            value_field.setAttribute('name', value_field_name);
            value_field.setAttribute('id', value_field_name);

            title_field_name = othis.getTitleFieldName(new_index);
            title_field.setAttribute('name', title_field_name);
            title_field.setAttribute('id', title_field_name);

            new_index += 1;
        });
        this.decreaseCount()
        this.initialize();
    },

    handleClick: function(event) {
        var target = event.target();
        var action = target.getAttribute('action');
        var index = target.getAttribute('index');
        if (action && index) {
            var func = bind(action, this);
            func(index);
        }
    },

});

var ObjectSequenceWidget = ObjectSequenceWidgetBase.extend({

    construct: function(widget_id) {
        arguments.callee.$.construct.call(this, widget_id)
        var othis = this;
        new Droppable(this.element, {
            hoverclass: 'drop-widget-hover',
            ondrop: function(element, last_active_element, event) {
                othis.handleDrop(element);
            },
        });
    },

    initialize: function() {
        arguments.callee.$.initialize.call(this);
        var new_li = LI({'class': 'new'},
                        'Weitere Einträge durch Drag and Drop hinzufügen…');
        appendChildNodes(this.ul_element, new_li);
        this.drop_target = new_li;
    },

    handleDrop: function(dragged_element) {
        var unique_id = dragged_element.uniqueId;
        var title_element = getFirstElementByTagAndClassName(
            null, 'Text', dragged_element);
        var title;
        if (title_element == undefined) {
            title = unique_id;
        } else {
            title = scrapeText(title_element)
        }
        arguments.callee.$.add.call(this, unique_id, title);
    },

});

// Connect breadcrumbs
connect(window, 'onload', function(event) {
    var lis = $('breadcrumbs').getElementsByTagName('li');
    forEach(lis, function(li) {
        if (getFirstElementByTagAndClassName('span', 'URL', li) != undefined) {
            new Draggable(li, {
                    starteffect: null,
                    endeffect: null});
        }
    });

});
<commit_msg>connect lightbox onclick correctly<commit_after>// Copyright (c) 2007-2008 gocept gmbh & co. kg
// See also LICENSE.txt
// $Id$

connect(MochiKit.DragAndDrop.Draggables, 'start', function(draggable) {
    // Generic handler for displaying the drag pane for draggables
    log("Dragging", draggable);
    var drag_pane_url = draggable.element.drag_pane_url;
    if (drag_pane_url == undefined) {
        try {
            var base_url = getFirstElementByTagAndClassName(
             'span', 'URL', draggable.element).textContent;
            drag_pane_url  = base_url + '/@@drag-pane.html';
        } catch (e) {
        }
    }
    if (drag_pane_url == undefined) {
        return;
    }

    var div = getElement('drag-pane');
    if (div) {
        div.parentNode.removeChild(div);
    }
    div = document.createElement('div');
    div.id = 'drag-pane';
    div.dragged_element = draggable.element;

    var content = getElement('body');

    content.appendChild(div);
    draggable.element = div;
    draggable.offset = [0, 0];

    log("Requesting", drag_pane_url);
    var d = doSimpleXMLHttpRequest(drag_pane_url);
    d.addCallbacks(
        function(result) {
            div.innerHTML = result.responseText;
            var unique_id = getElementsByTagAndClassName(
                'div', 'UniqueId', div)[0].textContent;
            div.uniqueId = unique_id;
            return result;
        });
});

connect(MochiKit.DragAndDrop.Draggables, 'end', function(draggable) {
    // Generic handler for hiding the drag pane after dragging ended.
    var element = draggable.element;
    var dragged_element = element.dragged_element;
    if (dragged_element == undefined) return;
    draggable.element = dragged_element;
    MochiKit.Visual.switchOff(element);
});

zeit.cms.TableSorter = Class.extend({
    // Infrastructure to sort tables
    // Reorders the table on the browser.

    construct: function(class_name) {
        var othis = this;
        var table = getFirstElementByTagAndClassName('table', class_name);
        forEach(table.rows, function(row) {
            if (row.cells[0].nodeName == 'TD') {
                new Draggable(row, {
                    ghosting: true
                });
            }

            new Droppable(row, {
                ondrop: function (element) {
                    var tbody = element.parentNode;
                    var before = null;
                    if (row.cells[0].nodeName == 'TH') {
                        before = tbody.firstChild;
                    } else {
                        before = row.nextSibling;
                    }
                    if (before) {
                        tbody.insertBefore(element, before);
                    } else {
                        tbody.appendChild(element);
                    }
                    othis.dropped(element);
                },
                hoverclass: 'tablesort-hover',
            });
        });

    },

    dropped: function(element) {
        // pass
    },
});

var ObjectReferenceWidget = Class.extend({
    // Widget for referencing one object via unique id.
    //
    // This is also thought to be used multiple times in one formlib field,
    // e.g. for Tuple fields.

    construct: function(element, default_browsing_url, type_filter, show_popup) {
        this.element = $(element);
        this.default_browsing_url = default_browsing_url;
        this.type_filter = type_filter;
        this.input = getFirstElementByTagAndClassName(
            'input', 'object-reference', this.element);

        var othis = this;
        new Droppable(this.element, {
            hoverclass: 'drop-widget-hover',
            ondrop: function(element, last_active_element, event) {
                    othis.handleDrop(element);
            },
        });
        connect(element, 'onclick', this, 'handleClick');

        // this saves a click and shows the object browser initially
        if (show_popup)
            this.browseObjects();
    },

    handleDrop: function(element) {
        this.selectObject(element.uniqueId);
    },

    handleClick: function(event) {
        var target = event.target();
        var action;
        var argument;
        if (target.nodeName == 'INPUT' && target.type == 'button') {
            var action = target.getAttribute('name');
        } else if (target.nodeName == 'A') {
            action = "handleNewUrl";
            argument = target.href;
        } else if (target.nodeName == 'TD') {
            var tr = target.parentNode;
            var url_node = getFirstElementByTagAndClassName(
                'span', 'uniqueId', tr);
            if (url_node) {
                action = 'handleObjectSelected';
                argument = url_node.textContent;
            }
        }

        if (action) {
            event.stop();
            var func = bind(action, this);
            func(argument);
        }
    },

    handleNewUrl: function(url) {
        var scroll_state = new ScrollStateRestorer('popup-navtree');
        scroll_state.rememberScrollState();
        this.loadContentFromUrl(url);
    },

    handleObjectSelected: function(unique_id) {
        this.lightbox.close();
        this.selectObject(unique_id);
    },

    browseObjects: function() {
        this.lightbox = new gocept.Lightbox($('body'));
        connect(this.lightbox.content_box, 'onclick', this, 'handleClick');
        this.loadContentFromUrl(this.default_browsing_url);
    },

    selectObject: function(unique_id) {
        this.input.value = unique_id;
    },

    loadContentFromUrl: function(url) {
        var d = this.lightbox.load_url(
            url + '/@@get_object_browser',
            {type_filter: this.type_filter});
        var othis = this;
        d.addCallback(function(result) {
            var url = getFirstElementByTagAndClassName(
                'div', 'tree-view-url', othis.lightbox.content_box).innerHTML;
            var navtree = new Tree(url, 'popup-navtree');
            var scroll_state = new ScrollStateRestorer('popup-navtree');
            scroll_state.restoreScrollState();
            return result;
        });
        return d;
    },
});

var ObjectSequenceWidgetBase = Class.extend({

    construct: function(widget_id) {
        var othis = this;
        this.widget_id = widget_id;
        this.element = getElement(widget_id);
        this.ul_element = getFirstElementByTagAndClassName(
            'ul', null, this.element)
        this.initialize();
        connect(this.element, 'onclick', this, 'handleClick');
    },

    initialize: function() {
        var othis = this;
        while (this.ul_element.firstChild != null) {
            removeElement(this.ul_element.firstChild);
        }
        var amount = Number(this.getCountField().value);
        forEach(range(amount), function(i) {
            //var value_name = this.widget_id + '.' + i;
            var title = othis.getTitleField(i).value;
            appendChildNodes(
                othis.ul_element,
                othis.renderElement(i, title));
        });
    },

    renderElement: function(index, title) {
        return LI({'class': 'element', 'index': index},
                  title,
                  IMG({'action': 'delete',
                       'index': index,
                       'src': '/@@/zeit.cms/icons/delete.png'}));
    },

    increaseCount: function() {
        var count_field = this.getCountField()
        var count = Number(count_field.value);
        count_field.value = count + 1;
        return count_field.value;
    },

    decreaseCount: function() {
        var count_field = this.getCountField()
        var count = Number(count_field.value);
        count_field.value = count - 1;
        return count_field.value;
    },

    getCountField: function() {
        return getElement(this.widget_id + '.count')
    },

    getValueField: function(index) {
        return getElement(this.getValueFieldName(index));
    },

    getValueFieldName: function(index) {
        return this.widget_id + '.' + index;
    },

    getTitleField: function(index) {
        return getElement(this.getTitleFieldName(index));
    },

    getTitleFieldName: function(index) {
        return this.widget_id + '.title.' + index;
    },

    add: function(value, title) {
        var next_id = this.increaseCount() - 1;

        var id_field_name = this.getValueFieldName(next_id);
        var title_field_name = this.getTitleFieldName(next_id);

        appendChildNodes(
            this.element,
            INPUT({'type': 'hidden',
                   'name': id_field_name,
                   'id': id_field_name,
                   'value': value}),
            INPUT({'type': 'hidden',
                   'name': title_field_name,
                   'id': title_field_name,
                   'value': title}));
        this.initialize();
    },

    delete: function(index) {
        var othis = this;

        removeElement(this.getValueField(index));
        removeElement(this.getTitleField(index));

        var count_field = this.getCountField();
        var amount = Number(count_field.value)
        var new_index = 0;
        forEach(range(amount), function(iteration_index) {
            var value_field = othis.getValueField(iteration_index)
            var title_field = othis.getTitleField(iteration_index)
            if (value_field == null) {
                return;
            }

            value_field_name = othis.getValueFieldName(new_index);
            value_field.setAttribute('name', value_field_name);
            value_field.setAttribute('id', value_field_name);

            title_field_name = othis.getTitleFieldName(new_index);
            title_field.setAttribute('name', title_field_name);
            title_field.setAttribute('id', title_field_name);

            new_index += 1;
        });
        this.decreaseCount()
        this.initialize();
    },

    handleClick: function(event) {
        var target = event.target();
        var action = target.getAttribute('action');
        var index = target.getAttribute('index');
        if (action && index) {
            var func = bind(action, this);
            func(index);
        }
    },

});

var ObjectSequenceWidget = ObjectSequenceWidgetBase.extend({

    construct: function(widget_id) {
        arguments.callee.$.construct.call(this, widget_id)
        var othis = this;
        new Droppable(this.element, {
            hoverclass: 'drop-widget-hover',
            ondrop: function(element, last_active_element, event) {
                othis.handleDrop(element);
            },
        });
    },

    initialize: function() {
        arguments.callee.$.initialize.call(this);
        var new_li = LI({'class': 'new'},
                        'Weitere Einträge durch Drag and Drop hinzufügen…');
        appendChildNodes(this.ul_element, new_li);
        this.drop_target = new_li;
    },

    handleDrop: function(dragged_element) {
        var unique_id = dragged_element.uniqueId;
        var title_element = getFirstElementByTagAndClassName(
            null, 'Text', dragged_element);
        var title;
        if (title_element == undefined) {
            title = unique_id;
        } else {
            title = scrapeText(title_element)
        }
        arguments.callee.$.add.call(this, unique_id, title);
    },

});

// Connect breadcrumbs
connect(window, 'onload', function(event) {
    var lis = $('breadcrumbs').getElementsByTagName('li');
    forEach(lis, function(li) {
        if (getFirstElementByTagAndClassName('span', 'URL', li) != undefined) {
            new Draggable(li, {
                    starteffect: null,
                    endeffect: null});
        }
    });

});
<|endoftext|>


<commit_before>/*
 * Copyright 2013 Amadeus s.a.s.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

var seleniumJavaRobot = require("selenium-java-robot").exec;
var registerChildProcess = require("../util/child-processes").register;
var attester = require("../attester");
var robotProcess = null;

/**
 * Launcher for the robot browser specified on the command line.
 */

function onLauncherConnect(slaveURL) {
    var robotBrowser = attester.config["robot-browser"];
    if (robotBrowser) {
        var args = ["--url", slaveURL, "--browser", robotBrowser, "--auto-restart"];
        robotProcess = seleniumJavaRobot(args, {
            stdio: "pipe"
        });
        registerChildProcess(robotProcess);
        robotProcess.stdout.pipe(process.stdout);
        robotProcess.stderr.pipe(process.stderr);
    }
}

module.exports = {
    __init__: function () {
        attester.event.on("launcher.connect", onLauncherConnect);
    },
    __reset__: function () {
        if (robotProcess) {
            // this notifies the robot process that it should close the browser:
            robotProcess.stdin.end();
            robotProcess = null;
        }
        attester.event.off("launcher.connect", onLauncherConnect);
    }
};
<commit_msg>Deprecating --robot-browser.<commit_after>/*
 * Copyright 2013 Amadeus s.a.s.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

var seleniumJavaRobot = require("selenium-java-robot").exec;
var registerChildProcess = require("../util/child-processes").register;
var attester = require("../attester");
var robotProcess = null;

/**
 * Launcher for the robot browser specified on the command line.
 */

function onLauncherConnect(slaveURL) {
    var robotBrowser = attester.config["robot-browser"];
    if (robotBrowser) {
        attester.logger.logWarn("The --robot-browser option is deprecated. Please consider using --launcher-config along with https://github.com/attester/robot-server instead.");
        var args = ["--url", slaveURL, "--browser", robotBrowser, "--auto-restart"];
        robotProcess = seleniumJavaRobot(args, {
            stdio: "pipe"
        });
        registerChildProcess(robotProcess);
        robotProcess.stdout.pipe(process.stdout);
        robotProcess.stderr.pipe(process.stderr);
    }
}

module.exports = {
    __init__: function () {
        attester.event.on("launcher.connect", onLauncherConnect);
    },
    __reset__: function () {
        if (robotProcess) {
            // this notifies the robot process that it should close the browser:
            robotProcess.stdin.end();
            robotProcess = null;
        }
        attester.event.off("launcher.connect", onLauncherConnect);
    }
};
<|endoftext|>