<commit_before>var express = require('express');
var router = express.Router();
var Workout = require('../models/workout');
var ExerciseDotCom = require('../models/sources/exercise-dot-com');
var User = require('../models/user')
var builder = require('xmlbuilder');
var ObjectId = require('mongoose').Types.ObjectId;

var passport = require('passport')
var LocalStrategy = require('passport-local').Strategy;

passport.use(new LocalStrategy(
  function(username, password, done) {
    User.findOne({ username: username }, function(err, user) {
      if (err) { return done(err); }
      if (!user) {
        return done(null, false, { message: 'Incorrect username.' });
      }
      if (!user.validPassword(password)) {
        return done(null, false, { message: 'Incorrect password.' });
      }
      return done(null, user);
    });
  }
));

passport.serializeUser(function(user, done) {
  done(null, user._id);
});

passport.deserializeUser(function(id, done) {
  User.findById(id, function(err, user) {
    done(err, user);
  });
});

/* GET users listing. */
router.get('/', function(req, res, next) {
  res.send('respond with a resource');
});

// router.post('/register', function (req, res, next) {
//
// });

router.post('/login', passport.authenticate('local', {
  successRedirect: '/',
  failureRedirect: '/login',
  failureFlash: true
}));

router.get('/:id/workouts', function (req, res, next) {
  var userId = decodeURIComponent(req.params.id);
  var from = req.query.from;
  var to = req.query.to;
  var sendData = builder.create('data')
    .ele('workouts');
  ExerciseDotCom.find({
    'userEmail': userId,
    // 'used': {
    //   $ne: true
    // }
  }, function (err, workouts) {
    if (err) {
      res.send(err);
      return;
    }

    // Each unsent workout.
    for(var i in workouts) {
      var health = 0;
      var stamina = 0;
      var magicka = 0;

      for (var j in workouts[i].data.workout_exercises) {
        if (workouts[i].data.workout_exercises.hasOwnProperty(j)) {
          var exerciseData = workouts[i].data.workout_exercises[j];
          if (exerciseData.hasOwnProperty('total_reps') && exerciseData.total_reps > 0) {
            // Health
            health += exerciseData.total_points;
          }
          else if (exerciseData.hasOwnProperty('distance') && typeof parseFloat(exerciseData['distance']) === 'number' && parseFloat(exerciseData.distance) > 0) {
            // Stamina
            stamina += exerciseData.total_points;
          } else {
            // Magicka
            magicka += exerciseData.total_points;
          }
        }
      }
      // console.log(workouts[i]);
      sendData.ele('workout').ele({
        syncDate: (new Date(Date.now())).toISOString(),
        workoutDate: (new Date(workouts[i].data.workout_date * 1000)).toISOString(),
        health: health,
        stamina: stamina,
        magicka: magicka
      }).up();
      workouts[i].used = true;
      workouts[i].save();
    }
    var str = sendData.end({pretty: true});
    console.log(str);
    res.send(str);
  });
});

module.exports = router;
<commit_msg>Only workouts between specific dates are returned.<commit_after>var express = require('express');
var router = express.Router();
var Workout = require('../models/workout');
var ExerciseDotCom = require('../models/sources/exercise-dot-com');
var User = require('../models/user')
var builder = require('xmlbuilder');
var ObjectId = require('mongoose').Types.ObjectId;

var passport = require('passport')
var LocalStrategy = require('passport-local').Strategy;

passport.use(new LocalStrategy(
  function(username, password, done) {
    User.findOne({ username: username }, function(err, user) {
      if (err) { return done(err); }
      if (!user) {
        return done(null, false, { message: 'Incorrect username.' });
      }
      if (!user.validPassword(password)) {
        return done(null, false, { message: 'Incorrect password.' });
      }
      return done(null, user);
    });
  }
));

passport.serializeUser(function(user, done) {
  done(null, user._id);
});

passport.deserializeUser(function(id, done) {
  User.findById(id, function(err, user) {
    done(err, user);
  });
});

/* GET users listing. */
router.get('/', function(req, res, next) {
  res.send('respond with a resource');
});

// router.post('/register', function (req, res, next) {
//
// });

router.post('/login', passport.authenticate('local', {
  successRedirect: '/',
  failureRedirect: '/login',
  failureFlash: true
}));

router.get('/:id/workouts/:from/:to', function (req, res, next) {
  var userId = decodeURIComponent(req.params.id);
  var from = req.params.from;
  var to = req.params.to;
  console.log(from);
  console.log(to);
  var sendData = builder.create('data')
    .ele('workouts');
  ExerciseDotCom.find({
    userEmail: userId,
    dateRetrieved: {
      $gt: new Date(parseInt(from)),
      $lt: new Date(parseInt(to))
    }
    // dateRetrieved: { $gt: new Date(1461200235423), $lt: new Date(1461200235425) }
  }, function (err, workouts) {
    if (err) {
      res.send(err);
      return;
    }

    // Each unsent workout.
    for(var i in workouts) {
      var health = 0;
      var stamina = 0;
      var magicka = 0;

      for (var j in workouts[i].data.workout_exercises) {
        if (workouts[i].data.workout_exercises.hasOwnProperty(j)) {
          var exerciseData = workouts[i].data.workout_exercises[j];
          if (exerciseData.hasOwnProperty('total_reps') && exerciseData.total_reps > 0) {
            // Health
            health += exerciseData.total_points;
          }
          else if (exerciseData.hasOwnProperty('distance') && typeof parseFloat(exerciseData['distance']) === 'number' && parseFloat(exerciseData.distance) > 0) {
            // Stamina
            stamina += exerciseData.total_points;
          } else {
            // Magicka
            magicka += exerciseData.total_points;
          }
        }
      }
      // console.log(workouts[i]);
      sendData.ele('workout').ele({
        syncDate: (new Date(Date.now())).toISOString(),
        workoutDate: (new Date(workouts[i].data.workout_date * 1000)).toISOString(),
        health: health,
        stamina: stamina,
        magicka: magicka
      }).up();
      workouts[i].used = true;
      workouts[i].save();
    }
    var str = sendData.end({pretty: true});
    console.log(str);
    res.send(str);
  });
});

module.exports = router;
<|endoftext|>


<commit_before>var express = require('express');
var router = express.Router();
require('dotenv').load();
var db = require('monk')(process.env.MONGOLAB_URI);
var students = db.get('students-assessment') // Somehow the name of the db became the identity function of the activity.  Triple pun score.
var users = db.get('users-assessment');
var bcrypt = require('bcrypt');

/* GET users listing. */
router.get('/', function(req, res, next) {
  res.render('index', {title: "Users With Crud"});
});

router.get('/signup', function(req, res, next) {
  res.render('signup');
});

router.post('/signup', function(req, res, next) {
  if(req.session.signedIn) {
    res.redirect('/students')
  }
  var errors = []; // error accumulation
  //console.log(req.body.loginPass, req.body.loginEmail);
  // validate input
  if(req.body.loginPass.length < 8) {
    errors.push("The password must be longer than 8 characters")
  }
  if((new RegExp('^\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,3}$').test(req.body.loginEmail))) {
    errors.push("Valid email address required.")
  }
  users.find({
    loginEmail: req.body.loginEmail
  }, function(userEntry) {
    if(userEntry) {
      errors.push("That email is already in use by someone else, or by you")
    }
    if(errors.length > 0) {
      res.render('signup', {errors: errors});
    }
    if(errors.length < 1) {
      // hash password
      // insert into users db.
      users.insert({
        loginEmail: req.body.loginEmail,
        loginPass: bcrypt.hashSync(req.body.loginPass, 12)
      });
      req.session.signedIn = true;
      req.session.name = req.body.loginEmail;
    }
    res.redirect('/users/students')
  });
});

router.get('/signin', function (req, res, next) {
  if(req.session.name) { req.body.name = req.session.name; }
  else { req.body.name = '';} // if previous attempt at login failed, populate field with name from prev. attempt

  res.render('signin', {
    title: 'the sign in page',
    name: req.body.name
  });
});
// signin is unfinished
router.post('/signin', function(req, res, next) {
  //set cookie
  req.session.name = req.body.name;
  //validate input by checking database
  //check usersdb for password with bcrypt.compare()

  users.findOne({loginEmail:req.body.email}, function(userEntry) {
    if(bcrypt.compare(req.body.loginPass, userEntry.loginPass)) {
      req.session.signedIn = true;
      req.session.name = userEntry.loginEmail;
    }
  });
  // if true, login, change cookie , etc...
});

router.get('/signout', function(req, res, next) {
  req.session = null; // cookie deleted
  res.render('/signin');
});

function authdPredicate (cookie) {
  if(!cookie.signedIn) {
    res.redirect('/users/signin');
  }
  return null;
}
// only users can use these, so check cookie and redirect if necessary
router.get('/students/add', function(req, res, next) {
  authdPredicate(req.session);
  res.render('addstudent');
});

router.post('/students/add', function(req, res, next) {
  authdPredicate(req.session);
  var errors = [];
  if(req.body.studentname.length < 1) {
    errors.push("The students name must be filled in")
  }
  if((new RegExp('^\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,3}$').test(req.body.studentemail))) {
    errors.push("The students email must be a valid email address.")
  }
  if(errors.length > 0 ){
      res.render('addstudent', {
      errors: errors
    });
  }
  if(errors.length < 1) {
    students.insert({
      name: req.body.studentname,
      email: req.body.studentemail
    });
    res.redirect('/users/students');
  }
});

// since it's student or students, careful of plural vs nonplural
router.get('/students', function(req, res, next) {
  authdPredicate(req.session);
  students.find({}, function(err, studentsList) {
    res.render('students', {
      title: 'Students listing',
      students: studentsList
    });
  });
});

router.get('/students/:id', function(req, res, next) {
  authdPredicate(req.session);
  students.findOne({_id: req.params.id}, function(err, singleStudent) {
    res.render('displaystudent', {
      title: "Single Student Info Display",
      studentname: singleStudent.name,
      studentemail: singleStudent.email
    });
  });
});

module.exports = router;
<commit_msg>Re-did redirects to right places now<commit_after>var express = require('express');
var router = express.Router();
require('dotenv').load();
var db = require('monk')(process.env.MONGOLAB_URI);
var students = db.get('students-assessment') // Somehow the name of the db became the identity function of the activity.  Triple pun score.
var users = db.get('users-assessment');
var bcrypt = require('bcrypt');

/* GET users listing. */
router.get('/', function(req, res, next) {
  res.render('index', {title: "Users With Crud"});
});

router.get('/signup', function(req, res, next) {
  res.render('signup');
});

router.post('/signup', function(req, res, next) {
  if(req.session.signedIn) {
    res.redirect('/students')
  }
  var errors = []; // error accumulation
  //console.log(req.body.loginPass, req.body.loginEmail);
  // validate input
  if(req.body.loginPass.length < 8) {
    errors.push("The password must be longer than 8 characters")
  }
  if((new RegExp('^\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,3}$').test(req.body.loginEmail))) {
    errors.push("Valid email address required.")
  }
  users.find({
    loginEmail: req.body.loginEmail
  }, function(userEntry) {
    if(userEntry) {
      errors.push("That email is already in use by someone else, or by you")
    }
    if(errors.length > 0) {
      res.render('signup', {errors: errors});
    }
    if(errors.length < 1) {
      // hash password
      // insert into users db.
      users.insert({
        loginEmail: req.body.loginEmail,
        loginPass: bcrypt.hashSync(req.body.loginPass, 12)
      });
      req.session.signedIn = true;
      req.session.name = req.body.loginEmail;
    }
    res.redirect('/students')
  });
});

