<commit_before>var utils = require('./utils')
var storage = require('./storage')

function Config () {
  this.config = {}
  this.defaults = {
    VERSION: this.VERSION,
    orgId: null,
    appId: null,
    token: null,
    context: {
      user: {
        uuid: _generateUUID()
      },
      extra: null
    }
  }
}

Config.prototype.init = function () {
  var scriptData = _getConfigFromScript()

  this.setConfig(scriptData)
}

Config.prototype.get = function (key) {
  return key.split('.').reduce(function (obj, i) {
    return obj[i]
  }, this.config)
},

Config.prototype.set = function (key, value) {
  var levels = key.split('.')
  var max_level = levels.length - 1
  var target = this.config

  levels.some(function (level, i) {
    if (typeof level === 'undefined') {
      return true
    }
    if (i === max_level) {
      target[level] = value
    } else {
      var obj = target[level] || {}
      target[level] = obj
      target = obj
    }
  })
},

Config.prototype.setConfig = function (properties) {
  properties = properties || {}
  this.config = utils.mergeObject(this.defaults, properties)
}

Config.prototype.isValid = function () {
  var requiredKeys = ['appId', 'orgId', 'token']
  var values = requiredKeys.map(function (key) {
    return this.config[key] === undefined
  }.bind(this))

  return values.indexOf(true) === -1
}

function _generateUUID() {

  var key = 'opbeat-uuid';
  var uuid = storage.get(key);

  if(!uuid) {
    uuid = utils.generateUuid();
    storage.set(key, uuid)
  }

  return uuid;
}

var _getConfigFromScript = function () {
  var script = utils.getCurrentScript()
  var config = _getDataAttributesFromNode(script)
  return config
}

function _getDataAttributesFromNode (node) {
  var dataAttrs = {}
  var dataRegex = /^data\-([\w\-]+)$/

  if (node) {
    var attrs = node.attributes
    for (var i = 0; i < attrs.length; i++) {
      var attr = attrs[i]
      if (dataRegex.test(attr.nodeName)) {
        var key = attr.nodeName.match(dataRegex)[1]

        // camelCase key
        key = key.split('-').map(function (group, index) {
          return index > 0 ? group.charAt(0).toUpperCase() + group.substring(1) : group
        }).join('')

        dataAttrs[key] = attr.value || attr.nodeValue
      }
    }
  }

  return dataAttrs
}

module.exports = new Config()
<commit_msg>Add apiHost to default config<commit_after>var utils = require('./utils')
var storage = require('./storage')

function Config () {
  this.config = {}
  this.defaults = {
    VERSION: this.VERSION,
    apiHost: 'intake.opbeat.com',
    orgId: null,
    appId: null,
    token: null,
    context: {
      user: {
        uuid: _generateUUID()
      },
      extra: null
    }
  }
}

Config.prototype.init = function () {
  var scriptData = _getConfigFromScript()

  this.setConfig(scriptData)
}

Config.prototype.get = function (key) {
  return key.split('.').reduce(function (obj, i) {
    return obj[i]
  }, this.config)
},

Config.prototype.set = function (key, value) {
  var levels = key.split('.')
  var max_level = levels.length - 1
  var target = this.config

  levels.some(function (level, i) {
    if (typeof level === 'undefined') {
      return true
    }
    if (i === max_level) {
      target[level] = value
    } else {
      var obj = target[level] || {}
      target[level] = obj
      target = obj
    }
  })
},

Config.prototype.setConfig = function (properties) {
  properties = properties || {}
  this.config = utils.mergeObject(this.defaults, properties)
}

Config.prototype.isValid = function () {
  var requiredKeys = ['appId', 'orgId', 'token']
  var values = requiredKeys.map(function (key) {
    return this.config[key] === undefined
  }.bind(this))

  return values.indexOf(true) === -1
}

function _generateUUID() {

  var key = 'opbeat-uuid';
  var uuid = storage.get(key);

  if(!uuid) {
    uuid = utils.generateUuid();
    storage.set(key, uuid)
  }

  return uuid;
}

var _getConfigFromScript = function () {
  var script = utils.getCurrentScript()
  var config = _getDataAttributesFromNode(script)
  return config
}

function _getDataAttributesFromNode (node) {
  var dataAttrs = {}
  var dataRegex = /^data\-([\w\-]+)$/

  if (node) {
    var attrs = node.attributes
    for (var i = 0; i < attrs.length; i++) {
      var attr = attrs[i]
      if (dataRegex.test(attr.nodeName)) {
        var key = attr.nodeName.match(dataRegex)[1]

        // camelCase key
        key = key.split('-').map(function (group, index) {
          return index > 0 ? group.charAt(0).toUpperCase() + group.substring(1) : group
        }).join('')

        dataAttrs[key] = attr.value || attr.nodeValue
      }
    }
  }

  return dataAttrs
}

module.exports = new Config()
<|endoftext|>


<commit_before>var StreamClient = require('./client');
var StreamFeed = require('./feed');
var StreamCollection = require('./collection');
var StreamReaction = require('./reaction');

StreamClient.prototype.collection = function(name, token) {
  return new StreamCollection(this, name, token);
};

StreamClient.prototype.reactions = function(token) {
  return new StreamReaction(this, token);
};

StreamFeed.prototype.getEnriched = function(options, callback) {
    /**
     * Reads the feed
     * @method getEnriched
     * @memberof StreamFeed.prototype
     * @param  {object}   options  Additional options
     * @param  {requestCallback} callback Callback to call on completion
     * @return {Promise} Promise object
     * @example feed.getEnriched({limit: 10, id_lte: 'activity-id'})
     * @example feed.getEnriched({limit: 10, mark_seen: true})
     */
     return this.get(options, callback, 'enrich/');
};
<commit_msg>add some examples for getEnriched<commit_after>var StreamClient = require('./client');
var StreamFeed = require('./feed');
var StreamCollection = require('./collection');
var StreamReaction = require('./reaction');

StreamClient.prototype.collection = function(name, token) {
  return new StreamCollection(this, name, token);
};

StreamClient.prototype.reactions = function(token) {
  return new StreamReaction(this, token);
};

StreamFeed.prototype.getEnriched = function(options, callback) {
    /**
     * Reads the feed
     * @method getEnriched
     * @memberof StreamFeed.prototype
     * @param  {object}   options  Additional options
     * @param  {requestCallback} callback Callback to call on completion
     * @return {Promise} Promise object
     * @example feed.getEnriched({limit: 10, id_lte: 'activity-id'})
     * @example feed.getEnriched({limit: 10, mark_seen: true})
     * @example feed.getEnriched({limit: 10, mark_seen: true, withRecentReactions: true})
     * @example feed.getEnriched({limit: 10, mark_seen: true, withReactionCounts: true})
     * @example feed.getEnriched({limit: 10, mark_seen: true, withOwnReactions: true, withReactionCounts: true})
     */
     return this.get(options, callback, 'enrich/');
};
<|endoftext|>


<commit_before>var zlib = require('zlib');
var EventEmitter = require('events').EventEmitter;
var uuid = require('hat');

// voxel dependencies
var Coordinates = require('./coordinates');
var HLRU = require('hashlru');
var debug = false;

function getRandomInt(min, max) {
    return Math.floor(Math.random() * (max - min)) + min;
}

var sendMessage = function(websocket, name, payload) {
    websocket.send( JSON.stringify([name, payload]) );
};

module.exports = Server;

function Server(config, clientSettings, chunkStore, wsServer, httpServer) {
    // force instantiation via `new` keyword
    //if(!(this instanceof Server)) { return new Server(serverSettings || {}, clientSettings || {}) }
    this.config = config;
    this.clientSettings = clientSettings;
    this.chunkStore = chunkStore;
    this.wsServer = wsServer;
    this.httpServer = httpServer;

    var chunkSize = config.chunkSize;
    var origin = [0, 0, 0];
    var step = chunkSize * config.worldRadius;
    this.lastWorldChunks = [
        // Lower chunk
        origin[0] - step,
        origin[1] - step,
        origin[2] - step,

        // Farther chunk
        origin[0] + step,
        origin[1] + step,
        origin[2] + step
    ];
    this.initialize();
};

Server.prototype.initialize = function() {
    var self = this;
    this.clients = {};
    this.emitter = new EventEmitter();
    this.coords = Coordinates(self.config.chunkSize);

    this.encodedChunkCache = new HLRU(10);

    // Prime our chunk store or LRU
    //self.requestNearbyChunks(this.clientSettings.initialPosition);

    // send player position/rotation updates
    setInterval(function() {
        self.sendPlayers();
    }, 1000 / 3);

    // Handle requests for chunk voxels
    self.httpServer.on('request', function(request, response) {
        var url = require('url').parse(request.url);
        var path = decodeURIComponent(url.path);
        if (path.substr(0, 7) == '/chunk/') {
            var chunkId = path.substr(7);
            if (!chunkId) {
                response.end();
                return;
            }
            // Bail if someone requested a chunk outside our world radius
            if (!self.isChunkInBounds(chunkId)) {
                response.end();
                return;
            }
            self.chunkStore.get(chunkId, function(error, chunk) {
                var acceptEncoding = request.headers['accept-encoding'] || '';

                // Note: This is not a conformant accept-encoding parser.
                // See https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.3
                if (/\bgzip\b/.test(acceptEncoding)) {
                    response.writeHead(200, { 'Content-Type': 'application/octet-stream', 'Content-Encoding': 'gzip', 'Access-Control-Allow-Origin': '*' });
                    if ('compressedVoxels' in chunk && chunk.compressedVoxels) {
                        response.end( chunk.compressedVoxels );
                    } else {
                        response.end( zlib.gzipSync(chunk.voxels) );
                    }
                } else {
                    response.writeHead(200, {});
                    response.end( chunk.voxels );
                }
            });
        }
    });

    self.wsServer.on('connection', function(connection) {
        var id = uuid();
        self.clients[id] = {
            id: id,
            // This gets updated when we get their position updates
            // Server should remove stale clients
            lastSeen: 0,
            connected: true,
            connection: connection,
            avatar: 'player',
            position: null,
            yaw: 0,
            pitch: 0,

            // The chunk ids this client cares about
            onlyTheseChunks: []
        };

        connection.on('error', function(message) {
            console.log('Client connection error: ' + message);
        });

        connection.on('end', function() {
            self.clients[id].connected = false;
        });

        connection.on('close', function(error) {
            self.clients[id].connected = false;
            delete self.clients[id];
        });

        connection.on('message', function(message) {
            // Decode message
            // Handle errors and exceptions
            var client = self.clients[id];
            var decoded = JSON.parse(message);
            var type = decoded[0];
            var payload = decoded[1];
            switch (type) {
                case 'chat':
                    // ignore if no message provided
                    if (!payload.text) return;
                    if (payload.text.match(/script/i)) {
                        console.log('Found script tag in message. Dropping');
                        return;
                    }
                    // limit chat message length
                    if (payload.text.length > 255) payload.text = payload.text.substr(0, 140);
                    self.broadcast(null, 'chat', payload);
                    self.emitter.emit('chat', payload);
                    break;

                // when user ready ( game created, etc )
                case 'created':
                    // emit client.created for module consumers
                    self.emitter.emit('client.created', payload);
                    break;
                case 'myPosition':
                    // client sends new position, rotation
                    //connection.on('myPosition', function(position, yaw, pitch, avatar) {
                    client.position = payload[0];
                    client.yaw = payload[1];
                    client.pitch = payload[2];
                    client.avatar = payload[3];
                    self.emitter.emit('client.state', client);
                    break;

                // Client sent us voxel changes for one or more chunks
                case 'chunkVoxelIndexValue':
                    var changes = payload;
                    // Update our chunk store
                    self.chunkStore.gotChunkChanges(changes);

                    // Re-broadcast this to the other players, too
                    for (var chunkId in changes) {
                        var chunkChanges = {};
                        if (!self.isChunkInBounds(chunkId)) {
                            continue;
                        }
                        chunkChanges[chunkId] = changes[chunkId];

                        self.encodedChunkCache.remove(chunkId);
                        for (var clientId in self.clients) {
                            var client;
                            var connection;
                            // Don't broadcast to the client that sent us the info
                            if (clientId === id) {
                                continue;
                            }
                            client = self.clients[clientId];
                            if (!client.connected) {
                                continue;
                            }
                            if (debug) {
                                console.log('sending to', clientId, args);
                            }
                            // emit over connection
                            sendMessage(client.connection, 'chunkVoxelIndexValue', chunkChanges);
                        }
                    }
                    break;

                // Client tells us which chunks it wants to hear about
                case 'onlyTheseChunks':
                    if (debug) {
                        console.log('Client only cares about these chunks', payload);
                    }
                    self.clients[id].onlyTheseChunks = payload;
                    break;
                default:
                    if (debug) {
                        console.log('Unexpected WebSocket message: ', decoded);
                    }
                    break;
            }
        });

        sendMessage(connection, 'settings', {id: id, settings: self.clientSettings});
    });
};