router.get('/signin', function (req, res, next) {
  if(req.session.name) { req.body.name = req.session.name; }
  else { req.body.name = '';} // if previous attempt at login failed, populate field with name from prev. attempt

  res.render('signin', {
    title: 'the sign in page',
    name: req.body.name
  });
});
// signin is unfinished
router.post('/signin', function(req, res, next) {
  //set cookie
  req.session.name = req.body.name;
  //validate input by checking database
  //check usersdb for password with bcrypt.compare()

  users.findOne({loginEmail:req.body.email}, function(userEntry) {
    if(bcrypt.compare(req.body.loginPass, userEntry.loginPass)) {
      req.session.signedIn = true;
      req.session.name = userEntry.loginEmail;
    }
  });
  // if true, login, change cookie , etc...
});

router.get('/signout', function(req, res, next) {
  req.session = null; // cookie deleted
  res.render('/signin');
});

function authdPredicate (cookie) {
  if(!cookie.signedIn) {
    res.redirect('/signin');
  }
  return null;
}
// only users can use these, so check cookie and redirect if necessary
router.get('/students/add', function(req, res, next) {
  authdPredicate(req.session);
  res.render('addstudent');
});

router.post('/students/add', function(req, res, next) {
  authdPredicate(req.session);
  var errors = [];
  if(req.body.studentname.length < 1) {
    errors.push("The students name must be filled in")
  }
  if((new RegExp('^\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,3}$').test(req.body.studentemail))) {
    errors.push("The students email must be a valid email address.")
  }
  if(errors.length > 0 ){
      res.render('addstudent', {
      errors: errors
    });
  }
  if(errors.length < 1) {
    students.insert({
      name: req.body.studentname,
      email: req.body.studentemail
    });
    res.redirect('/students');
  }
});

// since it's student or students, careful of plural vs nonplural
router.get('/students', function(req, res, next) {
  authdPredicate(req.session);
  students.find({}, function(err, studentsList) {
    res.render('students', {
      title: 'Students listing',
      students: studentsList
    });
  });
});

router.get('/students/:id', function(req, res, next) {
  authdPredicate(req.session);
  students.findOne({_id: req.params.id}, function(err, singleStudent) {
    res.render('displaystudent', {
      title: "Single Student Info Display",
      studentname: singleStudent.name,
      studentemail: singleStudent.email
    });
  });
});

module.exports = router;
<|endoftext|>


<commit_before>var express = require('express');
var router = express.Router();
var mysql = require('mysql');
var db = mysql.createConnection(process.env.JAWSDB_MARIA_URL);

function stripAlphaChars(source) {
  var out = source.replace(/[^0-9]/g, '');

  return out;
}

/*
 * GET userlist.
 */
router.get('/', function(req, res) {

  db.query('SELECT m.* FROM sarjataulukkodata m LEFT JOIN sarjataulukkodata b ON m.team_id = b.team_id AND m.kierros_id < b.kierros_id AND b.season_id = 1 WHERE b.kierros_id IS NULL AND m.season_id = 1 ORDER BY m.team_id', function(err, rows, fields) {
      console.log('Connection result error '+err);
      if (err) throw err;

      console.log('Connection result error '+err);
      console.log('no of records is '+rows.length);
      res.json(rows);

      });
});
router.get('/2016/:kierrosId', function(req, res) {
  var kierros = 0;
  kierros = kierros + parseInt(req.params.kierrosId) + 1;
  var sql = 'SELECT m.* FROM sarjataulukkodata m LEFT JOIN sarjataulukkodata b ON m.team_id = b.team_id AND m.kierros_id < b.kierros_id AND b.kierros_id < '+db.escape(kierros)+' AND b.season_id = 1 WHERE b.kierros_id IS NULL AND m.kierros_id < '+db.escape(kierros)+' m.season_id = 1 ORDER BY m.team_id';
  db.query(sql, function(err, rows, fields) {
      console.log('Connection result error '+err);
      if (err) throw err;

      console.log('Connection result error '+err);
      console.log('no of records is '+rows.length);
      res.json(rows);

      });
});

module.exports = router;
<commit_msg>moar testing<commit_after>var express = require('express');
var router = express.Router();
var mysql = require('mysql');
var db = mysql.createConnection(process.env.JAWSDB_MARIA_URL);

function stripAlphaChars(source) {
  var out = source.replace(/[^0-9]/g, '');

  return out;
}

/*
 * GET userlist.
 */
router.get('/', function(req, res) {

  db.query('SELECT m.* FROM sarjataulukkodata m LEFT JOIN sarjataulukkodata b ON m.team_id = b.team_id AND m.kierros_id < b.kierros_id AND b.season_id = 1 WHERE b.kierros_id IS NULL AND m.season_id = 1 ORDER BY m.team_id', function(err, rows, fields) {
      console.log('Connection result error '+err);
      if (err) throw err;

      console.log('Connection result error '+err);
      console.log('no of records is '+rows.length);
      res.json(rows);

      });
});
router.get('/2016/:kierrosId', function(req, res) {
  var kierros = 0;
  kierros = kierros + parseInt(req.params.kierrosId) + 1;
  var sql = 'SELECT m.* FROM sarjataulukkodata m LEFT JOIN sarjataulukkodata b ON m.team_id = b.team_id AND m.kierros_id < b.kierros_id AND b.kierros_id < '+db.escape(kierros)+' AND b.season_id = 1 WHERE b.kierros_id IS NULL AND m.kierros_id < '+db.escape(kierros)+' AND m.season_id = 1 ORDER BY m.team_id';
  db.query(sql, function(err, rows, fields) {
      console.log('Connection result error '+err);
      if (err) throw err;

      console.log('Connection result error '+err);
      console.log('no of records is '+rows.length);
      res.json(rows);

      });
});

module.exports = router;
<|endoftext|>


<commit_before>var mongo = require('mongodb');

var Server = mongo.Server,
    Db = mongo.Db,
    BSON = mongo.BSONPure;

var server = new Server('localhost', 27017, {auto_reconnect: true});
db = new Db('winedb', server);

db.open(function(err, db) {
    if(!err) {
        console.log("Connected to 'winedb' database");
        db.collection('wines', {safe:true}, function(err, collection) {
            if (err) {
                console.log("The 'wines' collection doesn't exist. Creating it with sample data...");
                populateDB();
            }
        });
    }
});

exports.findById = function(req, res) {
    var id = req.params.id;
    console.log('Retrieving wine: ' + id);
    db.collection('wines', function(err, collection) {
        collection.findOne({'_id':new BSON.ObjectID(id)}, function(err, item) {
            res.send(item);
        });
    });
};

exports.findAll = function(req, res) {
    db.collection('wines', function(err, collection) {
        collection.find().toArray(function(err, items) {
            res.send(items);
        });
    });
};

exports.addWine = function(req, res) {
    var wine = req.body;
    console.log('Adding wine: ' + JSON.stringify(wine));
    db.collection('wines', function(err, collection) {
        collection.insert(wine, {safe:true}, function(err, result) {
            if (err) {
                res.send({'error':'An error has occurred'});
            } else {
                console.log('Success: ' + JSON.stringify(result[0]));
                res.send(result[0]);
            }
        });
    });
    res.send(wine);
}

exports.updateWine = function(req, res) {
    var id = req.params.id;
    var wine = req.body;
    delete wine._id;
    console.log('Updating wine: ' + id);
    console.log(JSON.stringify(wine));
    db.collection('wines', function(err, collection) {
        collection.update({'_id':new BSON.ObjectID(id)}, wine, {safe:true}, function(err, result) {
            if (err) {
                console.log('Error updating wine: ' + err);
                res.send({'error':'An error has occurred'});
            } else {
                console.log('' + result + ' document(s) updated');
                res.send(wine);
            }
        });
    });
    res.send(wine);
}

exports.deleteWine = function(req, res) {
    var id = req.params.id;
    console.log('Deleting wine: ' + id);
    db.collection('wines', function(err, collection) {
        collection.remove({'_id':new BSON.ObjectID(id)}, {safe:true}, function(err, result) {
            if (err) {
                res.send({'error':'An error has occurred - ' + err});
            } else {
                console.log('' + result + ' document(s) deleted');
                res.send(req.body);
            }
        });
    });
      res.send(req.body);
}

/*--------------------------------------------------------------------------------------------------------------------*/
// Populate database with sample data -- Only used once: the first time the application is started.
// You'd typically not find this code in a real-life app, since the database would already exist.
var populateDB = function() {

    var wines = [
    {
        name: "CHATEAU DE SAINT COSME",
        year: "2009",
        grapes: "Grenache / Syrah",
        country: "France",
        region: "Southern Rhone",
        description: "The aromas of fruit and spice give one a hint of the light drinkability of this lovely wine, which makes an excellent complement to fish dishes.",
        picture: "saint_cosme.jpg"
    },
    {
        name: "LAN RIOJA CRIANZA",
        year: "2006",
        grapes: "Tempranillo",
        country: "Spain",
        region: "Rioja",
        description: "A resurgence of interest in boutique vineyards has opened the door for this excellent foray into the dessert wine market. Light and bouncy, with a hint of black truffle, this wine will not fail to tickle the taste buds.",
        picture: "lan_rioja.jpg"
    },
    {
        name: "MARGERUM SYBARITE",
        year: "2010",
        grapes: "Sauvignon Blanc",
        country: "USA",
        region: "California Central Cosat",
        description: "The cache of a fine Cabernet in ones wine cellar can now be replaced with a childishly playful wine bubbling over with tempting tastes of black cherry and licorice. This is a taste sure to transport you back in time.",
        picture: "margerum.jpg"
    },
    {
        name: "OWEN ROE \"EX UMBRIS\"",
        year: "2009",
        grapes: "Syrah",
        country: "USA",
        region: "Washington",
        description: "A one-two punch of black pepper and jalapeno will send your senses reeling, as the orange essence snaps you back to reality. Don't miss this award-winning taste sensation.",
        picture: "ex_umbris.jpg"
    },
    {
        name: "REX HILL",
        year: "2009",
        grapes: "Pinot Noir",
        country: "USA",
        region: "Oregon",
        description: "One cannot doubt that this will be the wine served at the Hollywood award shows, because it has undeniable star power. Be the first to catch the debut that everyone will be talking about tomorrow.",
        picture: "rex_hill.jpg"
    },
    {
        name: "VITICCIO CLASSICO RISERVA",
        year: "2007",
        grapes: "Sangiovese Merlot",
        country: "Italy",
        region: "Tuscany",
        description: "Though soft and rounded in texture, the body of this wine is full and rich and oh-so-appealing. This delivery is even more impressive when one takes note of the tender tannins that leave the taste buds wholly satisfied.",
        picture: "viticcio.jpg"
    },
    {
        name: "CHATEAU LE DOYENNE",
        year: "2005",
        grapes: "Merlot",
        country: "France",
        region: "Bordeaux",
        description: "Though dense and chewy, this wine does not overpower with its finely balanced depth and structure. It is a truly luxurious experience for the senses.",
        picture: "le_doyenne.jpg"
    },
    {
        name: "DOMAINE DU BOUSCAT",
        year: "2009",
        grapes: "Merlot",
        country: "France",
        region: "Bordeaux",
        description: "The light golden color of this wine belies the bright flavor it holds. A true summer wine, it begs for a picnic lunch in a sun-soaked vineyard.",
        picture: "bouscat.jpg"
    },
    {
        name: "BLOCK NINE",
        year: "2009",
        grapes: "Pinot Noir",
        country: "USA",
        region: "California",
        description: "With hints of ginger and spice, this wine makes an excellent complement to light appetizer and dessert fare for a holiday gathering.",
        picture: "block_nine.jpg"
    },
    {
        name: "DOMAINE SERENE",
        year: "2007",
        grapes: "Pinot Noir",
        country: "USA",
        region: "Oregon",
        description: "Though subtle in its complexities, this wine is sure to please a wide range of enthusiasts. Notes of pomegranate will delight as the nutty finish completes the picture of a fine sipping experience.",
        picture: "domaine_serene.jpg"
    },
    {
        name: "BODEGA LURTON",
        year: "2011",
        grapes: "Pinot Gris",
        country: "Argentina",
        region: "Mendoza",
        description: "Solid notes of black currant blended with a light citrus make this wine an easy pour for varied palates.",
        picture: "bodega_lurton.jpg"
    },
    {
        name: "LES MORIZOTTES",
        year: "2009",
        grapes: "Chardonnay",
        country: "France",
        region: "Burgundy",
        description: "Breaking the mold of the classics, this offering will surprise and undoubtedly get tongues wagging with the hints of coffee and tobacco in perfect alignment with more traditional notes. Sure to please the late-night crowd with the slight jolt of adrenaline it brings.",
        picture: "morizottes.jpg"
    },
    {
        name: "ARGIANO NON CONFUNDITUR",
        year: "2009",
        grapes: "Cabernet Sauvignon",
        country: "Italy",
        region: "Tuscany",
        description: "Like a symphony, this cabernet has a wide range of notes that will delight the taste buds and linger in the mind.",
        picture: "argiano.jpg"
    },
    {
        name: "DINASTIA VIVANCO ",
        year: "2008",
        grapes: "Tempranillo",
        country: "Spain",
        region: "Rioja",
        description: "Whether enjoying a fine cigar or a nicotine patch, don't pass up a taste of this hearty Rioja, both smooth and robust.",
        picture: "dinastia.jpg"
    },
    {
        name: "PETALOS BIERZO",
        year: "2009",
        grapes: "Mencia",
        country: "Spain",
        region: "Castilla y Leon",
        description: "For the first time, a blend of grapes from two different regions have been combined in an outrageous explosion of flavor that cannot be missed.",
        picture: "petalos.jpg"
    },
    {
        name: "SHAFER RED SHOULDER RANCH",
        year: "2009",
        grapes: "Chardonnay",
        country: "USA",
        region: "California",
        description: "Keep an eye out for this winery in coming years, as their chardonnays have reached the peak of perfection.",
        picture: "shafer.jpg"
    },
    {
        name: "PONZI",
        year: "2010",
        grapes: "Pinot Gris",
        country: "USA",
        region: "Oregon",
        description: "For those who appreciate the simpler pleasures in life, this light pinot grigio will blend perfectly with a light meal or as an after dinner drink.",
        picture: "ponzi.jpg"
    },
    {
        name: "HUGEL",
        year: "2010",
        grapes: "Pinot Gris",
        country: "France",
        region: "Alsace",
        description: "Fresh as new buds on a spring vine, this dewy offering is the finest of the new generation of pinot grigios.  Enjoy it with a friend and a crown of flowers for the ultimate wine tasting experience.",
        picture: "hugel.jpg"
    },
    {
        name: "FOUR VINES MAVERICK",
        year: "2011",
        grapes: "Zinfandel",
        country: "USA",
        region: "California",
        description: "o yourself a favor and have a bottle (or two) of this fine zinfandel on hand for your next romantic outing.  The only thing that can make this fine choice better is the company you share it with.",
        picture: "fourvines.jpg"
    },
    {
        name: "QUIVIRA DRY CREEK VALLEY",
        year: "2009",
        grapes: "Zinfandel",
        country: "USA",
        region: "California",
        description: "Rarely do you find a zinfandel this oakey from the Sonoma region. The vintners have gone to extremes to duplicate the classic flavors that brought high praise in the early '90s.",
        picture: "quivira.jpg"
    },
    {
        name: "CALERA 35TH ANNIVERSARY",
        year: "2010",
        grapes: "Pinot Noir",
        country: "USA",
        region: "California",
        description: "Fruity and bouncy, with a hint of spice, this pinot noir is an excellent candidate for best newcomer from Napa this year.",
        picture: "calera.jpg"
    },
    {
        name: "CHATEAU CARONNE STE GEMME",
        year: "2010",
        grapes: "Cabernet Sauvignon",
        country: "France",
        region: "Bordeaux",
        description: "Find a sommelier with a taste for chocolate and he's guaranteed to have this cabernet on his must-have list.",
        picture: "caronne.jpg"
    },
    {
        name: "MOMO MARLBOROUGH",
        year: "2010",
        grapes: "Sauvignon Blanc",
        country: "New Zealand",
        region: "South Island",
        description: "Best served chilled with melon or a nice salty prosciutto, this sauvignon blanc is a staple in every Italian kitchen, if not on their wine list.  Request the best, and you just may get it.",
        picture: "momo.jpg"
    },
    {
        name: "WATERBROOK",
        year: "2009",
        grapes: "Merlot",
        country: "USA",
        region: "Washington",
        description: "Legend has it the gods didn't share their ambrosia with mere mortals.  This merlot may be the closest we've ever come to a taste of heaven.",
        picture: "waterbrook.jpg"
    }];

    db.collection('wines', function(err, collection) {
        collection.insert(wines, {safe:true}, function(err, result) {});
    });

};<commit_msg>Removed extra res.send()<commit_after>var mongo = require('mongodb');

var Server = mongo.Server,
    Db = mongo.Db,
    BSON = mongo.BSONPure;

var server = new Server('localhost', 27017, {auto_reconnect: true});
db = new Db('winedb', server);

db.open(function(err, db) {
    if(!err) {
        console.log("Connected to 'winedb' database");
        db.collection('wines', {safe:true}, function(err, collection) {
            if (err) {
                console.log("The 'wines' collection doesn't exist. Creating it with sample data...");
                populateDB();
            }
        });
    }
});

exports.findById = function(req, res) {
    var id = req.params.id;
    console.log('Retrieving wine: ' + id);
    db.collection('wines', function(err, collection) {
        collection.findOne({'_id':new BSON.ObjectID(id)}, function(err, item) {
            res.send(item);
        });
    });
};

exports.findAll = function(req, res) {
    db.collection('wines', function(err, collection) {
        collection.find().toArray(function(err, items) {
            res.send(items);
        });
    });
};

exports.addWine = function(req, res) {
    var wine = req.body;
    console.log('Adding wine: ' + JSON.stringify(wine));
    db.collection('wines', function(err, collection) {
        collection.insert(wine, {safe:true}, function(err, result) {
            if (err) {
                res.send({'error':'An error has occurred'});
            } else {
                console.log('Success: ' + JSON.stringify(result[0]));
                res.send(result[0]);
            }
        });
    });
}

exports.updateWine = function(req, res) {
    var id = req.params.id;
    var wine = req.body;
    delete wine._id;
    console.log('Updating wine: ' + id);
    console.log(JSON.stringify(wine));
    db.collection('wines', function(err, collection) {
        collection.update({'_id':new BSON.ObjectID(id)}, wine, {safe:true}, function(err, result) {
            if (err) {
                console.log('Error updating wine: ' + err);
                res.send({'error':'An error has occurred'});
            } else {
                console.log('' + result + ' document(s) updated');
                res.send(wine);
            }
        });
    });
}

exports.deleteWine = function(req, res) {
    var id = req.params.id;
    console.log('Deleting wine: ' + id);
    db.collection('wines', function(err, collection) {
        collection.remove({'_id':new BSON.ObjectID(id)}, {safe:true}, function(err, result) {
            if (err) {
                res.send({'error':'An error has occurred - ' + err});
            } else {
                console.log('' + result + ' document(s) deleted');
                res.send(req.body);
            }
        });
    });
}