// send message to all clients
Server.prototype.broadcast = function(id, event, payload) {
    var self = this;
    for (var clientId in self.clients) {
        var client;
        var connection;
        // Don't broadcast to the client that sent us the info
        if (clientId === id) {
            continue;
        }
        client = self.clients[clientId];
        if (!client.connected) {
            continue;
        }
        if (debug) {
            console.log('sending to', clientId, payload);
        }
        // emit over connection
        sendMessage(client.connection, event, payload);
    }
};

// broadcast position, rotation updates for each player
Server.prototype.sendPlayers = function() {
    var self = this;
    var clientIds = Object.keys(self.clients);
    if (clientIds.length === 0) {
        return;
    }
    //console.log('Sending updates for ' + clientIds.length + ' clients')
    var players = {};

    clientIds.map(function(id) {
        var client = self.clients[id];
        if (!client.position) {
            return;
        }
        // TODO: Ignore client if they're really stale
        players[id] = {
            positions: [
                client.position[0],
                client.position[1],
                client.position[2],
                client.pitch,
                client.yaw,
                0
            ],
            avatar: client.avatar
        };
    });

    self.broadcast(null, 'players', players);
};

Server.prototype.requestNearbyChunks = function(position) {
    var self = this;
    this.coords.nearbyChunkIDsEach(position, 2, function(chunkID) {
        self.chunkStore.get(chunkID);
    });
};

Server.prototype.isChunkInBounds = function(chunkID) {
    var self = this;
    var position = chunkID.split('|').map(function(value) {
        return Number(value);
    });
    if (position[0] < self.lastWorldChunks[0] || position[1] < self.lastWorldChunks[1] || position[2] < self.lastWorldChunks[2] || position[0] > self.lastWorldChunks[3] || position[1] > self.lastWorldChunks[4] || position[2] > self.lastWorldChunks[5]) {
        return false;
    }
    return true;
};

Server.prototype.on = function(name, callback) {
    this.emitter.on(name, callback);
};
<commit_msg>use nocache for gzip assets<commit_after>var zlib = require('zlib');
var EventEmitter = require('events').EventEmitter;
var uuid = require('hat');

// voxel dependencies
var Coordinates = require('./coordinates');
var HLRU = require('hashlru');
var debug = false;

function getRandomInt(min, max) {
    return Math.floor(Math.random() * (max - min)) + min;
}

var sendMessage = function(websocket, name, payload) {
    websocket.send( JSON.stringify([name, payload]) );
};

module.exports = Server;

function Server(config, clientSettings, chunkStore, wsServer, httpServer) {
    // force instantiation via `new` keyword
    //if(!(this instanceof Server)) { return new Server(serverSettings || {}, clientSettings || {}) }
    this.config = config;
    this.clientSettings = clientSettings;
    this.chunkStore = chunkStore;
    this.wsServer = wsServer;
    this.httpServer = httpServer;

    var chunkSize = config.chunkSize;
    var origin = [0, 0, 0];
    var step = chunkSize * config.worldRadius;
    this.lastWorldChunks = [
        // Lower chunk
        origin[0] - step,
        origin[1] - step,
        origin[2] - step,

        // Farther chunk
        origin[0] + step,
        origin[1] + step,
        origin[2] + step
    ];
    this.initialize();
};

Server.prototype.initialize = function() {
    var self = this;
    this.clients = {};
    this.emitter = new EventEmitter();
    this.coords = Coordinates(self.config.chunkSize);

    this.encodedChunkCache = new HLRU(10);

    // Prime our chunk store or LRU
    //self.requestNearbyChunks(this.clientSettings.initialPosition);

    // send player position/rotation updates
    setInterval(function() {
        self.sendPlayers();
    }, 1000 / 3);

    // Handle requests for chunk voxels
    self.httpServer.on('request', function(request, response) {
        var url = require('url').parse(request.url);
        var path = decodeURIComponent(url.path);
        if (path.substr(0, 7) == '/chunk/') {
            var chunkId = path.substr(7);
            if (!chunkId) {
                response.end();
                return;
            }
            // Bail if someone requested a chunk outside our world radius
            if (!self.isChunkInBounds(chunkId)) {
                response.end();
                return;
            }
            self.chunkStore.get(chunkId, function(error, chunk) {
                var acceptEncoding = request.headers['accept-encoding'] || '';

                // Note: This is not a conformant accept-encoding parser.
                // See https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.3
                if (/\bgzip\b/.test(acceptEncoding)) {
                    response.writeHead(
                        200,
                        {
                            'Content-Type': 'application/octet-stream',
                            'Content-Encoding': 'gzip',
                            'Access-Control-Allow-Origin': '*',
                            'Cache-Control': 'no-cache'
                        }
                    );
                    if ('compressedVoxels' in chunk && chunk.compressedVoxels) {
                        response.end( chunk.compressedVoxels );
                    } else {
                        response.end( zlib.gzipSync(chunk.voxels) );
                    }
                } else {
                    response.writeHead(200, {});
                    response.end( chunk.voxels );
                }
            });
        }
    });

    self.wsServer.on('connection', function(connection) {
        var id = uuid();
        self.clients[id] = {
            id: id,
            // This gets updated when we get their position updates
            // Server should remove stale clients
            lastSeen: 0,
            connected: true,
            connection: connection,
            avatar: 'player',
            position: null,
            yaw: 0,
            pitch: 0,

            // The chunk ids this client cares about
            onlyTheseChunks: []
        };

        connection.on('error', function(message) {
            console.log('Client connection error: ' + message);
        });

        connection.on('end', function() {
            self.clients[id].connected = false;
        });

        connection.on('close', function(error) {
            self.clients[id].connected = false;
            delete self.clients[id];
        });

        connection.on('message', function(message) {
            // Decode message
            // Handle errors and exceptions
            var client = self.clients[id];
            var decoded = JSON.parse(message);
            var type = decoded[0];
            var payload = decoded[1];
            switch (type) {
                case 'chat':
                    // ignore if no message provided
                    if (!payload.text) return;
                    if (payload.text.match(/script/i)) {
                        console.log('Found script tag in message. Dropping');
                        return;
                    }
                    // limit chat message length
                    if (payload.text.length > 255) payload.text = payload.text.substr(0, 140);
                    self.broadcast(null, 'chat', payload);
                    self.emitter.emit('chat', payload);
                    break;

                // when user ready ( game created, etc )
                case 'created':
                    // emit client.created for module consumers
                    self.emitter.emit('client.created', payload);
                    break;
                case 'myPosition':
                    // client sends new position, rotation
                    //connection.on('myPosition', function(position, yaw, pitch, avatar) {
                    client.position = payload[0];
                    client.yaw = payload[1];
                    client.pitch = payload[2];
                    client.avatar = payload[3];
                    self.emitter.emit('client.state', client);
                    break;

                // Client sent us voxel changes for one or more chunks
                case 'chunkVoxelIndexValue':
                    var changes = payload;
                    // Update our chunk store
                    self.chunkStore.gotChunkChanges(changes);

                    // Re-broadcast this to the other players, too
                    for (var chunkId in changes) {
                        var chunkChanges = {};
                        if (!self.isChunkInBounds(chunkId)) {
                            continue;
                        }
                        chunkChanges[chunkId] = changes[chunkId];

                        self.encodedChunkCache.remove(chunkId);
                        for (var clientId in self.clients) {
                            var client;
                            var connection;
                            // Don't broadcast to the client that sent us the info
                            if (clientId === id) {
                                continue;
                            }
                            client = self.clients[clientId];
                            if (!client.connected) {
                                continue;
                            }
                            if (debug) {
                                console.log('sending to', clientId, args);
                            }
                            // emit over connection
                            sendMessage(client.connection, 'chunkVoxelIndexValue', chunkChanges);
                        }
                    }
                    break;

                // Client tells us which chunks it wants to hear about
                case 'onlyTheseChunks':
                    if (debug) {
                        console.log('Client only cares about these chunks', payload);
                    }
                    self.clients[id].onlyTheseChunks = payload;
                    break;
                default:
                    if (debug) {
                        console.log('Unexpected WebSocket message: ', decoded);
                    }
                    break;
            }
        });

        sendMessage(connection, 'settings', {id: id, settings: self.clientSettings});
    });
};

// send message to all clients
Server.prototype.broadcast = function(id, event, payload) {
    var self = this;
    for (var clientId in self.clients) {
        var client;
        var connection;
        // Don't broadcast to the client that sent us the info
        if (clientId === id) {
            continue;
        }
        client = self.clients[clientId];
        if (!client.connected) {
            continue;
        }
        if (debug) {
            console.log('sending to', clientId, payload);
        }
        // emit over connection
        sendMessage(client.connection, event, payload);
    }
};