/*--------------------------------------------------------------------------------------------------------------------*/
// Populate database with sample data -- Only used once: the first time the application is started.
// You'd typically not find this code in a real-life app, since the database would already exist.
var populateDB = function() {

    var wines = [
    {
        name: "CHATEAU DE SAINT COSME",
        year: "2009",
        grapes: "Grenache / Syrah",
        country: "France",
        region: "Southern Rhone",
        description: "The aromas of fruit and spice give one a hint of the light drinkability of this lovely wine, which makes an excellent complement to fish dishes.",
        picture: "saint_cosme.jpg"
    },
    {
        name: "LAN RIOJA CRIANZA",
        year: "2006",
        grapes: "Tempranillo",
        country: "Spain",
        region: "Rioja",
        description: "A resurgence of interest in boutique vineyards has opened the door for this excellent foray into the dessert wine market. Light and bouncy, with a hint of black truffle, this wine will not fail to tickle the taste buds.",
        picture: "lan_rioja.jpg"
    },
    {
        name: "MARGERUM SYBARITE",
        year: "2010",
        grapes: "Sauvignon Blanc",
        country: "USA",
        region: "California Central Cosat",
        description: "The cache of a fine Cabernet in ones wine cellar can now be replaced with a childishly playful wine bubbling over with tempting tastes of black cherry and licorice. This is a taste sure to transport you back in time.",
        picture: "margerum.jpg"
    },
    {
        name: "OWEN ROE \"EX UMBRIS\"",
        year: "2009",
        grapes: "Syrah",
        country: "USA",
        region: "Washington",
        description: "A one-two punch of black pepper and jalapeno will send your senses reeling, as the orange essence snaps you back to reality. Don't miss this award-winning taste sensation.",
        picture: "ex_umbris.jpg"
    },
    {
        name: "REX HILL",
        year: "2009",
        grapes: "Pinot Noir",
        country: "USA",
        region: "Oregon",
        description: "One cannot doubt that this will be the wine served at the Hollywood award shows, because it has undeniable star power. Be the first to catch the debut that everyone will be talking about tomorrow.",
        picture: "rex_hill.jpg"
    },
    {
        name: "VITICCIO CLASSICO RISERVA",
        year: "2007",
        grapes: "Sangiovese Merlot",
        country: "Italy",
        region: "Tuscany",
        description: "Though soft and rounded in texture, the body of this wine is full and rich and oh-so-appealing. This delivery is even more impressive when one takes note of the tender tannins that leave the taste buds wholly satisfied.",
        picture: "viticcio.jpg"
    },
    {
        name: "CHATEAU LE DOYENNE",
        year: "2005",
        grapes: "Merlot",
        country: "France",
        region: "Bordeaux",
        description: "Though dense and chewy, this wine does not overpower with its finely balanced depth and structure. It is a truly luxurious experience for the senses.",
        picture: "le_doyenne.jpg"
    },
    {
        name: "DOMAINE DU BOUSCAT",
        year: "2009",
        grapes: "Merlot",
        country: "France",
        region: "Bordeaux",
        description: "The light golden color of this wine belies the bright flavor it holds. A true summer wine, it begs for a picnic lunch in a sun-soaked vineyard.",
        picture: "bouscat.jpg"
    },
    {
        name: "BLOCK NINE",
        year: "2009",
        grapes: "Pinot Noir",
        country: "USA",
        region: "California",
        description: "With hints of ginger and spice, this wine makes an excellent complement to light appetizer and dessert fare for a holiday gathering.",
        picture: "block_nine.jpg"
    },
    {
        name: "DOMAINE SERENE",
        year: "2007",
        grapes: "Pinot Noir",
        country: "USA",
        region: "Oregon",
        description: "Though subtle in its complexities, this wine is sure to please a wide range of enthusiasts. Notes of pomegranate will delight as the nutty finish completes the picture of a fine sipping experience.",
        picture: "domaine_serene.jpg"
    },
    {
        name: "BODEGA LURTON",
        year: "2011",
        grapes: "Pinot Gris",
        country: "Argentina",
        region: "Mendoza",
        description: "Solid notes of black currant blended with a light citrus make this wine an easy pour for varied palates.",
        picture: "bodega_lurton.jpg"
    },
    {
        name: "LES MORIZOTTES",
        year: "2009",
        grapes: "Chardonnay",
        country: "France",
        region: "Burgundy",
        description: "Breaking the mold of the classics, this offering will surprise and undoubtedly get tongues wagging with the hints of coffee and tobacco in perfect alignment with more traditional notes. Sure to please the late-night crowd with the slight jolt of adrenaline it brings.",
        picture: "morizottes.jpg"
    },
    {
        name: "ARGIANO NON CONFUNDITUR",
        year: "2009",
        grapes: "Cabernet Sauvignon",
        country: "Italy",
        region: "Tuscany",
        description: "Like a symphony, this cabernet has a wide range of notes that will delight the taste buds and linger in the mind.",
        picture: "argiano.jpg"
    },
    {
        name: "DINASTIA VIVANCO ",
        year: "2008",
        grapes: "Tempranillo",
        country: "Spain",
        region: "Rioja",
        description: "Whether enjoying a fine cigar or a nicotine patch, don't pass up a taste of this hearty Rioja, both smooth and robust.",
        picture: "dinastia.jpg"
    },
    {
        name: "PETALOS BIERZO",
        year: "2009",
        grapes: "Mencia",
        country: "Spain",
        region: "Castilla y Leon",
        description: "For the first time, a blend of grapes from two different regions have been combined in an outrageous explosion of flavor that cannot be missed.",
        picture: "petalos.jpg"
    },
    {
        name: "SHAFER RED SHOULDER RANCH",
        year: "2009",
        grapes: "Chardonnay",
        country: "USA",
        region: "California",
        description: "Keep an eye out for this winery in coming years, as their chardonnays have reached the peak of perfection.",
        picture: "shafer.jpg"
    },
    {
        name: "PONZI",
        year: "2010",
        grapes: "Pinot Gris",
        country: "USA",
        region: "Oregon",
        description: "For those who appreciate the simpler pleasures in life, this light pinot grigio will blend perfectly with a light meal or as an after dinner drink.",
        picture: "ponzi.jpg"
    },
    {
        name: "HUGEL",
        year: "2010",
        grapes: "Pinot Gris",
        country: "France",
        region: "Alsace",
        description: "Fresh as new buds on a spring vine, this dewy offering is the finest of the new generation of pinot grigios.  Enjoy it with a friend and a crown of flowers for the ultimate wine tasting experience.",
        picture: "hugel.jpg"
    },
    {
        name: "FOUR VINES MAVERICK",
        year: "2011",
        grapes: "Zinfandel",
        country: "USA",
        region: "California",
        description: "o yourself a favor and have a bottle (or two) of this fine zinfandel on hand for your next romantic outing.  The only thing that can make this fine choice better is the company you share it with.",
        picture: "fourvines.jpg"
    },
    {
        name: "QUIVIRA DRY CREEK VALLEY",
        year: "2009",
        grapes: "Zinfandel",
        country: "USA",
        region: "California",
        description: "Rarely do you find a zinfandel this oakey from the Sonoma region. The vintners have gone to extremes to duplicate the classic flavors that brought high praise in the early '90s.",
        picture: "quivira.jpg"
    },
    {
        name: "CALERA 35TH ANNIVERSARY",
        year: "2010",
        grapes: "Pinot Noir",
        country: "USA",
        region: "California",
        description: "Fruity and bouncy, with a hint of spice, this pinot noir is an excellent candidate for best newcomer from Napa this year.",
        picture: "calera.jpg"
    },
    {
        name: "CHATEAU CARONNE STE GEMME",
        year: "2010",
        grapes: "Cabernet Sauvignon",
        country: "France",
        region: "Bordeaux",
        description: "Find a sommelier with a taste for chocolate and he's guaranteed to have this cabernet on his must-have list.",
        picture: "caronne.jpg"
    },
    {
        name: "MOMO MARLBOROUGH",
        year: "2010",
        grapes: "Sauvignon Blanc",
        country: "New Zealand",
        region: "South Island",
        description: "Best served chilled with melon or a nice salty prosciutto, this sauvignon blanc is a staple in every Italian kitchen, if not on their wine list.  Request the best, and you just may get it.",
        picture: "momo.jpg"
    },
    {
        name: "WATERBROOK",
        year: "2009",
        grapes: "Merlot",
        country: "USA",
        region: "Washington",
        description: "Legend has it the gods didn't share their ambrosia with mere mortals.  This merlot may be the closest we've ever come to a taste of heaven.",
        picture: "waterbrook.jpg"
    }];

    db.collection('wines', function(err, collection) {
        collection.insert(wines, {safe:true}, function(err, result) {});
    });

};<|endoftext|>


<commit_before>var csv = require('fast-csv');
var fs = require('fs');

var stream = fs.createReadStream("kow.csv");

var newArmy;

csv
 .fromStream(stream, {headers: true})
 .on("data", function(data){
     if (data.army != newArmy) {
        newArmy = data.army;
        console.log(newArmy);
     }
 })
 .on("end", function(){
     console.log("done");
 });
<commit_msg>Delete csv2json.js<commit_after><|endoftext|>


<commit_before>module.exports = {
    // temporarily disable babel-eslint, for eslint v2.3.0 compatibility
    parser: 'babel-eslint',
    env: {
        es6: true
    },
    parserOptions: {
        ecmaVersion: 7,
        ecmaFeatures: {
            // ES6+ modules are strict implicitly
            impliedStrict: true,

            // jsx should not be enabled for non-react projects
            jsx: false
        }
    },
    rules: {
        // 箭头函数的参数，即使只有一个也要带上括号
        'arrow-parens': ['warn', 'always'],

        // => 前后都应有空格
        'arrow-spacing': ['warn', { before: true, after: true }],

        // 生成器函数的星号前需要有空格，星号后不能有空格，例如 function *foo() {}
        'generator-star-spacing': ['warn', { before: true, after: false }],

        // yield *gen()
        'yield-star-spacing': ['warn', { before: true, after: false }],

        // Disallows spaces inside of the curly brace pair of template string interpolations
        'template-curly-spacing': ['warn', 'never'],

        // ES2015 provides a default class constructor if one is not specified.
        // As such, it is unnecessary to provide an empty constructor or one that simply delegates into its parent class.
        'no-useless-constructor': 'warn',

        // 派生类的构造器函数必须有 super() 调用，其他情况下构造器函数都不允许调用 super()
        'constructor-super': 'error',

        // 派生类必须先调用过 super() 才能引用 this
        'no-this-before-super': 'error',

        // 不要写出不带 yield 语句的生成器函数
        'require-yield': 'warn',

        // 不要出现以下例子里的情况：
        // class A {}
        // A = 0;
        'no-class-assign': 'error',

        // 不能对常量进行赋值
        'no-const-assign': 'error',

        // 禁止 class 定义中出现两个同名成员
        'no-dupe-class-members': 'error',

        // 禁止不产生新变量的 destructuring pattern
        'no-empty-pattern': 'error',

        // `new Symbol()` throws a `TypeError` exception
        'no-new-symbol': 'error',

        // 1. Use object shorthands only when it can imporve readability
        // 2. Notice that [object literal shorthands cannot be used as constructors](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Method_definitions#Method_definitions_are_not_constructable)
        // 是否使用 object shorthand 应该由开发者视可读性而定，不一刀切
        'object-shorthand': 'off',  // [1, 'always', { ignoreConstructors: true }]

        // 如果需要使用的方法可以用 Reflect 的接口完成，则优先使用 Reflect
        // Reflect duplicates some methods of Object,
        // but its methods return booleans indicating whether the operation succeeded
        // (where the Object methods return the object that was modified).
        // IMO, it's not superior to the original form, since it's more intuitive to use try..catch
        // to handle exceptions than using return values.
        'prefer-reflect': 'off',

        // es6 version of the rule `no-restricted-modules`
        // 禁止某些库的使用，一般情况下用不到
        // no-restricted-imports: [2, 'os', 'fs']

        // 仅使用 let 和 const，不使用 var
        'no-var': 'warn',

        // 对于不会被修改的变量，优先考虑使用 const 而非 let
        'prefer-const': 'warn',

        // 如果仅仅是为了使用数组作为函数参数，那么应该优先考虑使用 spread operator 而不是 .apply()
        'prefer-spread': 'warn',

        // prefer rest parameters than `arguments`
        'prefer-rest-params': 'warn',

        // 回调函数尽可能使用箭头函数，而不是 Inline 的匿名函数
        'prefer-arrow-callback': 'warn',

        // 禁止复杂的字符串拼接，用模板引擎或 ES6 template string 替代
        'prefer-template': 'warn',

        // Disallow arrow functions in places where it could be confused with a comparison operator, so as to avoid potential typo
        'no-confusing-arrow': 'error',

        // Require braces in arrow function body when there might be confusions
        'arrow-body-style': ['warn', 'as-needed'],

        // sort import statements
        // http://eslint.org/docs/rules/sort-imports
        'sort-imports': ['warn', {
            ignoreCase: false,
            ignoreMemberSort: false,
            memberSyntaxSortOrder: ['none', 'all', 'multiple', 'single']
        }]
    }
}
<commit_msg>Enable allowParens option for no-confusing-arrow<commit_after>module.exports = {
    // temporarily disable babel-eslint, for eslint v2.3.0 compatibility
    parser: 'babel-eslint',
    env: {
        es6: true
    },
    parserOptions: {
        ecmaVersion: 7,
        ecmaFeatures: {
            // ES6+ modules are strict implicitly
            impliedStrict: true,

            // jsx should not be enabled for non-react projects
            jsx: false
        }
    },
    rules: {
        // 箭头函数的参数，即使只有一个也要带上括号
        'arrow-parens': ['warn', 'always'],

        // => 前后都应有空格
        'arrow-spacing': ['warn', { before: true, after: true }],

        // 生成器函数的星号前需要有空格，星号后不能有空格，例如 function *foo() {}
        'generator-star-spacing': ['warn', { before: true, after: false }],

        // yield *gen()
        'yield-star-spacing': ['warn', { before: true, after: false }],

        // Disallows spaces inside of the curly brace pair of template string interpolations
        'template-curly-spacing': ['warn', 'never'],

        // ES2015 provides a default class constructor if one is not specified.
        // As such, it is unnecessary to provide an empty constructor or one that simply delegates into its parent class.
        'no-useless-constructor': 'warn',

        // 派生类的构造器函数必须有 super() 调用，其他情况下构造器函数都不允许调用 super()
        'constructor-super': 'error',

        // 派生类必须先调用过 super() 才能引用 this
        'no-this-before-super': 'error',

        // 不要写出不带 yield 语句的生成器函数
        'require-yield': 'warn',

        // 不要出现以下例子里的情况：
        // class A {}
        // A = 0;
        'no-class-assign': 'error',

        // 不能对常量进行赋值
        'no-const-assign': 'error',

        // 禁止 class 定义中出现两个同名成员
        'no-dupe-class-members': 'error',

        // 禁止不产生新变量的 destructuring pattern
        'no-empty-pattern': 'error',

        // `new Symbol()` throws a `TypeError` exception
        'no-new-symbol': 'error',

        // 1. Use object shorthands only when it can imporve readability
        // 2. Notice that [object literal shorthands cannot be used as constructors](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Method_definitions#Method_definitions_are_not_constructable)
        // 是否使用 object shorthand 应该由开发者视可读性而定，不一刀切
        'object-shorthand': 'off',  // [1, 'always', { ignoreConstructors: true }]

        // 如果需要使用的方法可以用 Reflect 的接口完成，则优先使用 Reflect
        // Reflect duplicates some methods of Object,
        // but its methods return booleans indicating whether the operation succeeded
        // (where the Object methods return the object that was modified).
        // IMO, it's not superior to the original form, since it's more intuitive to use try..catch
        // to handle exceptions than using return values.
        'prefer-reflect': 'off',

        // es6 version of the rule `no-restricted-modules`
        // 禁止某些库的使用，一般情况下用不到
        // no-restricted-imports: [2, 'os', 'fs']

        // 仅使用 let 和 const，不使用 var
        'no-var': 'warn',

        // 对于不会被修改的变量，优先考虑使用 const 而非 let
        'prefer-const': 'warn',

        // 如果仅仅是为了使用数组作为函数参数，那么应该优先考虑使用 spread operator 而不是 .apply()
        'prefer-spread': 'warn',

        // prefer rest parameters than `arguments`
        'prefer-rest-params': 'warn',

        // 回调函数尽可能使用箭头函数，而不是 Inline 的匿名函数
        'prefer-arrow-callback': 'warn',

        // 禁止复杂的字符串拼接，用模板引擎或 ES6 template string 替代
        'prefer-template': 'warn',

        // Disallow arrow functions in places where it could be confused with a comparison operator, so as to avoid potential typo
        'no-confusing-arrow': ['error', { allowParens: true }],

        // Require braces in arrow function body when there might be confusions
        'arrow-body-style': ['warn', 'as-needed'],

        // sort import statements
        // http://eslint.org/docs/rules/sort-imports
        'sort-imports': ['warn', {
            ignoreCase: false,
            ignoreMemberSort: false,
            memberSyntaxSortOrder: ['none', 'all', 'multiple', 'single']
        }]
    }
}
<|endoftext|>


<commit_before>'use strict';

module.exports = {
  plugins: [
    'import',
  ],
  parserOptions: {
    ecmaVersion: 2017,
    sourceType: 'module',
  },
  settings: {
    'import/resolver': {
      node: {
        extensions: ['.js', '.jsx'],
      },
    },
    'import/extensions': ['.js', '.jsx'],
    'import/ignore': ['node_modules'],
  },
  rules: {
    // Static analysis
    'import/no-unresolved': ['error', {commonjs: true}],
    'import/named': 'error',
    'import/default': 'error',
    // TODO: Enable when issue has been fixed:
    // https://github.com/benmosher/eslint-plugin-import/issues/656
    // 'import/namespace': ['error', {allowComputed: true}],
    'import/no-restricted-paths': 'off',
    'import/no-absolute-path': 'error',
    'import/no-dynamic-require': 'error',
    'import/no-internal-modules': 'off',
    'import/no-webpack-loader-syntax': 'error',

    // Helpful warnings
    'import/export': 'error',
    'import/no-named-as-default': 'error',
    'import/no-named-as-default-member': 'error',
    // TODO: Enable when the rule goes more stable
    // https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/no-deprecated.md
    // 'import/no-deprecated': 'error',
    'import/no-extraneous-dependencies': 'error',
    'import/no-mutable-exports': 'error',

    // Module systems
    // TODO: Disable rule due to Unambiguous JavaScript Grammar is rejected from tc39 and moved to inactive proposals
    // https://github.com/tc39/proposals/blob/eb23a429df79d13e0d8fff89dc38a53f5085fa1b/inactive-proposals.md
    // 'import/unambiguous': 'error',
    'import/no-commonjs': 'off',
    'import/no-amd': 'error',
    'import/no-nodejs-modules': 'off',

    // Style guide
    'import/first': 'error',
    'import/no-duplicates': 'error',
    'import/no-namespace': 'off',
    'import/extensions': ['error', {js: 'never', jsx: 'never'}],
    'import/order': ['error', {'newlines-between': 'never'}],
    'import/newline-after-import': 'error',
    'import/prefer-default-export': 'error',
    'import/max-dependencies': 'off',
    'import/no-unassigned-import': 'off',
    'import/no-named-default': 'error',
    'import/no-anonymous-default-export': [
      'error',
      {
        allowArray: true,
        allowArrowFunction: true,
        allowLiteral: true,
        allowObject: true,
      },
    ],
  },
};
<commit_msg>Add `import/exports-last` rule<commit_after>'use strict';

module.exports = {
  plugins: [
    'import',
  ],
  parserOptions: {
    ecmaVersion: 2017,
    sourceType: 'module',
  },
  settings: {
    'import/resolver': {
      node: {
        extensions: ['.js', '.jsx'],
      },
    },
    'import/extensions': ['.js', '.jsx'],
    'import/ignore': ['node_modules'],
  },
  rules: {
    // Static analysis
    'import/no-unresolved': ['error', {commonjs: true}],
    'import/named': 'error',
    'import/default': 'error',
    // TODO: Enable when issue has been fixed:
    // https://github.com/benmosher/eslint-plugin-import/issues/656
    // 'import/namespace': ['error', {allowComputed: true}],
    'import/no-restricted-paths': 'off',
    'import/no-absolute-path': 'error',
    'import/no-dynamic-require': 'error',
    'import/no-internal-modules': 'off',
    'import/no-webpack-loader-syntax': 'error',

    // Helpful warnings
    'import/export': 'error',
    'import/no-named-as-default': 'error',
    'import/no-named-as-default-member': 'error',
    // TODO: Enable when the rule goes more stable
    // https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/no-deprecated.md
    // 'import/no-deprecated': 'error',
    'import/no-extraneous-dependencies': 'error',
    'import/no-mutable-exports': 'error',

    // Module systems
    // TODO: Disable rule due to Unambiguous JavaScript Grammar is rejected from tc39 and moved to inactive proposals
    // https://github.com/tc39/proposals/blob/eb23a429df79d13e0d8fff89dc38a53f5085fa1b/inactive-proposals.md
    // 'import/unambiguous': 'error',
    'import/no-commonjs': 'off',
    'import/no-amd': 'error',
    'import/no-nodejs-modules': 'off',

    // Style guide
    'import/first': 'error',
    'import/exports-last': 'off',
    'import/no-duplicates': 'error',
    'import/no-namespace': 'off',
    'import/extensions': ['error', {js: 'never', jsx: 'never'}],
    'import/order': ['error', {'newlines-between': 'never'}],
    'import/newline-after-import': 'error',
    'import/prefer-default-export': 'error',
    'import/max-dependencies': 'off',
    'import/no-unassigned-import': 'off',
    'import/no-named-default': 'error',
    'import/no-anonymous-default-export': [
      'error',
      {
        allowArray: true,
        allowArrowFunction: true,
        allowLiteral: true,
        allowObject: true,
      },
    ],
  },
};
<|endoftext|>


<commit_before>'use strict';

module.exports = {
  plugins: [
    'import',
  ],
  parserOptions: {
    ecmaVersion: 2017,
    sourceType: 'module',
  },
  settings: {
    'import/resolver': {
      node: {
        extensions: ['.js', '.jsx'],
      },
    },
    'import/extensions': ['.js', '.jsx'],
  },
  rules: {
    // static analysis
    'import/no-unresolved': ['error', {commonjs: true}],
    'import/named': 'error',
    'import/default': 'error',
    'import/namespace': 'error',
    'import/no-restricted-paths': 'off',
    'import/no-absolute-path': 'error',
    'import/no-dynamic-require': 'error',
    'import/no-internal-modules': 'off',
    'import/no-webpack-loader-syntax': 'error',

    // helpful warnings
    'import/export': 'error',
    'import/no-named-as-default': 'error',
    'import/no-named-as-default-member': 'error',
    'import/no-deprecated': 'off',
    'import/no-extraneous-dependencies': 'error',
    'import/no-mutable-exports': 'error',

    // module systems
    'import/unambiguous': 'error',
    'import/no-commonjs': 'off',
    'import/no-amd': 'error',
    'import/no-nodejs-modules': 'off',

    // style guide
    'import/first': 'error',
    'import/no-duplicates': 'error',
    'import/no-namespace': 'off',
    'import/extensions': ['error', {js: 'never', jsx: 'never'}],
    'import/order': ['error', {'newlines-between': 'never'}],
    'import/newline-after-import': 'error',
    'import/prefer-default-export': 'off',
    'import/max-dependencies': 'off',
  },
};
<commit_msg>Add `import/no-unassigned-import` rule<commit_after>'use strict';

module.exports = {
  plugins: [
    'import',
  ],
  parserOptions: {
    ecmaVersion: 2017,
    sourceType: 'module',
  },
  settings: {
    'import/resolver': {
      node: {
        extensions: ['.js', '.jsx'],
      },
    },
    'import/extensions': ['.js', '.jsx'],
  },
  rules: {
    // static analysis
    'import/no-unresolved': ['error', {commonjs: true}],
    'import/named': 'error',
    'import/default': 'error',
    'import/namespace': 'error',
    'import/no-restricted-paths': 'off',
    'import/no-absolute-path': 'error',
    'import/no-dynamic-require': 'error',
    'import/no-internal-modules': 'off',
    'import/no-webpack-loader-syntax': 'error',

    // helpful warnings
    'import/export': 'error',
    'import/no-named-as-default': 'error',
    'import/no-named-as-default-member': 'error',
    'import/no-deprecated': 'off',
    'import/no-extraneous-dependencies': 'error',
    'import/no-mutable-exports': 'error',

    // module systems
    'import/unambiguous': 'error',
    'import/no-commonjs': 'off',
    'import/no-amd': 'error',
    'import/no-nodejs-modules': 'off',

    // style guide
    'import/first': 'error',
    'import/no-duplicates': 'error',
    'import/no-namespace': 'off',
    'import/extensions': ['error', {js: 'never', jsx: 'never'}],
    'import/order': ['error', {'newlines-between': 'never'}],
    'import/newline-after-import': 'error',
    'import/prefer-default-export': 'off',
    'import/max-dependencies': 'off',
    'import/no-unassigned-import': 'off',
  },
};
<|endoftext|>


<commit_before>import log from '../lib/logger-service';
import * as DynamoDBTable from './dynamodb-table';