// broadcast position, rotation updates for each player
Server.prototype.sendPlayers = function() {
    var self = this;
    var clientIds = Object.keys(self.clients);
    if (clientIds.length === 0) {
        return;
    }
    //console.log('Sending updates for ' + clientIds.length + ' clients')
    var players = {};

    clientIds.map(function(id) {
        var client = self.clients[id];
        if (!client.position) {
            return;
        }
        // TODO: Ignore client if they're really stale
        players[id] = {
            positions: [
                client.position[0],
                client.position[1],
                client.position[2],
                client.pitch,
                client.yaw,
                0
            ],
            avatar: client.avatar
        };
    });

    self.broadcast(null, 'players', players);
};

Server.prototype.requestNearbyChunks = function(position) {
    var self = this;
    this.coords.nearbyChunkIDsEach(position, 2, function(chunkID) {
        self.chunkStore.get(chunkID);
    });
};

Server.prototype.isChunkInBounds = function(chunkID) {
    var self = this;
    var position = chunkID.split('|').map(function(value) {
        return Number(value);
    });
    if (position[0] < self.lastWorldChunks[0] || position[1] < self.lastWorldChunks[1] || position[2] < self.lastWorldChunks[2] || position[0] > self.lastWorldChunks[3] || position[1] > self.lastWorldChunks[4] || position[2] > self.lastWorldChunks[5]) {
        return false;
    }
    return true;
};

Server.prototype.on = function(name, callback) {
    this.emitter.on(name, callback);
};
<|endoftext|>


<commit_before>import shell from 'shelljs'
import chalk from 'chalk'
import omit from 'lodash.omit'
import map from 'lodash.map'
import gitUrlParser from 'git-url-parse'
import fs from 'fs'
import waterfall from 'async-waterfall'

const log = {
  info (msg) {
    console.log(chalk.cyan(msg))
  },
  error (msg) {
    console.log(chalk.bold.underline.red('Error'), '\r\n', chalk.red(msg))
  },
  warn (msg) {
    console.log(chalk.yellow(msg))
  },
  success (msg) {
    console.log(chalk.green(msg))
  }
}

function isGitInstalled () {
  return shell.which('git')
}

function gotoRootDirectory (done) {
  shell.exec('git rev-parse --show-toplevel', {
    silent: true,
    async: true
  }, function cwdToRootCompleted (exitCode, output) {
    var trimmedOutput = output.trim()

    if (exitCode) {
      return done(output)
    }

    shell.cd(trimmedOutput, {
      silent: true
    })

    return done(null, trimmedOutput)
  })
}

function listPackageJsonFiles (branch, base, done) {
  var listArray
  listArray = shell.exec('git ls-tree -r ' +
    '--name-only ' + branch +
    '  | grep \'package.json\'', { silent: true })
    .stdout
    .trim()
    .replace(/(\r\n|\n|\r)/gm, ',')
    .split(',')
    .map(function addBasePath (path) {
      return base + '/' + path.replace('package.json', ' ').trim()
    })

  return done(null, listArray)
}

function getRepoName (repoUrl) {
  return gitUrlParser(repoUrl).name
}

function isGitRepo () {
  return shell.exec('git rev-parse --is-inside-work-tree', {
    silent: true
  }).stdout.trim()
}

function currentBranchName () {
  return shell.exec('git rev-parse --abbrev-ref HEAD', {
    silent: true
  }).stdout.trim()
}

function checkOutBranch (branch) {
  shell.exec('git checkout ' + branch, {
    silent: true
  }).stdout.trim()
  return branch
}

function prepareArguments (args) {
  var gitOptions = omit(args, [
    '$0',
    'h',
    'help',
    '_',
    'b',
    'debug',
    'version',
    'v',
    'branch',
    'repo',
    'repository'
  ])

  return map(gitOptions, function appendBasePath (value, key) {
    if (typeof value === 'boolean' && !value) {
      return
    }

    if (typeof value === 'boolean' && value) {
      if (key === 'd') { key = 'v' }
      return key.length > 1 ? '--' + key : '-' + key
    } else {
      return key.length > 1 ? '--' + key + ' ' + value : '-' + key + ' ' + value
    }
  }).join(' ')
}

function packagePaths (branchName, cb) {
  waterfall([
    gotoRootDirectory, (basePath, callback) => {
      return listPackageJsonFiles(branchName, basePath, callback)
    }
  ], (err, paths) => {
    if (err) {
      return cb(err)
    }
    return cb(null, paths)
  })
}

const Utils = {
  isGitInstalled,
  isGitRepo,
  prepareArguments,
  getRepoName,
  log,
  packagePaths,
  checkOutBranch,
  currentBranchName,
  isExists: fs.stat
}

export default Utils
<commit_msg>adds checking yarn installation function in utils<commit_after>import shell from 'shelljs'
import chalk from 'chalk'
import omit from 'lodash.omit'
import map from 'lodash.map'
import gitUrlParser from 'git-url-parse'
import fs from 'fs'
import waterfall from 'async-waterfall'

const log = {
  info (msg) {
    console.log(chalk.cyan(msg))
  },
  error (msg) {
    console.log(chalk.bold.underline.red('Error'), '\r\n', chalk.red(msg))
  },
  warn (msg) {
    console.log(chalk.yellow(msg))
  },
  success (msg) {
    console.log(chalk.green(msg))
  }
}

function isGitInstalled () {
  return shell.which('git')
}

function isYarnInstalled () {
  return shell.which('yarn')
}

function gotoRootDirectory (done) {
  shell.exec('git rev-parse --show-toplevel', {
    silent: true,
    async: true
  }, function cwdToRootCompleted (exitCode, output) {
    var trimmedOutput = output.trim()

    if (exitCode) {
      return done(output)
    }

    shell.cd(trimmedOutput, {
      silent: true
    })

    return done(null, trimmedOutput)
  })
}

function listPackageJsonFiles (branch, base, done) {
  var listArray
  listArray = shell.exec('git ls-tree -r ' +
    '--name-only ' + branch +
    '  | grep \'package.json\'', { silent: true })
    .stdout
    .trim()
    .replace(/(\r\n|\n|\r)/gm, ',')
    .split(',')
    .map(function addBasePath (path) {
      return base + '/' + path.replace('package.json', ' ').trim()
    })

  return done(null, listArray)
}

function getRepoName (repoUrl) {
  return gitUrlParser(repoUrl).name
}

function isGitRepo () {
  return shell.exec('git rev-parse --is-inside-work-tree', {
    silent: true
  }).stdout.trim()
}

function currentBranchName () {
  return shell.exec('git rev-parse --abbrev-ref HEAD', {
    silent: true
  }).stdout.trim()
}

function checkOutBranch (branch) {
  shell.exec('git checkout ' + branch, {
    silent: true
  }).stdout.trim()
  return branch
}

function prepareArguments (args) {
  var gitOptions = omit(args, [
    '$0',
    'h',
    'help',
    '_',
    'b',
    'debug',
    'version',
    'v',
    'branch',
    'repo',
    'repository'
  ])

  return map(gitOptions, function appendBasePath (value, key) {
    if (typeof value === 'boolean' && !value) {
      return
    }

    if (typeof value === 'boolean' && value) {
      if (key === 'd') { key = 'v' }
      return key.length > 1 ? '--' + key : '-' + key
    } else {
      return key.length > 1 ? '--' + key + ' ' + value : '-' + key + ' ' + value
    }
  }).join(' ')
}

function packagePaths (branchName, cb) {
  waterfall([
    gotoRootDirectory, (basePath, callback) => {
      return listPackageJsonFiles(branchName, basePath, callback)
    }
  ], (err, paths) => {
    if (err) {
      return cb(err)
    }
    return cb(null, paths)
  })
}

const Utils = {
  isGitInstalled,
  isGitRepo,
  prepareArguments,
  getRepoName,
  log,
  packagePaths,
  checkOutBranch,
  currentBranchName,
  isExists: fs.stat
}

export default Utils
<|endoftext|>


<commit_before>/**
 * @license
 * Copyright 2016 Google Inc. All rights reserved.
 *
 * 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.
 */
'use strict';

const Auditor = require('./auditor');
const Scheduler = require('./scheduler');
const Aggregator = require('./aggregator');

const GATHERER_CLASSES = [
  require('./gatherers/url'),
  require('./gatherers/https'),
  require('./gatherers/http-redirect'),
  require('./gatherers/service-worker'),
  require('./gatherers/viewport'),
  require('./gatherers/theme-color'),
  require('./gatherers/html'),
  require('./gatherers/manifest'),
  require('./gatherers/accessibility'),
  require('./gatherers/screenshots'),
  require('./gatherers/offline'),
  require('./gatherers/critical-request-chains')
];

const AUDITS = [
  require('./audits/security/is-on-https'),
  require('./audits/security/redirects-http'),
  require('./audits/offline/service-worker'),
  require('./audits/offline/works-offline'),
  require('./audits/mobile-friendly/viewport'),
  require('./audits/mobile-friendly/display'),
  require('./audits/performance/first-meaningful-paint'),
  require('./audits/performance/speed-index-metric'),
  require('./audits/performance/user-timings'),
  require('./audits/performance/screenshots'),
  // TODO: https://github.com/GoogleChrome/lighthouse/issues/336
  // require('./audits/performance/input-readiness-metric'),
  require('./audits/performance/critical-request-chains'),
  require('./audits/manifest/exists'),
  require('./audits/manifest/background-color'),
  require('./audits/manifest/theme-color'),
  require('./audits/manifest/icons-min-192'),
  require('./audits/manifest/icons-min-144'),
  require('./audits/manifest/name'),
  require('./audits/manifest/short-name'),
  require('./audits/manifest/short-name-length'),
  require('./audits/manifest/start-url'),
  require('./audits/html/meta-theme-color'),
  require('./audits/accessibility/aria-valid-attr'),
  require('./audits/accessibility/aria-allowed-attr'),
  require('./audits/accessibility/color-contrast'),
  require('./audits/accessibility/image-alt'),
  require('./audits/accessibility/label'),
  require('./audits/accessibility/tabindex')
];

const AGGREGATORS = [
  require('./aggregators/can-load-offline'),
  require('./aggregators/is-performant'),
  require('./aggregators/is-secure'),
  require('./aggregators/will-get-add-to-homescreen-prompt'),
  require('./aggregators/launches-with-splash-screen'),
  require('./aggregators/address-bar-is-themed'),
  require('./aggregators/is-sized-for-mobile-screen'),
  require('./aggregators/best-practices'),
  require('./aggregators/performance-metrics')
];