module.exports = class DynamoDBProvider {
  constructor() {
    this.table = new DynamoDBTable('sessions');
  }

  read(id) {
    return this.table.get({ id })
        .then((result) => (result !== undefined) ? result.context : {});
  }

  readAll() {
    return this.table;
  }

  write(id, context) {
    return new Promise((resolve, reject) => {
      if (!id) {
        return reject(new TypeError('No session ID'));
      }

      // coerce session id to string
      id = id + '';

      return resolve(
        this.table.put({ id }, { context })
            .then(({ context }) => context)
      );
    });
  }

  getAvailablePairs(id) {
    const params = {
      Limit: 50,
      FilterExpression: 'context.searching = :true AND ' +
                        '(NOT id = :id) AND ' +
                        '(NOT contains(context.pairRequests, :id)) AND ' +
                        '(NOT contains(context.rejectedPeers, :id))',
      ExpressionAttributeValues: { ':true': true,
                                   ':id': id },
      ProjectionExpression: 'id',
    };

    return this.table.scan(params).then((items) => {
      log.debug('Users searching for pair: {0}', JSON.stringify(items));
      return items;
    });
  }
};
<commit_msg>dynamoDb fix<commit_after>import log from '../lib/logger-service';
import * as DynamoDBTable from './dynamodb-table';

module.exports = class DynamoDBProvider {
  constructor() {
    this.table = new DynamoDBTable('sessions');
  }

  read(id) {
    return this.table.get({ id })
        .then((result) => (result !== undefined) ? result.context : {});
  }

  readAll() {
    return this.table.scan().then((items) => {
      return items;
    });
  }

  write(id, context) {
    return new Promise((resolve, reject) => {
      if (!id) {
        return reject(new TypeError('No session ID'));
      }

      // coerce session id to string
      id = id + '';

      return resolve(
        this.table.put({ id }, { context })
            .then(({ context }) => context)
      );
    });
  }

  getAvailablePairs(id) {
    const params = {
      Limit: 50,
      FilterExpression: 'context.searching = :true AND ' +
                        '(NOT id = :id) AND ' +
                        '(NOT contains(context.pairRequests, :id)) AND ' +
                        '(NOT contains(context.rejectedPeers, :id))',
      ExpressionAttributeValues: { ':true': true,
                                   ':id': id },
      ProjectionExpression: 'id',
    };

    return this.table.scan(params).then((items) => {
      log.debug('Users searching for pair: {0}', JSON.stringify(items));
      return items;
    });
  }
};
<|endoftext|>


<commit_before>var Cimpler  = require('../lib/cimpler');
var http     = require('http');
var assert   = require('assert');
var httpPort = 25750;

describe("build-status plugin", function() {
   it("should provide build list via http", function(done) {
      var cimpler = new Cimpler({
         plugins: {
            "build-status": { }
         },
         httpPort: httpPort,
         testMode: true  // Don't console.log() anything
      });

      var builds = [{
         repo:       'http',
         branch:     'test-branch',
      },{
         repo:       'http',
         branch:     'other-branch',
      }];

      cimpler.addBuild(builds[0]);
      cimpler.addBuild(builds[1]);
      cimpler.consumeBuild(function(inBuild) { });

      var options = {
        host: 'localhost',
        port: httpPort,
        path: '/builds/status'
      };

      http.get(options, function(res) {
         onEntireBody(res, function(err, body) {
            cimpler.shutdown();
            if (err) assert.fail(err);
            var expected = {
               queued: [builds[1]],
               building: [builds[0]]
            };
            assert.deepEqual(JSON.parse(body), expected);
            finished();
         });
      }).on('error', function(e) {
         finished(e);
      });

      function finished(err) {
         if (err) assert.fail(e);
         cimpler.shutdown();
         done();
      }
   });
});

function onEntireBody(stream, done) {
   var body = '';
   stream.setEncoding('utf8');
   stream.on('data', function (chunk) {
      body += chunk;
   });
   stream.on('end', function () {
      done(null, body);
   });
   stream.on('close', function (err) {
      done(err, body);
   });
}
<commit_msg>Tests: fix github commit status test<commit_after>var Cimpler  = require('../lib/cimpler');
var http     = require('http');
var assert   = require('assert');
var _        = require('underscore');
var httpPort = 25750;

describe("build-status plugin", function() {
   it("should provide build list via http", function(done) {
      var cimpler = new Cimpler({
         plugins: {
            "build-status": { }
         },
         httpPort: httpPort,
         testMode: true  // Don't console.log() anything
      });

      var builds = [{
         repo:       'http',
         branch:     'test-branch',
      },{
         repo:       'http',
         branch:     'other-branch',
      }];

      cimpler.addBuild(builds[0]);
      cimpler.addBuild(builds[1]);
      cimpler.consumeBuild(function(inBuild) { });

      var options = {
        host: 'localhost',
        port: httpPort,
        path: '/builds/status'
      };

      http.get(options, function(res) {
         onEntireBody(res, function(err, body) {
            cimpler.shutdown();
            if (err) assert.fail(err);
            builds = builds.map(function(build) {
               return _.omit(build, '_control');
            });
            var expected = {
               queued: [builds[1]],
               building: [builds[0]]
            };
            assert.deepEqual(JSON.parse(body), expected);
            finished();
         });
      }).on('error', function(e) {
         finished(e);
      });

      function finished(err) {
         if (err) assert.fail(e);
         cimpler.shutdown();
         done();
      }
   });
});

function onEntireBody(stream, done) {
   var body = '';
   stream.setEncoding('utf8');
   stream.on('data', function (chunk) {
      body += chunk;
   });
   stream.on('end', function () {
      done(null, body);
   });
   stream.on('close', function (err) {
      done(err, body);
   });
}
<|endoftext|>


<commit_before>import * as utils from '../network/utils'
import { searchData } from '../network'
/**
 * Make request and search data
 * @function countries
 * @param {object} params - object of parameters:
 * @param {string} params.countryCode
 * @param {function} [callback] - Called with two arguments (error, result) on completion. `result` is a country name returned or country names. Omit to return Promise
 * @returns {Promise|null} If no callback supplied, returns a Promise that resolves with an string
 */

export function countries({ code }, callback) {
  const params = {
    AMaaSClass: 'fundamentalCountries',
    query: {countryCode: [code]}
  }
  //if code is not specified, retun all countries
  let promise = searchData(params).then(result => {
    if (typeof callback === 'function') {
      callback(null, result)
    }
    return result
   }).catch((err) => {
     console.log(err.message);
  });
  if (typeof callback !== 'function') {
    // return promise if callback is not provided
    return promise
  }
  promise.catch(error => callback(error))
}

export function calcBusinessDate({date, codes, offset, invalidDates}, callback) //invalid dates
{
    if(!date){
        return "Must specify start_date in querystring"
    }else if(!codes){
        return "Must specify at least one country_code in querystring"
    }else if(!offset){
        return "Must specify offset in querystring"
    }else if(!Number.isInteger(offset)) {
         return "Offset must be an integer"
    }

    let code=""
    if(Array.isArray(codes)){
      for(var i = 0; i < codes.length;i++) {
            code+=codes[i]+","
       }
     code = code.substring(0, code.length - 1);
   }else{
    code=codes
   }

   let invalidDate=""
   if(invalidDates){
    if(Array.isArray(invalidDates)){
      for(var i = 0; i < invalidDates.length;i++) {
            invalidDate+=invalidDates[i]+","
       }
     invalidDate = invalidDate.substring(0,invalidDate.length - 1);
    }else{
      invalidDate=invalidDates
    }
   }

   let params
   if(!invalidDates){
          params = {
          AMaaSClass: 'fundamentalBusinessDate',
          query: {stratDate: [date], countryCode: [code], offset: [offset]}
          }
   }else{
         params = {
          AMaaSClass: 'fundamentalBusinessDate',
          query: {stratDate: [date], countryCode: [code], offset: [offset], invalidDate: [invalidDate]}
          }
   }

    let promise = searchData(params).then(result => {
    if (typeof callback === 'function') {
      callback(null, result)
    }
      return result //should return biz date!
    }).catch((err) => {
      console.log(err.message);
    });
   if (typeof callback !== 'function') {
    // return promise if callback is not provided
    return promise
   }
  promise.catch(error => callback(error))
}

export function processDateInfo ({date, codes}, callback)
{
    let code=""
    if(Array.isArray(codes)){
      for(var i = 0; i < codes.length;i++) {
            code+=codes[i]+","
       }
     code = code.substring(0, code.length - 1);
   }else{
    code=codes
   }

    const params = {
          AMaaSClass: 'fundamentalDateInfo',
          query: {stratDate: [date], countryCode: [code]}
    }
   let promise = searchData(params).then(result => {
    if (typeof callback === 'function') {
      callback(null, result)
    } //should retun true
      return result //should return biz date!
    }).catch((err) => {
      console.log(err.message);
    });
   if (typeof callback !== 'function') {
    // return promise if callback is not provided
    return promise
   }
  promise.catch(error => callback(error))
}

export function holidays ({codes, years}, callback)
{
    if(!codes) {
        return "Currently only country-based holiday calendars are supported"
    }

    let code=""
    if(Array.isArray(codes)){
      for(var i = 0; i < codes.length;i++) {
            code+=codes[i]+","
       }
     code = code.substring(0, code.length - 1);
   }else{
    code=codes
   }

   let year=""
   if(Array.isArray(years)){
      for(var i = 0; i < years.length;i++) {
            year+=years[i]+","
       }
     year = year.substring(0, year.length - 1);
   }else{
    year=years
   }

   const params = {
          AMaaSClass: 'fundamentalHoliday',
          query: {countryCode: [code], year: [year]}
    }

    let promise = searchData(params).then(result => {
    if (typeof callback === 'function') {
      callback(null, result)
    } //should retun true
      return result //should return biz date!
    }).catch((err) => {
      console.log(err.message);
    });
   if (typeof callback !== 'function') {
    // return promise if callback is not provided
    return promise
   }
  promise.catch(error => callback(error))
}
<commit_msg>Add comments<commit_after>import * as utils from '../network/utils'
import { searchData } from '../network'

/**
 * Make request and search data
 * @function countries
 * @param {object} params - object of parameters:
 * @param {string} params.countryCode
 * @param {function} [callback] - Called with two arguments (error, result) on completion. `result` is a country name returned or country names. Omit to return Promise
 * @returns {Promise|null}
 */
export function countries({ code }, callback) {
  const params = {
    AMaaSClass: 'fundamentalCountries',
    query: {countryCode: [code]}
  }
  //if code is not specified, retun all countries
  let promise = searchData(params).then(result => {
    if (typeof callback === 'function') {
      callback(null, result)
    }
    return result
   }).catch((err) => {
     console.log(err.message);
  });
  if (typeof callback !== 'function') {
    // return promise if callback is not provided
    return promise
  }
  promise.catch(error => callback(error))
}

/**
 * Make request and search data
 * @function calcBusinessDate
 * @param {object} params - object of parameters:
 * @param {string} params.codes - A country code string or an array of country codes strings
 * @param {string} params.date - start date
 * @param {string} params.offset
 * @param {string} params.invalidDates - an invalid date string or an array of invalid dates strings
 * @param {function} [callback] - Called with two arguments (error, result) on completion. `result` is a country name returned or country names. Omit to return Promise
 * @returns {Promise|null}
 */
export function calcBusinessDate({date, codes, offset, invalidDates}, callback) //invalid dates
{
    if(!date){
        return "Must specify start_date in querystring"
    }else if(!codes){
        return "Must specify at least one country_code in querystring"
    }else if(!offset){
        return "Must specify offset in querystring"
    }else if(!Number.isInteger(offset)) {
         return "Offset must be an integer"
    }

    let code=""
    if(Array.isArray(codes)){
      for(var i = 0; i < codes.length;i++) {
            code+=codes[i]+","
       }
     code = code.substring(0, code.length - 1);
   }else{
    code=codes
   }

   let invalidDate=""
   if(invalidDates){
    if(Array.isArray(invalidDates)){
      for(var i = 0; i < invalidDates.length;i++) {
            invalidDate+=invalidDates[i]+","
       }
     invalidDate = invalidDate.substring(0,invalidDate.length - 1);
    }else{
      invalidDate=invalidDates
    }
   }

   let params
   if(!invalidDates){
          params = {
          AMaaSClass: 'fundamentalBusinessDate',
          query: {startDate: [date], countryCode: [code], offset: [offset]}
          }
   }else{
         params = {
          AMaaSClass: 'fundamentalBusinessDate',
          query: {startDate: [date], countryCode: [code], offset: [offset], invalidDate: [invalidDate]}
          }
   }

    let promise = searchData(params).then(result => {
    if (typeof callback === 'function') {
      callback(null, result)
    }
      return result
    }).catch((err) => {
      console.log(err.message);
    });
   if (typeof callback !== 'function') {
    // return promise if callback is not provided
    return promise
   }
  promise.catch(error => callback(error))
}

/**
 * Make request and search data
 * @function processDateInfo
 * @param {object} params - object of parameters:
 * @param {string} params.codes - A country code string or an array of country codes strings
 * @param {string} params.date - start date
 * @param {function} [callback] - Called with two arguments (error, result) on completion. `result` is a country name returned or country names. Omit to return Promise
 * @returns {Promise|null}
 */
export function processDateInfo ({date, codes}, callback)
{
    let code=""
    if(Array.isArray(codes)){
      for(var i = 0; i < codes.length;i++) {
            code+=codes[i]+","
       }
     code = code.substring(0, code.length - 1);
   }else{
    code=codes
   }

    const params = {
          AMaaSClass: 'fundamentalDateInfo',
          query: {startDate: [date], countryCode: [code]}
    }
   let promise = searchData(params).then(result => {
    if (typeof callback === 'function') {
      callback(null, result)
    }
      return result
    }).catch((err) => {
      console.log(err.message);
    });
   if (typeof callback !== 'function') {
    // return promise if callback is not provided
    return promise
   }
  promise.catch(error => callback(error))
}

/**
 * Make request and search data
 * @function holidays
 * @param {object} params - object of parameters:
 * @param {string} params.codes - A country code string or an array of country codes strings
 * @param {string} params.year - A year string or an array of
 * @param {function} [callback] - Called with two arguments (error, result) on completion. `result` is a country name returned or country names. Omit to return Promise
 * @returns {Promise|null}
 */
export function holidays ({codes, years}, callback)
{
    if(!codes) {
        return "Currently only country-based holiday calendars are supported"
    }

    let code=""
    if(Array.isArray(codes)){
      for(var i = 0; i < codes.length;i++) {
            code+=codes[i]+","
       }
     code = code.substring(0, code.length - 1);
   }else{
    code=codes
   }

   let year=""
   if(Array.isArray(years)){
      for(var i = 0; i < years.length;i++) {
            year+=years[i]+","
       }
     year = year.substring(0, year.length - 1);
   }else{
    year=years
   }

   const params = {
          AMaaSClass: 'fundamentalHoliday',
          query: {countryCode: [code], year: [year]}
    }

    let promise = searchData(params).then(result => {
    if (typeof callback === 'function') {
      callback(null, result)
    }
      return result
    }).catch((err) => {
      console.log(err.message);
    });
   if (typeof callback !== 'function') {
    // return promise if callback is not provided
    return promise
   }
  promise.catch(error => callback(error))
}
<|endoftext|>


<commit_before>import pluginList from "../data/plugins.json";
import pluginFeatures from "../data/plugin-features";
import builtInsList from "../data/built-ins.json";
import browserslist from "browserslist";
import transformPolyfillRequirePlugin from "./transform-polyfill-require-plugin";
import electronToChromium from "../data/electron-to-chromium";

export const MODULE_TRANSFORMATIONS = {
  "amd": "transform-es2015-modules-amd",
  "commonjs": "transform-es2015-modules-commonjs",
  "systemjs": "transform-es2015-modules-systemjs",
  "umd": "transform-es2015-modules-umd"
};

const defaultInclude = [
  "web.timers",
  "web.immediate",
  "web.dom.iterable"
];

export const validIncludesAndExcludes = [
  ...Object.keys(pluginFeatures),
  ...Object.keys(MODULE_TRANSFORMATIONS).map((m) => MODULE_TRANSFORMATIONS[m]),
  ...Object.keys(builtInsList),
  ...defaultInclude
];

/**
 * Determine if a transformation is required
 * @param  {Object}  supportedEnvironments  An Object containing environment keys and the lowest
 *                                          supported version as a value
 * @param  {Object}  plugin                 An Object containing environment keys and the lowest
 *                                          version the feature was implmented in as a value
 * @return {Boolean}  Whether or not the transformation is required
 */
export const isPluginRequired = (supportedEnvironments, plugin) => {
  if (supportedEnvironments.browsers) {
    supportedEnvironments = getTargets(supportedEnvironments);
  }

  const targetEnvironments = Object.keys(supportedEnvironments);

  if (targetEnvironments.length === 0) { return true; }

  const isRequiredForEnvironments = targetEnvironments
    .filter((environment) => {
      // Feature is not implemented in that environment
      if (!plugin[environment]) { return true; }

      const lowestImplementedVersion = plugin[environment];
      const lowestTargetedVersion = supportedEnvironments[environment];

      if (lowestTargetedVersion < lowestImplementedVersion) {
        return true;
      }

      return false;
    });

  return isRequiredForEnvironments.length > 0 ? true : false;
};

const isBrowsersQueryValid = (browsers) => {
  return typeof browsers === "string" || Array.isArray(browsers);
};

const browserNameMap = {
  chrome: "chrome",
  edge: "edge",
  firefox: "firefox",
  ie: "ie",
  ios_saf: "ios",
  safari: "safari"
};

const getLowestVersions = (browsers) => {
  return browsers.reduce((all, browser) => {
    const [browserName, browserVersion] = browser.split(" ");
    if (browserName in browserNameMap) {
      all[browserNameMap[browserName]] = parseInt(browserVersion);
    }
    return all;
  }, {});
};

const mergeBrowsers = (fromQuery, fromTarget) => {
  return Object.keys(fromTarget).reduce((queryObj, targKey) => {
    if (targKey !== "browsers") {
      queryObj[targKey] = fromTarget[targKey];
    }
    return queryObj;
  }, fromQuery);
};

export const getCurrentNodeVersion = () => {
  return parseFloat(process.versions.node);
};

export const electronVersionToChromeVersion = (semverVer) => {
  semverVer = String(semverVer);

  if (semverVer === "1") {
    semverVer = "1.0";
  }

  const m = semverVer.match(/^(\d+\.\d+)/);
  if (!m) {
    throw new Error("Electron version must be a semver version");
  }

  let result = electronToChromium[m[1]];
  if (!result) {
    throw new Error(`Electron version ${m[1]} is either too old or too new`);
  }

  return result;
};

const _extends = Object.assign || function (target) {
  for (let i = 1; i < arguments.length; i++) {
    const source = arguments[i];
    for (let key in source) {
      if (Object.prototype.hasOwnProperty.call(source, key)) {
        target[key] = source[key];
      }
    }
  }
  return target;
};

export const getTargets = (targets = {}) => {
  const targetOps = _extends({}, targets);

  if (targetOps.node === true || targetOps.node === "current") {
    targetOps.node = getCurrentNodeVersion();
  }

  // Rewrite Electron versions to their Chrome equivalents
  if (targetOps.electron) {
    targetOps.chrome = electronVersionToChromeVersion(targetOps.electron);
    delete targetOps.electron;
  }

  const browserOpts = targetOps.browsers;
  if (isBrowsersQueryValid(browserOpts)) {
    const queryBrowsers = getLowestVersions(browserslist(browserOpts));
    return mergeBrowsers(queryBrowsers, targetOps);
  }
  return targetOps;
};

// TODO: Allow specifying plugins as either shortened or full name
// babel-plugin-transform-es2015-classes
// transform-es2015-classes
export const validateLooseOption = (looseOpt = false) => {
  if (typeof looseOpt !== "boolean") {
    throw new Error("Preset env: 'loose' option must be a boolean.");
  }

  return looseOpt;
};

export const validateModulesOption = (modulesOpt = "commonjs") => {
  if (modulesOpt !== false && Object.keys(MODULE_TRANSFORMATIONS).indexOf(modulesOpt) === -1) {
    throw new Error("The 'modules' option must be 'false' to indicate no modules\n" +
      "or a module type which be be one of: 'commonjs' (default), 'amd', 'umd', 'systemjs'");
  }

  return modulesOpt;
};

export function validatePluginsOption(opts = [], type) {
  if (!Array.isArray(opts)) {
    throw new Error(`The '${type}' option must be an Array<string> of plugins/built-ins`);
  }

  let unknownOpts = [];
  opts.forEach((opt) => {
    if (validIncludesAndExcludes.indexOf(opt) === -1) {
      unknownOpts.push(opt);
    }
  });

  if (unknownOpts.length > 0) {
    throw new Error(`Invalid plugins/built-ins '${unknownOpts}' passed to '${type}' option.
      Check data/[plugin-features|built-in-features].js in babel-preset-env`);
  }

  return {
    all: opts,
    plugins: opts.filter((opt) => !opt.match(/^(es\d+|web)\./)),
    builtIns: opts.filter((opt) => opt.match(/^(es\d+|web)\./))
  };
}

const validateIncludeOption = (opts) => validatePluginsOption(opts, "include");
const validateExcludeOption = (opts) => validatePluginsOption(opts, "exclude");

export function checkDuplicateIncludeExcludes(include, exclude) {
  let duplicates = [];
  include.forEach((opt) => {
    if (exclude.indexOf(opt) >= 0) {
      duplicates.push(opt);
    }
  });

  if (duplicates.length > 0) {
    throw new Error(`Duplicate plugins/built-ins: '${duplicates}' found
      in both the "include" and "exclude" options.`);
  }
}

let hasBeenLogged = false;
let hasBeenWarned = false;

const logPlugin = (plugin, targets, list) => {
  const envList = list[plugin] || {};
  const filteredList = Object.keys(targets)
  .reduce((a, b) => {
    a[b] = envList[b];
    return a;
  }, {});
  const logStr = `\n  ${plugin}\n  ${JSON.stringify(filteredList)}`;
  console.log(logStr);
};