module.exports = function(driver, opts) {
  // Default mobile emulation and page loading to true.
  // The extension will switch these off initially.
  if (typeof opts.flags.mobile === 'undefined') {
    opts.flags.mobile = true;
  }

  if (typeof opts.flags.loadPage === 'undefined') {
    opts.flags.loadPage = true;
  }

  // Discard any audits not whitelisted.
  let audits = AUDITS;
  if (opts.flags.auditWhitelist) {
    const whitelist = opts.flags.auditWhitelist;
    audits = audits.filter(audit => whitelist.has(audit.name));
  }

  // Collate all artifacts required by audits to be run.
  const auditArtifacts = audits.map(audit => audit.requiredArtifacts);
  const requiredArtifacts = new Set([].concat(...auditArtifacts));

  // Instantiate gatherers and discard any not needed by requested audits.
  // For now, the trace and network records are assumed to be required.
  const gatherers = GATHERER_CLASSES.map(G => new G())
    .filter(gatherer => requiredArtifacts.has(gatherer.name));

  return Scheduler
      .run(gatherers, Object.assign({}, opts, {driver}))
      .then(artifacts => Auditor.audit(artifacts, audits))
      .then(results => Aggregator.aggregate(AGGREGATORS, results))
      .then(aggregations => {
        return {
          url: opts.url,
          aggregations
        };
      });
};

/**
 * Returns list of audit names for external querying.
 * @return {!Array<string>}
 */