export default function buildPreset(context, opts = {}) {
  const loose = validateLooseOption(opts.loose);
  const moduleType = validateModulesOption(opts.modules);
  // TODO: remove whitelist in favor of include in next major
  if (opts.whitelist && !hasBeenWarned) {
    hasBeenWarned = true;
    console.warn(`The "whitelist" option has been deprecated
    in favor of "include" to match the newly added "exclude" option (instead of "blacklist").`);
  }
  const include = validateIncludeOption(opts.whitelist || opts.include);
  const exclude = validateExcludeOption(opts.exclude);
  checkDuplicateIncludeExcludes(include.all, exclude.all);
  const targets = getTargets(opts.targets);
  const debug = opts.debug;
  const useBuiltIns = opts.useBuiltIns;

  let transformations = Object.keys(pluginList)
    .filter((pluginName) => isPluginRequired(targets, pluginList[pluginName]));

  let polyfills;
  if (useBuiltIns) {
    polyfills = Object.keys(builtInsList)
      .filter((builtInName) => isPluginRequired(targets, builtInsList[builtInName]))
      .concat(defaultInclude)
      .filter((plugin) => exclude.builtIns.indexOf(plugin) === -1)
      .concat(include.builtIns);
  }

  if (debug && !hasBeenLogged) {
    hasBeenLogged = true;
    console.log("babel-preset-env: `DEBUG` option");
    console.log("\nUsing targets:");
    console.log(JSON.stringify(opts.targets, null, 2));
    console.log(`\nModules transform: ${moduleType}`);
    console.log("\nUsing plugins:");
    transformations.forEach((transform) => {
      logPlugin(transform, targets, pluginList);
    });
    console.log("\nUsing polyfills:");
    if (useBuiltIns && polyfills.length) {
      polyfills.forEach((polyfill) => {
        logPlugin(polyfill, targets, builtInsList);
      });
    }
  }

  const allTransformations = transformations
  .filter((plugin) => exclude.plugins.indexOf(plugin) === -1)
  .concat(include.plugins);

  const regenerator = allTransformations.indexOf("transform-regenerator") >= 0;
  const modulePlugin = moduleType !== false && MODULE_TRANSFORMATIONS[moduleType];
  const plugins = [];

  modulePlugin &&
    plugins.push([require(`babel-plugin-${modulePlugin}`), { loose }]);

  plugins.push(...allTransformations.map((pluginName) =>
    [require(`babel-plugin-${pluginName}`), { loose }]
  ));

  useBuiltIns &&
    plugins.push([transformPolyfillRequirePlugin, { polyfills, regenerator }]);

  return {
    plugins
  };
}
<commit_msg>Make plugin output single-lined.<commit_after>import pluginList from "../data/plugins.json";
import pluginFeatures from "../data/plugin-features";
import builtInsList from "../data/built-ins.json";
import browserslist from "browserslist";
import transformPolyfillRequirePlugin from "./transform-polyfill-require-plugin";
import electronToChromium from "../data/electron-to-chromium";

export const MODULE_TRANSFORMATIONS = {
  "amd": "transform-es2015-modules-amd",
  "commonjs": "transform-es2015-modules-commonjs",
  "systemjs": "transform-es2015-modules-systemjs",
  "umd": "transform-es2015-modules-umd"
};

const defaultInclude = [
  "web.timers",
  "web.immediate",
  "web.dom.iterable"
];

export const validIncludesAndExcludes = [
  ...Object.keys(pluginFeatures),
  ...Object.keys(MODULE_TRANSFORMATIONS).map((m) => MODULE_TRANSFORMATIONS[m]),
  ...Object.keys(builtInsList),
  ...defaultInclude
];

/**
 * Determine if a transformation is required
 * @param  {Object}  supportedEnvironments  An Object containing environment keys and the lowest
 *                                          supported version as a value
 * @param  {Object}  plugin                 An Object containing environment keys and the lowest
 *                                          version the feature was implmented in as a value
 * @return {Boolean}  Whether or not the transformation is required
 */
export const isPluginRequired = (supportedEnvironments, plugin) => {
  if (supportedEnvironments.browsers) {
    supportedEnvironments = getTargets(supportedEnvironments);
  }

  const targetEnvironments = Object.keys(supportedEnvironments);

  if (targetEnvironments.length === 0) { return true; }

  const isRequiredForEnvironments = targetEnvironments
    .filter((environment) => {
      // Feature is not implemented in that environment
      if (!plugin[environment]) { return true; }

      const lowestImplementedVersion = plugin[environment];
      const lowestTargetedVersion = supportedEnvironments[environment];

      if (lowestTargetedVersion < lowestImplementedVersion) {
        return true;
      }

      return false;
    });

  return isRequiredForEnvironments.length > 0 ? true : false;
};

const isBrowsersQueryValid = (browsers) => {
  return typeof browsers === "string" || Array.isArray(browsers);
};

const browserNameMap = {
  chrome: "chrome",
  edge: "edge",
  firefox: "firefox",
  ie: "ie",
  ios_saf: "ios",
  safari: "safari"
};

const getLowestVersions = (browsers) => {
  return browsers.reduce((all, browser) => {
    const [browserName, browserVersion] = browser.split(" ");
    if (browserName in browserNameMap) {
      all[browserNameMap[browserName]] = parseInt(browserVersion);
    }
    return all;
  }, {});
};

const mergeBrowsers = (fromQuery, fromTarget) => {
  return Object.keys(fromTarget).reduce((queryObj, targKey) => {
    if (targKey !== "browsers") {
      queryObj[targKey] = fromTarget[targKey];
    }
    return queryObj;
  }, fromQuery);
};

export const getCurrentNodeVersion = () => {
  return parseFloat(process.versions.node);
};

export const electronVersionToChromeVersion = (semverVer) => {
  semverVer = String(semverVer);

  if (semverVer === "1") {
    semverVer = "1.0";
  }

  const m = semverVer.match(/^(\d+\.\d+)/);
  if (!m) {
    throw new Error("Electron version must be a semver version");
  }

  let result = electronToChromium[m[1]];
  if (!result) {
    throw new Error(`Electron version ${m[1]} is either too old or too new`);
  }

  return result;
};

const _extends = Object.assign || function (target) {
  for (let i = 1; i < arguments.length; i++) {
    const source = arguments[i];
    for (let key in source) {
      if (Object.prototype.hasOwnProperty.call(source, key)) {
        target[key] = source[key];
      }
    }
  }
  return target;
};

export const getTargets = (targets = {}) => {
  const targetOps = _extends({}, targets);

  if (targetOps.node === true || targetOps.node === "current") {
    targetOps.node = getCurrentNodeVersion();
  }

  // Rewrite Electron versions to their Chrome equivalents
  if (targetOps.electron) {
    targetOps.chrome = electronVersionToChromeVersion(targetOps.electron);
    delete targetOps.electron;
  }

  const browserOpts = targetOps.browsers;
  if (isBrowsersQueryValid(browserOpts)) {
    const queryBrowsers = getLowestVersions(browserslist(browserOpts));
    return mergeBrowsers(queryBrowsers, targetOps);
  }
  return targetOps;
};

// TODO: Allow specifying plugins as either shortened or full name
// babel-plugin-transform-es2015-classes
// transform-es2015-classes
export const validateLooseOption = (looseOpt = false) => {
  if (typeof looseOpt !== "boolean") {
    throw new Error("Preset env: 'loose' option must be a boolean.");
  }

  return looseOpt;
};

export const validateModulesOption = (modulesOpt = "commonjs") => {
  if (modulesOpt !== false && Object.keys(MODULE_TRANSFORMATIONS).indexOf(modulesOpt) === -1) {
    throw new Error("The 'modules' option must be 'false' to indicate no modules\n" +
      "or a module type which be be one of: 'commonjs' (default), 'amd', 'umd', 'systemjs'");
  }

  return modulesOpt;
};

export function validatePluginsOption(opts = [], type) {
  if (!Array.isArray(opts)) {
    throw new Error(`The '${type}' option must be an Array<string> of plugins/built-ins`);
  }

  let unknownOpts = [];
  opts.forEach((opt) => {
    if (validIncludesAndExcludes.indexOf(opt) === -1) {
      unknownOpts.push(opt);
    }
  });

  if (unknownOpts.length > 0) {
    throw new Error(`Invalid plugins/built-ins '${unknownOpts}' passed to '${type}' option.
      Check data/[plugin-features|built-in-features].js in babel-preset-env`);
  }

  return {
    all: opts,
    plugins: opts.filter((opt) => !opt.match(/^(es\d+|web)\./)),
    builtIns: opts.filter((opt) => opt.match(/^(es\d+|web)\./))
  };
}

const validateIncludeOption = (opts) => validatePluginsOption(opts, "include");
const validateExcludeOption = (opts) => validatePluginsOption(opts, "exclude");

export function checkDuplicateIncludeExcludes(include, exclude) {
  let duplicates = [];
  include.forEach((opt) => {
    if (exclude.indexOf(opt) >= 0) {
      duplicates.push(opt);
    }
  });

  if (duplicates.length > 0) {
    throw new Error(`Duplicate plugins/built-ins: '${duplicates}' found
      in both the "include" and "exclude" options.`);
  }
}

let hasBeenLogged = false;
let hasBeenWarned = false;

const logPlugin = (plugin, targets, list) => {
  const envList = list[plugin] || {};
  const filteredList = Object.keys(targets)
  .reduce((a, b) => {
    a[b] = envList[b];
    return a;
  }, {});
  const logStr = `  ${plugin} ${JSON.stringify(filteredList)}`;
  console.log(logStr);
};

export default function buildPreset(context, opts = {}) {
  const loose = validateLooseOption(opts.loose);
  const moduleType = validateModulesOption(opts.modules);
  // TODO: remove whitelist in favor of include in next major
  if (opts.whitelist && !hasBeenWarned) {
    hasBeenWarned = true;
    console.warn(`The "whitelist" option has been deprecated
    in favor of "include" to match the newly added "exclude" option (instead of "blacklist").`);
  }
  const include = validateIncludeOption(opts.whitelist || opts.include);
  const exclude = validateExcludeOption(opts.exclude);
  checkDuplicateIncludeExcludes(include.all, exclude.all);
  const targets = getTargets(opts.targets);
  const debug = opts.debug;
  const useBuiltIns = opts.useBuiltIns;

  let transformations = Object.keys(pluginList)
    .filter((pluginName) => isPluginRequired(targets, pluginList[pluginName]));

  let polyfills;
  if (useBuiltIns) {
    polyfills = Object.keys(builtInsList)
      .filter((builtInName) => isPluginRequired(targets, builtInsList[builtInName]))
      .concat(defaultInclude)
      .filter((plugin) => exclude.builtIns.indexOf(plugin) === -1)
      .concat(include.builtIns);
  }

  if (debug && !hasBeenLogged) {
    hasBeenLogged = true;
    console.log("babel-preset-env: `DEBUG` option");
    console.log("\nUsing targets:");
    console.log(JSON.stringify(opts.targets, null, 2));
    console.log(`\nModules transform: ${moduleType}`);
    console.log("\nUsing plugins:");
    transformations.forEach((transform) => {
      logPlugin(transform, targets, pluginList);
    });
    console.log("\nUsing polyfills:");
    if (useBuiltIns && polyfills.length) {
      polyfills.forEach((polyfill) => {
        logPlugin(polyfill, targets, builtInsList);
      });
    }
  }

  const allTransformations = transformations
  .filter((plugin) => exclude.plugins.indexOf(plugin) === -1)
  .concat(include.plugins);

  const regenerator = allTransformations.indexOf("transform-regenerator") >= 0;
  const modulePlugin = moduleType !== false && MODULE_TRANSFORMATIONS[moduleType];
  const plugins = [];

  modulePlugin &&
    plugins.push([require(`babel-plugin-${modulePlugin}`), { loose }]);

  plugins.push(...allTransformations.map((pluginName) =>
    [require(`babel-plugin-${pluginName}`), { loose }]
  ));

  useBuiltIns &&
    plugins.push([transformPolyfillRequirePlugin, { polyfills, regenerator }]);

  return {
    plugins
  };
}
<|endoftext|>