module.exports.getAuditList = function() {
  return AUDITS.map(audit => audit.name);
};
<commit_msg>Log the whitelisted and skipped audits. (#386)<commit_after>/**
 * @license
 * Copyright 2016 Google Inc. All rights reserved.
 *
 * 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.
 */
'use strict';

const Auditor = require('./auditor');
const Scheduler = require('./scheduler');
const Aggregator = require('./aggregator');
const log = require('./lib/log.js');

const GATHERER_CLASSES = [
  require('./gatherers/url'),
  require('./gatherers/https'),
  require('./gatherers/http-redirect'),
  require('./gatherers/service-worker'),
  require('./gatherers/viewport'),
  require('./gatherers/theme-color'),
  require('./gatherers/html'),
  require('./gatherers/manifest'),
  require('./gatherers/accessibility'),
  require('./gatherers/screenshots'),
  require('./gatherers/offline'),
  require('./gatherers/critical-request-chains')
];

const AUDITS = [
  require('./audits/security/is-on-https'),
  require('./audits/security/redirects-http'),
  require('./audits/offline/service-worker'),
  require('./audits/offline/works-offline'),
  require('./audits/mobile-friendly/viewport'),
  require('./audits/mobile-friendly/display'),
  require('./audits/performance/first-meaningful-paint'),
  require('./audits/performance/speed-index-metric'),
  require('./audits/performance/user-timings'),
  require('./audits/performance/screenshots'),
  // TODO: https://github.com/GoogleChrome/lighthouse/issues/336
  // require('./audits/performance/input-readiness-metric'),
  require('./audits/performance/critical-request-chains'),
  require('./audits/manifest/exists'),
  require('./audits/manifest/background-color'),
  require('./audits/manifest/theme-color'),
  require('./audits/manifest/icons-min-192'),
  require('./audits/manifest/icons-min-144'),
  require('./audits/manifest/name'),
  require('./audits/manifest/short-name'),
  require('./audits/manifest/short-name-length'),
  require('./audits/manifest/start-url'),
  require('./audits/html/meta-theme-color'),
  require('./audits/accessibility/aria-valid-attr'),
  require('./audits/accessibility/aria-allowed-attr'),
  require('./audits/accessibility/color-contrast'),
  require('./audits/accessibility/image-alt'),
  require('./audits/accessibility/label'),
  require('./audits/accessibility/tabindex')
];

const AGGREGATORS = [
  require('./aggregators/can-load-offline'),
  require('./aggregators/is-performant'),
  require('./aggregators/is-secure'),
  require('./aggregators/will-get-add-to-homescreen-prompt'),
  require('./aggregators/launches-with-splash-screen'),
  require('./aggregators/address-bar-is-themed'),
  require('./aggregators/is-sized-for-mobile-screen'),
  require('./aggregators/best-practices'),
  require('./aggregators/performance-metrics')
];

module.exports = function(driver, opts) {
  // Default mobile emulation and page loading to true.
  // The extension will switch these off initially.
  if (typeof opts.flags.mobile === 'undefined') {
    opts.flags.mobile = true;
  }

  if (typeof opts.flags.loadPage === 'undefined') {
    opts.flags.loadPage = true;
  }

  // Discard any audits not whitelisted.
  let audits = AUDITS;
  let rejected;
  if (opts.flags.auditWhitelist) {
    const whitelist = opts.flags.auditWhitelist;
    rejected = audits.filter(audit => !whitelist.has(audit.name));
    audits = audits.filter(audit => whitelist.has(audit.name));
    if (rejected.length) {
      log.log('info', 'Running these audits:', `${audits.map(a => a.name).join(', ')}`);
      log.log('info', 'Skipping these audits:', `${rejected.map(a => a.name).join(', ')}`);
    }
  }

  // Collate all artifacts required by audits to be run.
  const auditArtifacts = audits.map(audit => audit.requiredArtifacts);
  const requiredArtifacts = new Set([].concat(...auditArtifacts));

  // Instantiate gatherers and discard any not needed by requested audits.
  // For now, the trace and network records are assumed to be required.
  const gatherers = GATHERER_CLASSES.map(G => new G())
    .filter(gatherer => requiredArtifacts.has(gatherer.name));

  return Scheduler
      .run(gatherers, Object.assign({}, opts, {driver}))
      .then(artifacts => Auditor.audit(artifacts, audits))
      .then(results => Aggregator.aggregate(AGGREGATORS, results))
      .then(aggregations => {
        return {
          url: opts.url,
          aggregations
        };
      });
};

/**
 * Returns list of audit names for external querying.
 * @return {!Array<string>}
 */
module.exports.getAuditList = function() {
  return AUDITS.map(audit => audit.name);
};
<|endoftext|>


<commit_before>import Immutable, { List, Map, Set } from 'immutable';
import { isSmallScreen } from '../utils/media_utils';
import { iconUrl } from '../icon/index';
import * as d from '../dict/index';
import t from '../dict/t';
import trim from 'trim';

// TODO: move to its own utils module
function dataFns(nsKeyPath) {
  function keyPath(keyOrKeyPath) {
    return nsKeyPath.concat(
      typeof keyOrKeyPath === "object" ? keyOrKeyPath : [keyOrKeyPath]
    );
  }

  return {
    get: function(m, keyOrKeyPath, notSetValue = undefined) {
      return m.getIn(keyPath(keyOrKeyPath), notSetValue);
    },

    set: function(m, keyOrKeyPath, value) {
      return m.setIn(keyPath(keyOrKeyPath), value);
    },

    remove: function(m, keyOrKeyPath) {
      return m.removeIn(keyPath(keyOrKeyPath));
    },

    init: function(id, m) {
      return new Map({id: id}).setIn(nsKeyPath, m);
    }
  }
}

const { get, set, init } = dataFns(["core"]);

function buildSetupSnapshot(m) {
  return set(m, "setupSnapshot", m);
}

export function setup(id, clientID, domain, options, signInCallback, hookRunner) {
  let m = init(id, Immutable.fromJS({
    auth: extractAuthOptions(options),
    clientID: clientID,
    domain: domain,
    hookRunner: hookRunner,
    mode: options.mode,
    signInCallback: signInCallback,
    pickedConnections: Immutable.fromJS(options.connections || []),
    ui: extractUIOptions(id, options.mode, options)
  }));
  return buildSetupSnapshot(m);
}

export function id(m) {
  return m.get("id");
}

export function clientID(m) {
  return get(m, "clientID");
}

export function domain(m) {
  return get(m, "domain");
}

export function modeName(m) {
  return get(m, "mode");
}

export function show(m) {
  return get(m, "show", false);
}

export function setShow(m, value) {
  return set(m, "show", value);
}

export function setSubmitting(m, value, error) {
  m = set(m, "submitting", value);
  m = error && !value ? setGlobalError(m, error) : clearGlobalError(m);
  return m;
}

export function submitting(m) {
  return get(m, "submitting", false);
}

export function setGlobalError(m, str) {
  return set(m, "globalError", str);
}

export function globalError(m) {
  return get(m, "globalError", "");
}

export function clearGlobalError(m) {
  return remove(m, "globalError");
}

export function setGlobalSuccess(m, str) {
  return set(m, "globalSuccess", str);
}

export function globalSuccess(m) {
  return get(m, "globalSuccess", "");
}

export function clearGlobalSuccess(m) {
  return remove(m, "globalSuccess");
}

export function rendering(m) {
  return get(m, "render", false);
}

export function gravatar(m) {
  if (ui.gravatar(m)) {
    return m.get("gravatar");
  } else {
    return undefined;
  }
}

function extractUIOptions(id, modeName, options) {
  const closable = options.container ? false : undefined === options.closable ? true : !!options.closable;
  return new Map({
    containerID: options.container || `auth0-lock-container-${id}`,
    appendContainer: !options.container,
    autoclose: undefined === options.autoclose ? false : closable && options.autoclose,
    icon: options.icon || "//cdn.auth0.com/styleguide/1.0.0/img/badge.png",
    closable: closable,
    dict: d.buildDict(modeName, typeof options.dict === "object" ? options.dict : {}),
    disableWarnings: options.disableWarnings === undefined ? false : !!options.disableWarnings,
    focusInput: undefined === options.focusInput ? !(options.container || isSmallScreen()) : !!options.focusInput,
    gravatar: undefined === options.gravatar ? true : !!options.gravatar,
    mobile: undefined === options.mobile ? false : !!options.mobile,
    popup: undefined === options.popup ? false : !!options.popup,
    popupOptions: new Map(undefined === options.popupOptions ? {} : options.popupOptions),
    primaryColor: options.primaryColor && typeof options.primaryColor === "string" ? options.primaryColor : "#ea5323",
    rememberLastLogin: undefined === options.rememberLastLogin ? true : !!options.rememberLastLogin
  });
}

const { get: getUIAttribute } = dataFns(["core", "ui"]);

export const ui = {
  containerID: lock => getUIAttribute(lock, "containerID"),
  appendContainer: lock => getUIAttribute(lock, "appendContainer"),
  autoclose: lock => getUIAttribute(lock, "autoclose"),
  icon: lock => getUIAttribute(lock, "icon"),
  closable: lock => getUIAttribute(lock, "closable"),
  dict: lock => getUIAttribute(lock, "dict"),
  disableWarnings: lock => getUIAttribute(lock, "disableWarnings"),
  t: (lock, keyPath, params) => t(ui.dict(lock), keyPath, params),
  focusInput: lock => getUIAttribute(lock, "focusInput"),
  gravatar: lock => getUIAttribute(lock, "gravatar"),
  mobile: lock => getUIAttribute(lock, "mobile"),
  popup: lock => getUIAttribute(lock, "popup"),
  popupOptions: lock => getUIAttribute(lock, "popupOptions"),
  primaryColor: lock => getUIAttribute(lock, "primaryColor"),
  rememberLastLogin: lock => getUIAttribute(lock, "rememberLastLogin")
};

const { get: getAuthAttribute } = dataFns(["core", "auth"]);

export const auth = {
  authParams: lock => getAuthAttribute(lock, "authParams"),
  callbackURL: lock => getAuthAttribute(lock, "callbackURL"),
  forceJSONP: lock => getAuthAttribute(lock, "forceJSONP"),
  responseType: lock => getAuthAttribute(lock, "responseType")
};

function extractAuthOptions(options) {
  // TODO: should `popup` be a auth option?
  let { authParams, callbackURL, forceJSONP, responseType, sso } = options;

  authParams = typeof authParams === "object" ? authParams : {};
  callbackURL = typeof callbackURL === "string" && callbackURL ? callbackURL : undefined;
  responseType = typeof responseType === "string" ? responseType : callbackURL ? "code" : "token";
  sso = typeof sso === "boolean" ? sso : true;

  if (trim(authParams.scope || "") === "openid profile") {
    warn(m, "Usage of scope 'openid profile' is not recommended. See https://auth0.com/docs/scopes for more details.");
  }

  return Immutable.fromJS({
    authParams,
    callbackURL,
    forceJSONP,
    responseType,
    sso
  });
}

export function withAuthOptions(m, opts, flattenAuthParams = true) {
  const auth = get(m, "auth");
  const authOptions = flattenAuthParams
    ? auth.remove("authParams").merge(auth.get("authParams"))
    : auth;

  return authOptions.merge(Immutable.fromJS(opts)).toJS();
}

export function invokeSignInCallback(m, ...args) {
  get(m, "signInCallback").apply(undefined, args);
}

export function shouldRedirect(m) {
  // TODO: remove this hack
  return m.get("forceRedirect", false) || auth.callbackURL(m);
}

export function render(m) {
  return set(m, "render", true);
}

export function close(m) {
  return set(m, "show", false);
}

export function reset(m) {
  return buildSetupSnapshot(get(m, "setupSnapshot"));
}

export function setSignedIn(m, value) {
  return set(m, "signedIn", value);
}

export function signedIn(m) {
  return get(m, "signedIn", false);
}

export function tabIndex(m, n) {
  return [id(m), n > 9 ? "" : "0", n].join("");
}

export function warn(x, str) {
  const shouldOutput = Map.isMap(x)
    ? !ui.disableWarnings(x)
    : !x.disableWarnings;

  if (shouldOutput && console && console.warn) {
    console.warn(str);
  }
}

export function getPickedConnections(m) {
  return get(m, "pickedConnections");
}

export function getEnabledConnections(m, type) {
  return get(m, ["enabledConnections", type], List());
}

export function isConnectionEnabled(m, name) {
  // TODO: is the name enough? shouldn't we check for strategy and/or type?
  return get(m, "enabledConnections", Map())
    .flatten(true)
    .some(c => c.get("name") === name);
}

export function runHook(m, str, ...args) {
  get(m, "hookRunner")(modeName(m), str, id(m), ...args);
}
<commit_msg>Add transient data manipulation fns<commit_after>import Immutable, { List, Map, Set } from 'immutable';
import { isSmallScreen } from '../utils/media_utils';
import { iconUrl } from '../icon/index';
import * as d from '../dict/index';
import t from '../dict/t';
import trim from 'trim';

// TODO: move to its own utils module
function dataFns(baseNSKeyPath) {

  function keyPath(nsKeyPath, keyOrKeyPath) {
    return nsKeyPath.concat(
      typeof keyOrKeyPath === "object" ? keyOrKeyPath : [keyOrKeyPath]
    );
  }

  function getFn(nsKeyPath) {
    return function(m, keyOrKeyPath, notSetValue = undefined) {
      return m.getIn(keyPath(nsKeyPath, keyOrKeyPath), notSetValue);
    }
  }

  function setFn(nsKeyPath) {
    return function(m, keyOrKeyPath, value) {
      return m.setIn(keyPath(nsKeyPath, keyOrKeyPath), value);
    }
  }

  function removeFn(nsKeyPath) {
    return function(m, keyOrKeyPath) {
      return m.removeIn(keyPath(nsKeyPath, keyOrKeyPath));
    }
  }

  const transientNSKeyPath = baseNSKeyPath.concat(["transient"]);

  return {
    get: getFn(baseNSKeyPath),
    set: setFn(baseNSKeyPath),
    remove: removeFn(baseNSKeyPath),
    tget: getFn(transientNSKeyPath),
    tset: setFn(transientNSKeyPath),
    tremove: removeFn(transientNSKeyPath),
    init: function(id, m) {
      return new Map({id: id}).setIn(baseNSKeyPath, m);
    }
  }
}

const { get, set, remove, tget, tset, tremove, init } = dataFns(["core"]);

function buildSetupSnapshot(m) {
  return set(m, "setupSnapshot", m);
}

export function setup(id, clientID, domain, options, signInCallback, hookRunner) {
  let m = init(id, Immutable.fromJS({
    auth: extractAuthOptions(options),
    clientID: clientID,
    domain: domain,
    hookRunner: hookRunner,
    mode: options.mode,
    signInCallback: signInCallback,
    pickedConnections: Immutable.fromJS(options.connections || []),
    ui: extractUIOptions(id, options.mode, options)
  }));
  return buildSetupSnapshot(m);
}

export function id(m) {
  return m.get("id");
}

export function clientID(m) {
  return get(m, "clientID");
}

export function domain(m) {
  return get(m, "domain");
}

export function modeName(m) {
  return get(m, "mode");
}

export function show(m) {
  return tget(m, "show", false);
}

export function setShow(m, value) {
  return tset(m, "show", value);
}

export function setSubmitting(m, value, error) {
  m = tset(m, "submitting", value);
  m = error && !value ? setGlobalError(m, error) : clearGlobalError(m);
  return m;
}

export function submitting(m) {
  return tget(m, "submitting", false);
}

export function setGlobalError(m, str) {
  return tset(m, "globalError", str);
}

export function globalError(m) {
  return tget(m, "globalError", "");
}

export function clearGlobalError(m) {
  return tremove(m, "globalError");
}

export function setGlobalSuccess(m, str) {
  return tset(m, "globalSuccess", str);
}

export function globalSuccess(m) {
  return tget(m, "globalSuccess", "");
}

export function clearGlobalSuccess(m) {
  return tremove(m, "globalSuccess");
}

export function rendering(m) {
  return tget(m, "render", false);
}

export function gravatar(m) {
  if (ui.gravatar(m)) {
    return m.get("gravatar");
  } else {
    return undefined;
  }
}

function extractUIOptions(id, modeName, options) {
  const closable = options.container ? false : undefined === options.closable ? true : !!options.closable;
  return new Map({
    containerID: options.container || `auth0-lock-container-${id}`,
    appendContainer: !options.container,
    autoclose: undefined === options.autoclose ? false : closable && options.autoclose,
    icon: options.icon || "//cdn.auth0.com/styleguide/1.0.0/img/badge.png",
    closable: closable,
    dict: d.buildDict(modeName, typeof options.dict === "object" ? options.dict : {}),
    disableWarnings: options.disableWarnings === undefined ? false : !!options.disableWarnings,
    focusInput: undefined === options.focusInput ? !(options.container || isSmallScreen()) : !!options.focusInput,
    gravatar: undefined === options.gravatar ? true : !!options.gravatar,
    mobile: undefined === options.mobile ? false : !!options.mobile,
    popup: undefined === options.popup ? false : !!options.popup,
    popupOptions: new Map(undefined === options.popupOptions ? {} : options.popupOptions),
    primaryColor: options.primaryColor && typeof options.primaryColor === "string" ? options.primaryColor : "#ea5323",
    rememberLastLogin: undefined === options.rememberLastLogin ? true : !!options.rememberLastLogin
  });
}

const { get: getUIAttribute } = dataFns(["core", "ui"]);

export const ui = {
  containerID: lock => getUIAttribute(lock, "containerID"),
  appendContainer: lock => getUIAttribute(lock, "appendContainer"),
  autoclose: lock => getUIAttribute(lock, "autoclose"),
  icon: lock => getUIAttribute(lock, "icon"),
  closable: lock => getUIAttribute(lock, "closable"),
  dict: lock => getUIAttribute(lock, "dict"),
  disableWarnings: lock => getUIAttribute(lock, "disableWarnings"),
  t: (lock, keyPath, params) => t(ui.dict(lock), keyPath, params),
  focusInput: lock => getUIAttribute(lock, "focusInput"),
  gravatar: lock => getUIAttribute(lock, "gravatar"),
  mobile: lock => getUIAttribute(lock, "mobile"),
  popup: lock => getUIAttribute(lock, "popup"),
  popupOptions: lock => getUIAttribute(lock, "popupOptions"),
  primaryColor: lock => getUIAttribute(lock, "primaryColor"),
  rememberLastLogin: lock => getUIAttribute(lock, "rememberLastLogin")
};

const { get: getAuthAttribute } = dataFns(["core", "auth"]);

export const auth = {
  authParams: lock => getAuthAttribute(lock, "authParams"),
  callbackURL: lock => getAuthAttribute(lock, "callbackURL"),
  forceJSONP: lock => getAuthAttribute(lock, "forceJSONP"),
  responseType: lock => getAuthAttribute(lock, "responseType")
};

function extractAuthOptions(options) {
  // TODO: should `popup` be a auth option?
  let { authParams, callbackURL, forceJSONP, responseType, sso } = options;

  authParams = typeof authParams === "object" ? authParams : {};
  callbackURL = typeof callbackURL === "string" && callbackURL ? callbackURL : undefined;
  responseType = typeof responseType === "string" ? responseType : callbackURL ? "code" : "token";
  sso = typeof sso === "boolean" ? sso : true;

  if (trim(authParams.scope || "") === "openid profile") {
    warn(m, "Usage of scope 'openid profile' is not recommended. See https://auth0.com/docs/scopes for more details.");
  }

  return Immutable.fromJS({
    authParams,
    callbackURL,
    forceJSONP,
    responseType,
    sso
  });
}

export function withAuthOptions(m, opts, flattenAuthParams = true) {
  const auth = get(m, "auth");
  const authOptions = flattenAuthParams
    ? auth.remove("authParams").merge(auth.get("authParams"))
    : auth;

  return authOptions.merge(Immutable.fromJS(opts)).toJS();
}

export function invokeSignInCallback(m, ...args) {
  get(m, "signInCallback").apply(undefined, args);
}

export function shouldRedirect(m) {
  // TODO: remove this hack
  return m.get("forceRedirect", false) || auth.callbackURL(m);
}

export function render(m) {
  return tset(m, "render", true);
}

export function close(m) {
  return tset(m, "show", false);
}

export function reset(m) {
  return buildSetupSnapshot(get(m, "setupSnapshot"));
}

export function setSignedIn(m, value) {
  return tset(m, "signedIn", value);
}

export function signedIn(m) {
  return tget(m, "signedIn", false);
}

export function tabIndex(m, n) {
  return [id(m), n > 9 ? "" : "0", n].join("");
}

export function warn(x, str) {
  const shouldOutput = Map.isMap(x)
    ? !ui.disableWarnings(x)
    : !x.disableWarnings;

  if (shouldOutput && console && console.warn) {
    console.warn(str);
  }
}

export function getPickedConnections(m) {
  return get(m, "pickedConnections");
}

export function getEnabledConnections(m, type) {
  return get(m, ["enabledConnections", type], List());
}

export function isConnectionEnabled(m, name) {
  // TODO: is the name enough? shouldn't we check for strategy and/or type?
  return get(m, "enabledConnections", Map())
    .flatten(true)
    .some(c => c.get("name") === name);
}

export function runHook(m, str, ...args) {
  get(m, "hookRunner")(modeName(m), str, id(m), ...args);
}
<|endoftext|>


<commit_before>
    // Initial Setup
    // -------------

    /**
     * The one global object for F.
     * @namespace F
     */
    var F = {};

    /**
     * The previous value of the `F` variable, so that it can be
     * restored later on, if `noConflict` is used.
     * @type {F}
     */
    var previousF = F;

    /**
     * Current version of the library.
     * Must be keept in sync with `package.json` and `bower.json`.
     * @type {String}
     */
    F.VERSION = '::VERSION_NUMBER::';

    /**
     * Set framework to debug mode. Disabled by default
     * @type {Boolean}
     */
    F.DEBUG = false;

    /**
     * Runs F.js in *noConflict* mode, returning the `F` variable
     * to its previous owner.
     * @return {F} a reference to this F object
     */
    F.noConflict = function() {
        F = previousF;
        return this;
    };

    // Patch Object
    Object.getOwnPropertyDescriptors = function (obj) {
        var descriptors = {};
        for (var prop in obj) {
            if (obj.hasOwnProperty(prop)) {
                descriptors[prop] = Object.getOwnPropertyDescriptor(obj, prop);
            }
        }
        return descriptors;
    };

    // Util
    // ---

    // Composes objects by combining them into a new one
    F.compose = Object.assign;

    /**
     * Helper function to correctly set up the prototype chain for subclasses.
     * Similar to `goog.inherits`, but uses a hash of prototype properties and
     * class properties to be extended.
     *
     * Taken from Backbone.js of Jeremy Ashkenas
     * @see https://github.com/jashkenas/backbone/blob/master/backbone.js#L1839
     * @see https://gist.github.com/juandopazo/1367191
     *
     * @param  {Object} protoProps - the instance properties for the *Class*
     * @param  {Object} staticProps - the static properties for the *Class*
     * @return {Function} - a new constructor function
     */
    F.extend = function(protoProps, staticProps) {
        var parent = this;
        var child;

        // The constructor function for the new subclass is either defined by you
        // (the "constructor" property in your `extend` definition), or defaulted
        // by us to simply call the parent constructor.
        if (!protoProps.hasOwnProperty('constructor')) {
            Object.defineProperty(protoProps, 'constructor', {
                value: function () {
                    // Default call to superclass as in maxmin classes
                    parent.apply(this, arguments);
                },
                writable: true,
                configurable: true,
                enumerable: false
            });
        }

        child = protoProps.constructor;
        // Add static properties to the constructor function, if supplied.
        Object.assign(child, parent, staticProps);

        // Set the prototype chain to inherit from `parent`, without calling
        // `parent`'s constructor function and add the prototype properties.
        child.prototype = Object.create(parent.prototype, Object.getOwnPropertyDescriptors(protoProps));
        child.prototype.constructor = child;

        // Set a convenience property in case the parent's prototype is needed
        // later.
        child.__super__ = parent.prototype;

        return child;
    };

    /**
     * Performs event delegation setting.
     * @param  {HTMLElement} element the element we want to delegate events for
     * @param  {string} event    the type of event we want to delegate
     * @param  {string} selector a css selector
     * @param  {Function} handler  the handler function
     * @param  {Object} context  the context under which the handler fn
     *                           will be called
     * @param {boolean} useCapture indicates that events of this type will be
     *                           dispatched to the registered listener before
     *                           being dispatched to any EventTarget beneath
     *                           it in the DOM tree
     * @return {void}
     */
    F.delegateEvent = function(element, event, selector, handler, context, useCapture) {

        var listener =  function(e){
            if (typeof selector === "undefined" || selector === null) {
                return handler.call(context || null, e);
            } else if (e.target && e.target.matches(selector)) {
                // console.log('event: ' + eventName + ', selector: ' + selector + ', handler: ' + handler + ', matches: ' + e.target.matches(selector));
                return handler.call(context || null, e);
            }
        };

        useCapture = useCapture || false;
        element.addEventListener(event, listener, useCapture);
    };

    /**
     * Performs event delegation unsetting.
     * @param  {HTMLElement} element the element we want to undelegate events for
     * @param  {string} event    the type of event we want to undelegate
     * @param  {string} selector a css selector
     * @param  {Function} handler  the handler function
     * @param  {Object} context  the context under which the handler fn
     *                           will be called
     * @param {boolean} useCapture indicates that events of this type will be
     *                             dispatched to the registered listener before
     *                             being dispatched to any EventTarget beneath
     *                             it in the DOM tree
     * @return {void}
     */
    F.undelegateEvent = function(element, event, selector, handler, context, useCapture) {

        var listener = function(e) {
            if (typeof selector === "undefined" || selector === null) {
                return handler.call(context || null, e);
            } else if (e.target && e.target.matches(selector)) {
                // console.log('event: ' + eventName + ', selector: ' + selector + ', handler: ' + handler + ', matches: ' + e.target.matches(selector));
                return handler.call(context || null, e);
            }
        };
        useCapture = useCapture || false;

        element.removeEventListener(event, listener, useCapture);
    };

    // Guard
    // ---

    /**
     * Guards that the given assertion is satisfied, immediately raising an
     * error when its not.
     * @param {boolean} assertion the condition to be checked for truthness
     * @param {String} message the message to be contained in the raised error
     * @return {void}
     */
    F.guardThat = function(assertion, message) {
        if (typeof assertion !== 'boolean') {
            throw new Error('assertion must be boolean')
        }

        if (message && typeof message !== 'string') {
            throw new Error('message must be a string')
        }

        if (!assertion) {
            throw new Error(message || "assertion has been violated!");
        }
    }
<commit_msg>add task reminder<commit_after>
    // Initial Setup
    // -------------

    /**
     * The one global object for F.
     * @namespace F
     */
    var F = {};

    /**
     * The previous value of the `F` variable, so that it can be
     * restored later on, if `noConflict` is used.
     * @type {F}
     */
    var previousF = F;

    /**
     * Current version of the library.
     * Must be keept in sync with `package.json` and `bower.json`.
     * @type {String}
     */
    F.VERSION = '::VERSION_NUMBER::';

    /**
     * Set framework to debug mode. Disabled by default
     * @type {Boolean}
     */
    F.DEBUG = false;

    /**
     * Runs F.js in *noConflict* mode, returning the `F` variable
     * to its previous owner.
     * @return {F} a reference to this F object
     */
    F.noConflict = function() {
        F = previousF;
        return this;
    };

    // Patch Object
    Object.getOwnPropertyDescriptors = function (obj) {
        var descriptors = {};
        for (var prop in obj) {
            if (obj.hasOwnProperty(prop)) {
                descriptors[prop] = Object.getOwnPropertyDescriptor(obj, prop);
            }
        }
        return descriptors;
    };

    // Util
    // ---

    // Composes objects by combining them into a new one
    // TODO: Object.assign only exists in ES6 and library is for ES5 so fix this.
    F.compose = Object.assign;

    /**
     * Helper function to correctly set up the prototype chain for subclasses.
     * Similar to `goog.inherits`, but uses a hash of prototype properties and
     * class properties to be extended.
     *
     * Taken from Backbone.js of Jeremy Ashkenas
     * @see https://github.com/jashkenas/backbone/blob/master/backbone.js#L1839
     * @see https://gist.github.com/juandopazo/1367191
     *
     * @param  {Object} protoProps - the instance properties for the *Class*
     * @param  {Object} staticProps - the static properties for the *Class*
     * @return {Function} - a new constructor function
     */
    F.extend = function(protoProps, staticProps) {
        var parent = this;
        var child;

        // The constructor function for the new subclass is either defined by you
        // (the "constructor" property in your `extend` definition), or defaulted
        // by us to simply call the parent constructor.
        if (!protoProps.hasOwnProperty('constructor')) {
            Object.defineProperty(protoProps, 'constructor', {
                value: function () {
                    // Default call to superclass as in maxmin classes
                    parent.apply(this, arguments);
                },
                writable: true,
                configurable: true,
                enumerable: false
            });
        }

        child = protoProps.constructor;
        // Add static properties to the constructor function, if supplied.
        Object.assign(child, parent, staticProps);

        // Set the prototype chain to inherit from `parent`, without calling
        // `parent`'s constructor function and add the prototype properties.
        child.prototype = Object.create(parent.prototype, Object.getOwnPropertyDescriptors(protoProps));
        child.prototype.constructor = child;

        // Set a convenience property in case the parent's prototype is needed
        // later.
        child.__super__ = parent.prototype;

        return child;
    };

    /**
     * Performs event delegation setting.
     * @param  {HTMLElement} element the element we want to delegate events for
     * @param  {string} event    the type of event we want to delegate
     * @param  {string} selector a css selector
     * @param  {Function} handler  the handler function
     * @param  {Object} context  the context under which the handler fn
     *                           will be called
     * @param {boolean} useCapture indicates that events of this type will be
     *                           dispatched to the registered listener before
     *                           being dispatched to any EventTarget beneath
     *                           it in the DOM tree
     * @return {void}
     */
    F.delegateEvent = function(element, event, selector, handler, context, useCapture) {

        var listener =  function(e){
            if (typeof selector === "undefined" || selector === null) {
                return handler.call(context || null, e);
            } else if (e.target && e.target.matches(selector)) {
                // console.log('event: ' + eventName + ', selector: ' + selector + ', handler: ' + handler + ', matches: ' + e.target.matches(selector));
                return handler.call(context || null, e);
            }
        };

        useCapture = useCapture || false;
        element.addEventListener(event, listener, useCapture);
    };

    /**
     * Performs event delegation unsetting.
     * @param  {HTMLElement} element the element we want to undelegate events for
     * @param  {string} event    the type of event we want to undelegate
     * @param  {string} selector a css selector
     * @param  {Function} handler  the handler function
     * @param  {Object} context  the context under which the handler fn
     *                           will be called
     * @param {boolean} useCapture indicates that events of this type will be
     *                             dispatched to the registered listener before
     *                             being dispatched to any EventTarget beneath
     *                             it in the DOM tree
     * @return {void}
     */
    F.undelegateEvent = function(element, event, selector, handler, context, useCapture) {

        var listener = function(e) {
            if (typeof selector === "undefined" || selector === null) {
                return handler.call(context || null, e);
            } else if (e.target && e.target.matches(selector)) {
                // console.log('event: ' + eventName + ', selector: ' + selector + ', handler: ' + handler + ', matches: ' + e.target.matches(selector));
                return handler.call(context || null, e);
            }
        };
        useCapture = useCapture || false;

        element.removeEventListener(event, listener, useCapture);
    };

    // Guard
    // ---

    /**
     * Guards that the given assertion is satisfied, immediately raising an
     * error when its not.
     * @param {boolean} assertion the condition to be checked for truthness
     * @param {String} message the message to be contained in the raised error
     * @return {void}
     */
    F.guardThat = function(assertion, message) {
        if (typeof assertion !== 'boolean') {
            throw new Error('assertion must be boolean')
        }

        if (message && typeof message !== 'string') {
            throw new Error('message must be a string')
        }

        if (!assertion) {
            throw new Error(message || "assertion has been violated!");
        }
    }
<|endoftext|>


<commit_before>import {
  launchFilename,
  launchNewNotebook,
} from './launch';

import { Menu, app } from 'electron';
import { defaultMenu, loadFullMenu } from './menu';
import { resolve } from 'path';

const program = require('commander');
const version = require('../../package.json').version;

program._name = 'nteract';
process.argv.splice(1,0,'')

program
  .version(version)
  .option('-k, --kernel [kernel]', 'kernel')
  .parse(process.argv);

const notebooks = program.args;

app.on('window-all-closed', () => {
  // On OS X, we want to keep the app and menu bar active
  if (process.platform !== 'darwin') {
    app.quit();
  }
});

app.on('open-file', (event, path) => {
  event.preventDefault();
  launchFilename(resolve(path));
});

app.on('ready', () => {
  // Get the default menu first
  Menu.setApplicationMenu(defaultMenu);
  // Let the kernels/languages come in after
  loadFullMenu().then(menu => Menu.setApplicationMenu(menu));
  if (notebooks <= 0) {
    launchNewNotebook('python3');
  } else {
    notebooks.filter(Boolean).forEach(f => launchFilename(resolve(f)));
  }
});
<commit_msg>satisfying the linter<commit_after>import {
  launchFilename,
  launchNewNotebook,
} from './launch';

import { Menu, app } from 'electron';
import { defaultMenu, loadFullMenu } from './menu';
import { resolve } from 'path';

const program = require('commander');
const version = require('../../package.json').version;

program._name = 'nteract';
process.argv.splice(1, 0, '');

program
  .version(version)
  .option('-k, --kernel [kernel]', 'kernel')
  .parse(process.argv);

const notebooks = program.args;

app.on('window-all-closed', () => {
  // On OS X, we want to keep the app and menu bar active
  if (process.platform !== 'darwin') {
    app.quit();
  }
});

app.on('open-file', (event, path) => {
  event.preventDefault();
  launchFilename(resolve(path));
});

app.on('ready', () => {
  // Get the default menu first
  Menu.setApplicationMenu(defaultMenu);
  // Let the kernels/languages come in after
  loadFullMenu().then(menu => Menu.setApplicationMenu(menu));
  if (notebooks <= 0) {
    launchNewNotebook('python3');
  } else {
    notebooks.filter(Boolean).forEach(f => launchFilename(resolve(f)));
  }
});
<|endoftext|>


<commit_before>#! /usr/bin/env node

// Run ampm under nodemon. It watches changes to ampm-restart.json so that ampm
// can restart itself. It also restarts on crash.

// Really should be using nodemon as a module, but:
// https://github.com/stimulant/ampm/issues/12

var path = require('path');
var child_process = require('child_process');

var configFiles = process.argv[2] || 'ampm.json';
var configFile = path.resolve(configFiles.split(',')[0]);
var appPath = path.dirname(configFile);
var restartFile = path.join(appPath, 'ampm-restart.json');
var stateFile = path.join(appPath, 'ampm-state.json');
var mode = process.argv[3] || 'default';
var cmd = 'nodemon';
var server = path.join(__dirname, 'server.js');

if (process.platform === 'win32') {
    // Gotta go to great lengths to avoid spaces in the path.
    // https://github.com/nodejs/node-v0.x-archive/issues/25895
    cmd = process.env.SYSTEMDRIVE + '\\PROGRA~1\\nodejs\\nodemon.cmd';
    if (__dirname.indexOf('Program Files') !== -1) {
        server = process.env.SYSTEMDRIVE + '\\PROGRA~1\\nodejs\\node_modules\\ampm\\server.js';
    }
}

var args = [
    '--verbose',
    '--exitcrash',
    '--watch', configFile,
    '--watch', restartFile,
    '--watch', '.',
    '--ignore', 'logs',
    '--ignore', stateFile,
    server,
    configFiles,
    mode
];

function start() {
    var ampm = child_process.spawn(cmd, args, {
        stdio: 'inherit'
    });
    ampm.on('close', start);
}

start();
<commit_msg>handle npm not being in program files on windows<commit_after>#! /usr/bin/env node

// Run ampm under nodemon. It watches changes to ampm-restart.json so that ampm
// can restart itself. It also restarts on crash.

// Really should be using nodemon as a module, but:
// https://github.com/stimulant/ampm/issues/12

var path = require('path');
var child_process = require('child_process');

var configFiles = process.argv[2] || 'ampm.json';
var configFile = path.resolve(configFiles.split(',')[0]);
var appPath = path.dirname(configFile);
var restartFile = path.join(appPath, 'ampm-restart.json');
var stateFile = path.join(appPath, 'ampm-state.json');
var mode = process.argv[3] || 'default';
var cmd = 'nodemon';
var server = path.join(__dirname, 'server.js');

if (process.platform === 'win32') {
    // Gotta go to great lengths to avoid spaces in the path.
    // https://github.com/nodejs/node-v0.x-archive/issues/25895
    cmd = child_process.execSync('where nodemon').toString().split('\n')[1].replace('Program Files', 'PROGRA~1').trim();
    server = child_process.execSync('where ampm').toString().split('\n')[1].replace('Program Files', 'PROGRA~1').trim();
    server = path.join(path.dirname(server), 'node_modules', 'ampm', 'server.js');
}

var args = [
    '--verbose',
    '--exitcrash',
    '--watch', configFile,
    '--watch', restartFile,
    '--watch', '.',
    '--ignore', 'logs',
    '--ignore', stateFile,
    server,
    configFiles,
    mode
];

function start() {
    var ampm = child_process.spawn(cmd, args, {
        stdio: 'inherit'
    });
    ampm.on('close', start);
}

start();
<|endoftext|>


<commit_before>'use strict';
const moment = require('moment');
const scribe = require('scribe-js')({
    createDefaultConsole: false
});
const Discord = require("discord.js");
const express = require("express");

const config = require("./config.json");
const data = require("./data.json");
const defBot = require("./defBot.json");

const bot = new Discord.Client();
const app = express();
const sLogWriter = new scribe.LogWriter('IdleRPG');

sLogWriter.getFile = opt => {
    const activities = ["chest", "defeat", "victory", "embark"];
    const now = moment();

    if (activities.indexOf(opt.logger.name) !== -1) return `[Activity] ${(now.format('DD-MM-YYYY')).toLowerCase()}.json`;
    else if (opt.logger.name === "wanted") return `[Wanted] ${(now.format('DD-MM-YYYY')).toLowerCase()}.json`;
    else return `[Shop] ${(now.format('DD-MM-YYYY')).toLowerCase()}.json`;
};

const sConsole = scribe.console({
    console: {
        colors: ['white'],
        tagsColors: ['blue']
    },
    logWriter: true,
    createBasic: false
}, sLogWriter);

// Change Console Colours Here
sConsole.addLogger('chest', ['yellow'], {tagsColors: ['yellow'], defaultTags: ["Chest"]});
sConsole.addLogger('defeat', ['red'], {tagsColors: ['red'], defaultTags: ["Defeat"]});
sConsole.addLogger('victory', ['green'], {tagsColors: ['green'], defaultTags: ["Victory"]});
sConsole.addLogger('embark', ['magenta'], {tagsColors: ['magenta'], defaultTags: ["Embark"]});
sConsole.addLogger('shop', ['bgBlue'], {tagsColors: ['bgBlue']});
sConsole.addLogger('wanted', ['bgRed'], {tagsColors: ['bgRed'], defaultTags: ["Wanted"]});

app.set('port', process.env.PORT || 5000);
app.use('/', scribe.webPanel());

bot.on("warn", m => global.console.log("[warn]", m));
bot.on("debug", m => global.console.log("[debug]", m));

let user = false;

bot.on("ready", () => {
    user = bot.users.get("id", config.discordId);
    if (!bot.servers.get("id", "86004744966914048")) bot.joinServer("https://discord.gg/0Tmfo5ZbORC20hEs");
});

bot.on("message", m => {
    if (m.channel.id === '134811337246244864') {
        if (m.content.indexOf(config.name) !== -1) {
            const messages = m.content.split("\n");

            for (let i = 0; i < messages.length; i++) {
                if (messages[i].indexOf(config.name) !== -1) {
                    if (messages[i].indexOf("found a") !== -1) {
                        if (config.consoleLog) sConsole.chest(messages[i].split('**').join(''));
                        if (config.pmLog) bot.sendMessage(user, messages[i]);
                    } else if (messages[i].indexOf("embarked on the quest") !== -1) {
                        if (config.consoleLog) sConsole.embark(messages[i].split('**').join(''));
                        if (config.pmLog) bot.sendMessage(user, messages[i]);
                    } else if (messages[i].indexOf("Quest Completed") !== -1) {
                        if (config.consoleLog) sConsole.victory(messages[i].split('**').join(''));
                        if (config.pmLog) bot.sendMessage(user, messages[i]);
                    } else if (messages[i] === `@${user.username} `) {
                        break;
                    } else {
                        if (config.consoleLog) sConsole.defeat(messages[i].split('**').join(''));
                        if (config.pmLog) bot.sendMessage(user, messages[i]);
                    }
                    break;
                }
            }
        }
    } else if (m.channel.id === '135579492616765440') {
        let shop = m.content;

        if (config.shopLevel.toLowerCase() === "above") {
            shop = shop.split("\n=")[0];
            shop = shop.split("\n");
            shop.shift();
            shop.pop();
        } else if (config.shopLevel.toLowerCase() === "below") {
            shop = shop.split("\n=")[1];
            shop = shop.split("\n");
            shop.shift();
            shop.pop();
        } else {
            shop = shop.split("\n");
            shop.pop();

            for (let i = 0; i < shop.length; i++) {
                if (shop[i].indexOf("!hgamble") !== -1) {
                    shop.splice(i, 1);
                    break;
                }
            }
        }
        if (config.consoleLog) sConsole.shop("==========Separator==========");

        for (let i = 0; i < shop.length; i++) {
            if (shop[i].includes("====")) {
                shop.splice(i, 1);
                i--;
            }
        }
        shop = shop.join("\n");
        shop = shop.split("```").join("").split("\n");
        let message = [];

        for (let i = 0; i < shop.length; i++) {
            const itemData = shop[i].split(" | ");
            const tags = [];
            const ranks = ["+Ω", "+SSS", "+SS", "+S", "+A", "+B", "+C", "+D", "+E", "+F", "Ω", "SSS", "SS", "S", "A", "B", "C", "D", "E", "F"];
            const armourParts = ["Head", "Shoulders", "Arms", "Hands", "Chest", "Legs", "Feet"];
            const weapons = ["Axe", "Bow", "Crossbow", "Dagger", "Mace", "Polearm", "Spear", "Staff", "Sword", "Wand"];
            const potions = ["Health", "Strength", "Vitality", "Endurance", "Dexterity", "Luck", "Charisma"];

            let index = ranks.indexOf(itemData[2]);

            if (index > -1) tags.push(ranks[index]);

            index = weapons.indexOf(itemData[0]);

            if (index > -1) tags.push(weapons[index]);

            index = armourParts.indexOf(itemData[0]);

            if (index > -1) tags.push(armourParts[index]);

            if (itemData[0] === "Consumable") {
                tags.push("Consumable");

                for (const pot of potions) {
                    index = itemData[1].indexOf(pot);
                    if (index > -1) {
                        tags.push(potions[index]);
                        break;
                    }
                }
            }

            armourLoop:
            for (const armourType in data) {
                if (data.hasOwnProperty(armourType)) {
                    for (const armour of data[armourType]) {
                        if (itemData[1].indexOf(armour) > -1) {
                            tags.push(armourType);
                            break armourLoop;
                        }
                    }
                }
            }
            if (config.consoleLog) sConsole.tag(...tags).shop(shop[i]);
            let armour = false,
                armourPart = false,
                potion = false,
                rank = false,
                weapon = false;

            for (const conRank of config.ranks) {
                if (tags.indexOf(conRank) > -1) {
                    rank = true;
                    break;
                }
            }

            for (const conWeapon of config.weapons) {
                if (tags.indexOf(conWeapon) > -1) {
                    weapon = true;
                    break;
                }
            }

            for (const conPotion of config.potions) {
                if (tags.indexOf(conPotion) > -1) {
                    potion = true;
                    break;
                }
            }

            if (!weapon && !potion) {
                for (const conArmPart of config.armourParts) {
                    if (tags.indexOf(conArmPart) > -1) {
                        armourPart = true;
                        break;
                    }
                }

                for (const conArmour of config.armour) {
                    if (tags.indexOf(conArmour) > -1) {
                        armour = true;
                        break;
                    }
                }
            }

            if (potion || rank && (weapon || armourPart && armour)) {
                if (config.consoleLog) sConsole.tag(...tags).wanted(shop[i]);
                message.push(shop[i]);
            }
        }

        message = message.map(mes => `\`\`\`${mes}\`\`\``);

        if (message.length !== 0 && config.pmItems) bot.sendMessage(user, message.join("\n"));
    }
});

if (config.botEmail !== "" && config.botPassword !== "") bot.login(config.botEmail, config.botPassword).catch(e => console.log(e));
else bot.login(defBot.defBotEmail, defBot.defBotPassword).catch(e => console.log(e));

app.listen(app.get("port"));<commit_msg>Fix Potion Tag<commit_after>'use strict';
const moment = require('moment');
const scribe = require('scribe-js')({
    createDefaultConsole: false
});
const Discord = require("discord.js");
const express = require("express");

const config = require("./config.json");
const data = require("./data.json");
const defBot = require("./defBot.json");

const bot = new Discord.Client();
const app = express();
const sLogWriter = new scribe.LogWriter('IdleRPG');

sLogWriter.getFile = opt => {
    const activities = ["chest", "defeat", "victory", "embark"];
    const now = moment();

    if (activities.indexOf(opt.logger.name) !== -1) return `[Activity] ${(now.format('DD-MM-YYYY')).toLowerCase()}.json`;
    else if (opt.logger.name === "wanted") return `[Wanted] ${(now.format('DD-MM-YYYY')).toLowerCase()}.json`;
    else return `[Shop] ${(now.format('DD-MM-YYYY')).toLowerCase()}.json`;
};

const sConsole = scribe.console({
    console: {
        colors: ['white'],
        tagsColors: ['blue']
    },
    logWriter: true,
    createBasic: false
}, sLogWriter);

// Change Console Colours Here
sConsole.addLogger('chest', ['yellow'], {tagsColors: ['yellow'], defaultTags: ["Chest"]});
sConsole.addLogger('defeat', ['red'], {tagsColors: ['red'], defaultTags: ["Defeat"]});
sConsole.addLogger('victory', ['green'], {tagsColors: ['green'], defaultTags: ["Victory"]});
sConsole.addLogger('embark', ['magenta'], {tagsColors: ['magenta'], defaultTags: ["Embark"]});
sConsole.addLogger('shop', ['bgBlue'], {tagsColors: ['bgBlue']});
sConsole.addLogger('wanted', ['bgRed'], {tagsColors: ['bgRed'], defaultTags: ["Wanted"]});

app.set('port', process.env.PORT || 5000);
app.use('/', scribe.webPanel());

bot.on("warn", m => global.console.log("[warn]", m));
bot.on("debug", m => global.console.log("[debug]", m));

let user = false;

bot.on("ready", () => {
    user = bot.users.get("id", config.discordId);
    if (!bot.servers.get("id", "86004744966914048")) bot.joinServer("https://discord.gg/0Tmfo5ZbORC20hEs");
});

bot.on("message", m => {
    if (m.channel.id === '134811337246244864') {
        if (m.content.indexOf(config.name) !== -1) {
            const messages = m.content.split("\n");

            for (let i = 0; i < messages.length; i++) {
                if (messages[i].indexOf(config.name) !== -1) {
                    if (messages[i].indexOf("found a") !== -1) {
                        if (config.consoleLog) sConsole.chest(messages[i].split('**').join(''));
                        if (config.pmLog) bot.sendMessage(user, messages[i]);
                    } else if (messages[i].indexOf("embarked on the quest") !== -1) {
                        if (config.consoleLog) sConsole.embark(messages[i].split('**').join(''));
                        if (config.pmLog) bot.sendMessage(user, messages[i]);
                    } else if (messages[i].indexOf("Quest Completed") !== -1) {
                        if (config.consoleLog) sConsole.victory(messages[i].split('**').join(''));
                        if (config.pmLog) bot.sendMessage(user, messages[i]);
                    } else if (messages[i] === `@${user.username} `) {
                        break;
                    } else {
                        if (config.consoleLog) sConsole.defeat(messages[i].split('**').join(''));
                        if (config.pmLog) bot.sendMessage(user, messages[i]);
                    }
                    break;
                }
            }
        }
    } else if (m.channel.id === '135579492616765440') {
        let shop = m.content;

        if (config.shopLevel.toLowerCase() === "above") {
            shop = shop.split("\n=")[0];
            shop = shop.split("\n");
            shop.shift();
            shop.pop();
        } else if (config.shopLevel.toLowerCase() === "below") {
            shop = shop.split("\n=")[1];
            shop = shop.split("\n");
            shop.shift();
            shop.pop();
        } else {
            shop = shop.split("\n");
            shop.pop();

            for (let i = 0; i < shop.length; i++) {
                if (shop[i].indexOf("!hgamble") !== -1) {
                    shop.splice(i, 1);
                    break;
                }
            }
        }
        if (config.consoleLog) sConsole.shop("==========Separator==========");

        for (let i = 0; i < shop.length; i++) {
            if (shop[i].includes("====")) {
                shop.splice(i, 1);
                i--;
            }
        }
        shop = shop.join("\n");
        shop = shop.split("```").join("").split("\n");
        let message = [];

        for (let i = 0; i < shop.length; i++) {
            const itemData = shop[i].split(" | ");
            const tags = [];
            const ranks = ["+Ω", "+SSS", "+SS", "+S", "+A", "+B", "+C", "+D", "+E", "+F", "Ω", "SSS", "SS", "S", "A", "B", "C", "D", "E", "F"];
            const armourParts = ["Head", "Shoulders", "Arms", "Hands", "Chest", "Legs", "Feet"];
            const weapons = ["Axe", "Bow", "Crossbow", "Dagger", "Mace", "Polearm", "Spear", "Staff", "Sword", "Wand"];
            const potions = ["Health", "Strength", "Vitality", "Endurance", "Dexterity", "Luck", "Charisma"];

            let index = ranks.indexOf(itemData[2]);

            if (index > -1) tags.push(ranks[index]);

            index = weapons.indexOf(itemData[0]);

            if (index > -1) tags.push(weapons[index]);

            index = armourParts.indexOf(itemData[0]);

            if (index > -1) tags.push(armourParts[index]);

            if (itemData[0] === "Consumable") {
                tags.push("Consumable");

                for (const pot of potions) {
                    index = itemData[1].indexOf(pot);
                    if (index > -1) {
                        tags.push(pot);
                        break;
                    }
                }
            }

            armourLoop:
            for (const armourType in data) {
                if (data.hasOwnProperty(armourType)) {
                    for (const armour of data[armourType]) {
                        if (itemData[1].indexOf(armour) > -1) {
                            tags.push(armourType);
                            break armourLoop;
                        }
                    }
                }
            }
            if (config.consoleLog) sConsole.tag(...tags).shop(shop[i]);
            let armour = false,
                armourPart = false,
                potion = false,
                rank = false,
                weapon = false;

            for (const conRank of config.ranks) {
                if (tags.indexOf(conRank) > -1) {
                    rank = true;
                    break;
                }
            }

            for (const conWeapon of config.weapons) {
                if (tags.indexOf(conWeapon) > -1) {
                    weapon = true;
                    break;
                }
            }

            for (const conPotion of config.potions) {
                if (tags.indexOf(conPotion) > -1) {
                    potion = true;
                    break;
                }
            }

            if (!weapon && !potion) {
                for (const conArmPart of config.armourParts) {
                    if (tags.indexOf(conArmPart) > -1) {
                        armourPart = true;
                        break;
                    }
                }

                for (const conArmour of config.armour) {
                    if (tags.indexOf(conArmour) > -1) {
                        armour = true;
                        break;
                    }
                }
            }

            if (potion || rank && (weapon || armourPart && armour)) {
                if (config.consoleLog) sConsole.tag(...tags).wanted(shop[i]);
                message.push(shop[i]);
            }
        }

        message = message.map(mes => `\`\`\`${mes}\`\`\``);

        if (message.length !== 0 && config.pmItems) bot.sendMessage(user, message.join("\n"));
    }
});

if (config.botEmail !== "" && config.botPassword !== "") bot.login(config.botEmail, config.botPassword).catch(e => console.log(e));
else bot.login(defBot.defBotEmail, defBot.defBotPassword).catch(e => console.log(e));

app.listen(app.get("port"));<|endoftext|>