<commit_before>"use strict";

const mongoose = require('mongoose');
const express = require('express');
const cel = require('connect-ensure-login');
const router = express.Router();
const email = require('../lib/email');
const log = require('../lib/logger');
const libInvoice = require('../lib/invoice');
const libFmt = require('../lib/fmt');

const Event = mongoose.models.Event;
const Team = mongoose.models.Team;
const TeamEvent = mongoose.models.TeamEvent;
const Program = mongoose.models.Program;
const InvoicingOrg = mongoose.models.InvoicingOrg;
const User = mongoose.models.User;

module.exports = router;

router.param('id', async function (req, res, next){
    const id = req.params.id;
    let r;
    console.log("Event id",id);
    try {
        r = await Event.findById(id);
        r = await Program.populate(r,'programId');
        r = await InvoicingOrg.populate(r,'invoicingOrg');
        req.event = r;
        if (r) {
            req.user.isEventOrganizer = (req.event.managers.indexOf(req.user.id) >= 0);
            req.user.isProgramManager = (req.event.programId.managers.indexOf(req.user.id) >= 0);
            req.user.isInvoicingOrgManager = (req.event.invoicingOrg.managers.indexOf(req.user.id) >= 0);
            r.teams = [];
            let tmse = await TeamEvent.find({eventId: r.id});
            let tms = await Team.populate(tmse, 'teamId');
            tms.forEach(t => r.teams.push({id: t.teamId.id, name: t.teamId.name}));
            r.teams.sort(function(a,b) {return (a.name > b.name) ? 1 : ((b.name > a.name) ? -1 : 0);} );

            console.log("Event id=", r.id, " name=", r.name);

        } else
            throw new Error("event not found");
        next();
    } catch (err) {
        res.render('error',{message:"Stretnutie/Turnaj nenájdený",error:{status:err.message}});
    }

});

router.get('/:id', async function (req, res, next) {
    const cmd = req.query.cmd;
    console.log("/event/:id - get");

    if (cmd)
        next();
    else
        res.render('event',{event: req.event, user: req.user, fmt:libFmt});

});

router.get('/:id', cel.ensureLoggedIn('/login'), async function (req, res, next) {
    const cmd = req.query.cmd;
    const eventId = req.params.id;
    console.log("/event/:id - get (CMD)");
    console.log(req.query);

    const r = {result:"error", status:200};
    r.isAdmin = req.user.isAdmin || req.user.isSuperAdmin;
    r.isEventOrganizer = req.user.isEventOrganizer;

    try {
        switch (cmd) {
            case 'getTeams':
                console.log('Going to get list of registered teams');
                const te = await TeamEvent.find({eventId:eventId});
                if (!te)
                    throw new Error("Error while fetching teams for event "+eventId);

                r.list = [];
                for (let t of te) {
                    try {
                        console.log("TE=",t.id);
                        let ti = await Team.findById(t.teamId);
                        let a = JSON.parse(JSON.stringify(ti)); // ti is  frozen for adding properties, so copy is needed
                        if (ti) {
                            a.teamEvent = t;
                            r.list.push(a);
                        }
                    } catch (err) {
                        throw new Error("Error while fetching data for teamEvent="+ti.teamEvent);
                    }
                }

                r.result = "ok";
                break;
            case 'getOrganizers':
                console.log('Going to get list of event organizers');
                let e = await User.populate(req.event,{path:"managers", select:{fullName:1}});
                r.list = e.managers;
                r.result = "ok";

                break;

            default:
                console.log('cmd=unknown');
        }
    } catch (err) {
        r.error = err;
        log.ERROR("GET /event/:id failed. err="+err);
    }
    res.json(r);
    res.end();

});

router.get('/', cel.ensureLoggedIn('/login'), async function (req, res, next) {
    const cmd = req.query.cmd;
    const progId = req.query.program;
    console.log("/event - get (CMD)");
    console.log(req.query);

    const r = {result:"error", status:200};
    r.isAdmin = req.user.isAdmin || req.user.isSuperAdmin;
    r.isEventOrganizer = req.user.isEventOrganizer;

    try {
        switch (cmd) {
            case 'getList':
                console.log('Going to get list of all events');
                let q = {recordStatus: 'active'};
                if (progId)
                    q.programId = progId;
                const p = await Event.find(q, {
                    name: true,
                    id: true
                });
                r.result = "ok";
                r.list = p;
                r.list.sort(function(a,b) {return (a.name > b.name) ? 1 : ((b.name > a.name) ? -1 : 0);} );
                break;

            case 'getAvailTeamEvents':
                console.log('Going to get list of team events');
                const t = await Team.findOneActive({_id: req.query.teamId});
                if (t) {
                    const p = await Event.find({recordStatus: 'active', programId: t.programId}, {
                        name: true,
                        id: true
                    });
                    r.result = "ok";
                    r.list = p;
                    r.list.sort(function(a,b) {return (a.name > b.name) ? 1 : ((b.name > a.name) ? -1 : 0);} );
                } else {
                    throw new Error("Team not found");
                }
                break;
            default:
                if (cmd)
                    console.log('cmd=unknown');
        }
    } catch (err) {
        r.error = {};
        r.error.message = err.message;
    }
    res.json(r);
    res.end();

});

router.post('/', cel.ensureLoggedIn('/login'), async function (req, res, next) {
    const cmd = req.body.cmd;
    console.log("/event - put");
    console.log(req.body);

    const r = {result:"error", status:200};
    r.isAdmin = req.user.isAdmin || req.user.isSuperAdmin;
    r.isEventOrganizer = req.user.isEventOrganizer;

    try {
        switch (cmd) {
            case 'createEvent':
                if (!req.user.isAdmin && !req.user.isProgramManager)
                    return res.render('error',{message:"Prístup zamietnutý"});

                let name = req.body.name;
                console.log('Going to create event ', name);

                let p = await Program.findOneActive({_id:req.body.programId});
                if (!p) throw new Error("Program does not exist");
                let io = await InvoicingOrg.findOneActive({_id:req.body.invOrgId});
                if (!io) throw new Error("Invoicing org does not exist");

                let e = await Event.findOneActive({name:name});
                if (e) throw new Error("Duplicate event name");

                try {
                    e = await Event.create({name: name, programId: p.id, invoicingOrg: io.id});
                    console.log("Event created", e.name, e.id);
                    r.result = "ok";
                    r.event = e;
                } catch (er) {
                    log.ERROR("Failed creating event: "+name+" err="+er.message);
                    r.error = {};
                    r.error.message = er.message;

                }
                break;

            default:
                console.log("cmd=unknown");

        }
    } catch (err) {
        r.error = {};
        r.error.message = err.message;
    }
    res.json(r);
    res.end();

});

router.post('/:id', cel.ensureLoggedIn('/login'), async function (req, res, next) {
    const siteUrl = req.protocol + '://' + req.get("host");
    const cmd = req.body.cmd;

    console.log("/event/:id - put");
    console.log(req.body);

    const r = {result:"error", status:200};
    r.isAdmin = req.user.isAdmin || req.user.isSuperAdmin;
    r.isEventOrganizer = req.user.isEventOrganizer;

    try {
        switch (cmd) {
            case 'registerTeam':
                console.log('Going to register team for an event');

                let t = await Team.findOneActive({_id: req.body.teamId});
                if (!t) throw new Error("Team not found");

                let p = await Program.findOneActive({_id:t.programId});
                if (!p) throw new Error("Team not joined in program");

                let e = await Event.findOneActive({programId:p._id, _id:req.event.id});
                if (!e) throw new Error("Event not found or not relevant for program team is joined to");

                e = await User.populate(e,"managers");
                if (!e) throw new Error("Failed to populate event managers for event id="+e._id);

                let te;
                try {
                    te = await TeamEvent.create({
                        teamId: t.id,
                        eventId: e.id,
                        programId: p.id,
                        registeredOn: Date.now()
                    });
                } catch (er) {
                    log.ERROR("Failed registering team="+t.name+" for event="+e.name+" err="+er.message);
                }

                if (!te) throw new Error("Failed to register");

                let inv;
                try {
                    console.log('Going to create invoice');
                    inv = await libInvoice.createInvoice(te.teamId, te.eventId, "P");
                } catch (er) {
                    log.ERROR("Failed creating invoice for teamId="+te.teamId+" eventId="+te.eventId+" err="+er.message);
                }

                if (inv)
                    email.sendInvoice(req.user, inv, siteUrl);
                if (te)
                    email.sendEventRegisterConfirmation(req.user, t, e, siteUrl);

                r.result = "ok";
                r.teamEvent = te;
                break;
            case "addOrganizer":
                console.log('Going to add organizer for an event');

                if (!req.user.isAdmin && !req.user.isEventOrganizer && !req.user.isProgramManager){
                    log.WARN("addOrganizer: Permission denied for user="+req.user.username);
                    r.error = {message:"permission denied"};
                    break;
                }

                let u = await User.findOneActive({username:req.body.username});
                if (!u) throw new Error("User not found "+req.body.username);

                try {

                    let e = await Event.findOneAndUpdate({_id:req.event._id},{ $addToSet: { managers: u._id } });
                    if (!e) throw new Error("Failed to update event="+req.event._id);

                    r.result = "ok";
                    r.event = e;
                } catch (err) {
                    log.ERROR("Failed to save event organizer. err="+err);
                }
                break;
            case "setDate":
                console.log('Going to set event date');

                if (!req.user.isAdmin && !req.user.isEventOrganizer && !req.user.isProgramManager){
                    log.WARN("setDate: Permission denied for user="+req.user.username);
                    r.error = {message:"permission denied"};
                    break;
                }

                try {

                    let newEvDate = new Date(req.body.newStartDate);

                    let e = await Event.findOneAndUpdate({_id:req.event._id},{ $set: { startDate: newEvDate, endDate:newEvDate } });
                    if (!e) throw new Error("Failed to update event="+req.event._id);

                    r.result = "ok";
                    r.event = e;
                } catch (err) {
                    log.ERROR("Failed to save new event date. err="+err);
                }
                break;

            default:
                console.log("cmd=unknown");

        }
    } catch (err) {
        console.log(err);
        r.error = {message:err.message};
    }
    res.json(r);
    res.end();

});<commit_msg>include event dates in the reply<commit_after>"use strict";

const mongoose = require('mongoose');
const express = require('express');
const cel = require('connect-ensure-login');
const router = express.Router();
const email = require('../lib/email');
const log = require('../lib/logger');
const libInvoice = require('../lib/invoice');
const libFmt = require('../lib/fmt');

const Event = mongoose.models.Event;
const Team = mongoose.models.Team;
const TeamEvent = mongoose.models.TeamEvent;
const Program = mongoose.models.Program;
const InvoicingOrg = mongoose.models.InvoicingOrg;
const User = mongoose.models.User;

module.exports = router;

router.param('id', async function (req, res, next){
    const id = req.params.id;
    let r;
    console.log("Event id",id);
    try {
        r = await Event.findById(id);
        r = await Program.populate(r,'programId');
        r = await InvoicingOrg.populate(r,'invoicingOrg');
        req.event = r;
        if (r) {
            req.user.isEventOrganizer = (req.event.managers.indexOf(req.user.id) >= 0);
            req.user.isProgramManager = (req.event.programId.managers.indexOf(req.user.id) >= 0);
            req.user.isInvoicingOrgManager = (req.event.invoicingOrg.managers.indexOf(req.user.id) >= 0);
            r.teams = [];
            let tmse = await TeamEvent.find({eventId: r.id});
            let tms = await Team.populate(tmse, 'teamId');
            tms.forEach(t => r.teams.push({id: t.teamId.id, name: t.teamId.name}));
            r.teams.sort(function(a,b) {return (a.name > b.name) ? 1 : ((b.name > a.name) ? -1 : 0);} );

            console.log("Event id=", r.id, " name=", r.name);

        } else
            throw new Error("event not found");
        next();
    } catch (err) {
        res.render('error',{message:"Stretnutie/Turnaj nenájdený",error:{status:err.message}});
    }

});

router.get('/:id', async function (req, res, next) {
    const cmd = req.query.cmd;
    console.log("/event/:id - get");

    if (cmd)
        next();
    else
        res.render('event',{event: req.event, user: req.user, fmt:libFmt});

});

router.get('/:id', cel.ensureLoggedIn('/login'), async function (req, res, next) {
    const cmd = req.query.cmd;
    const eventId = req.params.id;
    console.log("/event/:id - get (CMD)");
    console.log(req.query);

    const r = {result:"error", status:200};
    r.isAdmin = req.user.isAdmin || req.user.isSuperAdmin;
    r.isEventOrganizer = req.user.isEventOrganizer;

    try {
        switch (cmd) {
            case 'getTeams':
                console.log('Going to get list of registered teams');
                const te = await TeamEvent.find({eventId:eventId});
                if (!te)
                    throw new Error("Error while fetching teams for event "+eventId);

                r.list = [];
                for (let t of te) {
                    try {
                        console.log("TE=",t.id);
                        let ti = await Team.findById(t.teamId);
                        let a = JSON.parse(JSON.stringify(ti)); // ti is  frozen for adding properties, so copy is needed
                        if (ti) {
                            a.teamEvent = t;
                            r.list.push(a);
                        }
                    } catch (err) {
                        throw new Error("Error while fetching data for teamEvent="+ti.teamEvent);
                    }
                }

                r.result = "ok";
                break;
            case 'getOrganizers':
                console.log('Going to get list of event organizers');
                let e = await User.populate(req.event,{path:"managers", select:{fullName:1}});
                r.list = e.managers;
                r.result = "ok";

                break;

            default:
                console.log('cmd=unknown');
        }
    } catch (err) {
        r.error = err;
        log.ERROR("GET /event/:id failed. err="+err);
    }
    res.json(r);
    res.end();

});

router.get('/', cel.ensureLoggedIn('/login'), async function (req, res, next) {
    const cmd = req.query.cmd;
    const progId = req.query.program;
    console.log("/event - get (CMD)");
    console.log(req.query);

    const r = {result:"error", status:200};
    r.isAdmin = req.user.isAdmin || req.user.isSuperAdmin;
    r.isEventOrganizer = req.user.isEventOrganizer;

    try {
        switch (cmd) {
            case 'getList':
                console.log('Going to get list of all events');
                let q = {recordStatus: 'active'};
                if (progId)
                    q.programId = progId;
                const p = await Event.find(q, {id: 1, name: 1, startDate:1, endDate:1});
                r.result = "ok";
                r.list = p;
                r.list.sort(function(a,b) {return (a.name > b.name) ? 1 : ((b.name > a.name) ? -1 : 0);} );
                break;

            case 'getAvailTeamEvents':
                console.log('Going to get list of team events');
                const t = await Team.findOneActive({_id: req.query.teamId});
                if (t) {
                    const p = await Event.find({recordStatus: 'active', programId: t.programId}, {
                        name: true,
                        id: true
                    });
                    r.result = "ok";
                    r.list = p;
                    r.list.sort(function(a,b) {return (a.name > b.name) ? 1 : ((b.name > a.name) ? -1 : 0);} );
                } else {
                    throw new Error("Team not found");
                }
                break;
            default:
                if (cmd)
                    console.log('cmd=unknown');
        }
    } catch (err) {
        r.error = {};
        r.error.message = err.message;
    }
    res.json(r);
    res.end();

});

router.post('/', cel.ensureLoggedIn('/login'), async function (req, res, next) {
    const cmd = req.body.cmd;
    console.log("/event - put");
    console.log(req.body);

    const r = {result:"error", status:200};
    r.isAdmin = req.user.isAdmin || req.user.isSuperAdmin;
    r.isEventOrganizer = req.user.isEventOrganizer;

    try {
        switch (cmd) {
            case 'createEvent':
                if (!req.user.isAdmin && !req.user.isProgramManager)
                    return res.render('error',{message:"Prístup zamietnutý"});

                let name = req.body.name;
                console.log('Going to create event ', name);

                let p = await Program.findOneActive({_id:req.body.programId});
                if (!p) throw new Error("Program does not exist");
                let io = await InvoicingOrg.findOneActive({_id:req.body.invOrgId});
                if (!io) throw new Error("Invoicing org does not exist");

                let e = await Event.findOneActive({name:name});
                if (e) throw new Error("Duplicate event name");

                try {
                    e = await Event.create({name: name, programId: p.id, invoicingOrg: io.id});
                    console.log("Event created", e.name, e.id);
                    r.result = "ok";
                    r.event = e;
                } catch (er) {
                    log.ERROR("Failed creating event: "+name+" err="+er.message);
                    r.error = {};
                    r.error.message = er.message;

                }
                break;

            default:
                console.log("cmd=unknown");

        }
    } catch (err) {
        r.error = {};
        r.error.message = err.message;
    }
    res.json(r);
    res.end();

});

router.post('/:id', cel.ensureLoggedIn('/login'), async function (req, res, next) {
    const siteUrl = req.protocol + '://' + req.get("host");
    const cmd = req.body.cmd;

    console.log("/event/:id - put");
    console.log(req.body);

    const r = {result:"error", status:200};
    r.isAdmin = req.user.isAdmin || req.user.isSuperAdmin;
    r.isEventOrganizer = req.user.isEventOrganizer;

    try {
        switch (cmd) {
            case 'registerTeam':
                console.log('Going to register team for an event');

                let t = await Team.findOneActive({_id: req.body.teamId});
                if (!t) throw new Error("Team not found");

                let p = await Program.findOneActive({_id:t.programId});
                if (!p) throw new Error("Team not joined in program");

                let e = await Event.findOneActive({programId:p._id, _id:req.event.id});
                if (!e) throw new Error("Event not found or not relevant for program team is joined to");

                e = await User.populate(e,"managers"); // needed in order to get event managers' emails
                if (!e) throw new Error("Failed to populate event managers for event id="+e._id);

                let te;
                try {
                    te = await TeamEvent.create({
                        teamId: t.id,
                        eventId: e.id,
                        programId: p.id,
                        registeredOn: Date.now()
                    });
                } catch (er) {
                    log.ERROR("Failed registering team="+t.name+" for event="+e.name+" err="+er.message);
                }

                if (!te) throw new Error("Failed to register");

                let inv;
                try {
                    console.log('Going to create invoice');
                    inv = await libInvoice.createInvoice(te.teamId, te.eventId, "P");
                } catch (er) {
                    log.ERROR("Failed creating invoice for teamId="+te.teamId+" eventId="+te.eventId+" err="+er.message);
                }

                if (inv)
                    email.sendInvoice(req.user, inv, siteUrl);
                if (te)
                    email.sendEventRegisterConfirmation(req.user, t, e, siteUrl);

                r.result = "ok";
                r.teamEvent = te;
                break;
            case "addOrganizer":
                console.log('Going to add organizer for an event');

                if (!req.user.isAdmin && !req.user.isEventOrganizer && !req.user.isProgramManager){
                    log.WARN("addOrganizer: Permission denied for user="+req.user.username);
                    r.error = {message:"permission denied"};
                    break;
                }

                let u = await User.findOneActive({username:req.body.username});
                if (!u) throw new Error("User not found "+req.body.username);

                try {

                    let e = await Event.findOneAndUpdate({_id:req.event._id},{ $addToSet: { managers: u._id } });
                    if (!e) throw new Error("Failed to update event="+req.event._id);

                    r.result = "ok";
                    r.event = e;
                } catch (err) {
                    log.ERROR("Failed to save event organizer. err="+err);
                }
                break;
            case "setDate":
                console.log('Going to set event date');

                if (!req.user.isAdmin && !req.user.isEventOrganizer && !req.user.isProgramManager){
                    log.WARN("setDate: Permission denied for user="+req.user.username);
                    r.error = {message:"permission denied"};
                    break;
                }

                try {

                    let newEvDate = new Date(req.body.newStartDate);

                    let e = await Event.findOneAndUpdate({_id:req.event._id},{ $set: { startDate: newEvDate, endDate:newEvDate } });
                    if (!e) throw new Error("Failed to update event="+req.event._id);

                    r.result = "ok";
                    r.event = e;
                } catch (err) {
                    log.ERROR("Failed to save new event date. err="+err);
                }
                break;

            default:
                console.log("cmd=unknown");

        }
    } catch (err) {
        console.log(err);
        r.error = {message:err.message};
    }
    res.json(r);
    res.end();

});<|endoftext|>


<commit_before>function dumpModernizr(){
  var str = '';
  dumpModernizr.old = dumpModernizr.old || {};

    for (var prop in Modernizr) {

      // skip previously done ones.
      if (dumpModernizr.old[prop]) continue;
      else dumpModernizr.old[prop] = true;

      if (typeof Modernizr[prop] === 'function') continue;
      // skip unit test items
      if (/^test/.test(prop)) continue;

      if (~TEST.inputs.indexOf(prop)) {
        str += '
'+prop+'{}
';
        for (var field in Modernizr[prop]) {
          str += '
' + field + ': ' + Modernizr[prop][field] + '
';
        }
        str += '

';
      } else {
        str += '
' + prop + ': ' + Modernizr[prop] + '
';
      }
  }
  return str;
}

function grabFeatDetects(){
  // thx github.js
  $.getScript('https://api.github.com/repos/Modernizr/Modernizr/git/trees/master?recursive=1&callback=processTree');
}

function processTree(data){
  var filenames = [];

  for (var i = 0; i < data.data.tree.length; i++){
    var file = data.data.tree[i];
    var match = file.path.match(/^feature-detects\/(.*)/);
    if (!match) continue;

    var relpath = location.host == "modernizr.github.com" ?
                    '../modernizr-git/' : '../';

    filenames.push(relpath + match[0]);
  }

  var jqxhrs = filenames.map(function(filename){
    return jQuery.getScript(filename);
  });

  jQuery.when.apply(jQuery, jqxhrs).done(resultsToDOM);

}

function resultsToDOM(){

  var modOutput = document.createElement('div'),
      ref = document.getElementById('qunit-testresult') || document.getElementById('qunit-tests');

  modOutput.className = 'output';
  modOutput.innerHTML = dumpModernizr();

  ref.parentNode.insertBefore(modOutput, ref);

  // Modernizr object as text
  document.getElementsByTagName('textarea')[0].innerHTML = JSON.stringify(Modernizr);

}

/* uno    */ resultsToDOM();
/* dos    */ grabFeatDetects();
/* tres   */ setTimeout(resultsToDOM,  5e3);
/* quatro */ setTimeout(resultsToDOM, 15e3);
<commit_msg>workaround to test new standalones by themselves.<commit_after>function dumpModernizr(){
  var str = '';
  dumpModernizr.old = dumpModernizr.old || {};

    for (var prop in Modernizr) {

      // skip previously done ones.
      if (dumpModernizr.old[prop]) continue;
      else dumpModernizr.old[prop] = true;

      if (typeof Modernizr[prop] === 'function') continue;
      // skip unit test items
      if (/^test/.test(prop)) continue;

      if (~TEST.inputs.indexOf(prop)) {
        str += '
'+prop+'{}
';
        for (var field in Modernizr[prop]) {
          str += '
' + field + ': ' + Modernizr[prop][field] + '
';
        }
        str += '

';
      } else {
        str += '
' + prop + ': ' + Modernizr[prop] + '
';
      }
  }
  return str;
}

function grabFeatDetects(){

  var tests20120926 = ["a-download", "applicationcache", "audio-audiodata-api", "audio-webaudio-api", "audio", "battery-api", "battery-level", "blob-constructor", "canvas-todataurl-type", "canvas", "canvastext", "contenteditable", "contentsecuritypolicy", "contextmenu", "cookies", "cors", "css-animations", "css-backgroundposition-shorthand", "css-backgroundposition-xy", "css-backgroundrepeat", "css-backgroundsize", "css-backgroundsizecover", "css-borderimage", "css-borderradius", "css-boxshadow", "css-boxsizing", "css-calc", "css-columns", "css-cubicbezierrange", "css-displayrunin", "css-displaytable", "css-filters", "css-flexbox", "css-flexboxlegacy", "css-fontface", "css-generatedcontent", "css-gradients", "css-hsla", "css-hyphens", "css-lastchild", "css-mask", "css-mediaqueries", "css-multiplebgs", "css-objectfit", "css-opacity", "css-overflow-scrolling", "css-pointerevents", "css-positionsticky", "css-reflections", "css-regions", "css-remunit", "css-resize", "css-rgba", "css-scrollbars", "css-subpixelfont", "css-supports", "css-textshadow", "css-transforms", "css-transforms3d", "css-transitions", "css-userselect", "css-vhunit", "css-vmaxunit", "css-vminunit", "css-vwunit", "custom-protocol-handler", "dart", "dataview-api", "dom-classlist", "dom-createElement-attrs", "dom-dataset", "dom-microdata", "draganddrop", "elem-datalist", "elem-details", "elem-output", "elem-progress-meter", "elem-ruby", "elem-time", "elem-track", "emoji", "es5-strictmode", "event-deviceorientation-motion", "exif-orientation", "file-api", "file-filesystem", "forms-fileinput", "forms-formattribute", "forms-inputnumber-l10n", "forms-placeholder", "forms-speechinput", "forms-validation", "fullscreen-api", "gamepad", "geolocation", "getusermedia", "hashchange", "history", "ie8compat", "iframe-sandbox", "iframe-seamless", "iframe-srcdoc", "img-apng", "img-webp-lossless", "img-webp", "indexedDB", "json", "lists-reversed", "mathml", "network-connection", "network-eventsource", "network-xhr2", "notification", "performance", "pointerlock-api", "postmessage", "quota-management-api", "requestanimationframe", "script-async", "script-defer", "storage-localstorage", "storage-sessionstorage", "style-scoped", "svg-clippaths", "svg-filters", "svg-inline", "svg-smil", "svg-svg", "touch", "unicode", "url-data-uri", "userdata", "vibration", "video", "web-intents", "webgl-extensions", "webgl", "websockets-binary", "websockets", "websqldatabase", "window-framed", "workers-blobworkers", "workers-dataworkers", "workers-sharedworkers", "workers-webworkers"];

  if (location.protocol == 'file:'){
    for (var i = 0; i < tests20120926.length; i++){
      var test = tests20120926[i];
      document.write('


<commit_before>/**
 * Created by pkotov on 03.02.2015.
 */

var grunt = require("grunt");
var path = require("path");
var glob = require("glob");
var kelper = require(path.normalize(process.cwd() + "/tasks/kelper"));
var assert = require('chai').assert;
var expect = require('chai').expect;
var should = require('chai').should();

describe("Kelper", function(){

    var lastPhase = "finalization";

    // Setting up Test options
    grunt.file.setBase(__dirname);
    grunt.file.delete("target", {force: true});
    grunt.test = true;

    // Run base setup
    describe("Task setup", function(){

        var plugin = {};
        it('Run plugin base', function(){
            plugin = kelper(grunt);
        });

        it('Check plugin for being registered itself with Grunt', function(){
            should.exist(grunt.task._tasks["kelper"]);
        });

        it('Check module phases', function(){
            var modules = plugin.configuration.phase[lastPhase];
            assert.deepEqual(modules, plugin.configuration.modules, "Finalization phase doesn't include all phases");
        });

    });

    // Checking modules for errors

    var plugin = kelper(grunt);
    var modules = plugin.configuration.phase[lastPhase];

    describe("Checking modules", function(){
        modules.forEach(function(module){
            it(module, function(){
                module = require(plugin.configuration.modulePath + path.sep + module + path.sep + "main").init(grunt);
                assert.ok(module, " works fine");
            });
        });
    });

    // Run modules and watch for results
    describe("Run modules and watch for results", function(){
        describe("Compile module", function(){
            var module = require(plugin.configuration.modulePath + path.sep + "compile" + path.sep + "main").init(grunt);
            module.modulePath = path.dirname(plugin.configuration.builderPath);
            module.environment = plugin.environment;
            it("Run", function(){
                module.run();
            });
            it("Checking for files", function(){
                glob(path.normalize(__dirname + "/expected/target/compiled/**/*.js"), function(err, files){
                    should.not.exist(err, "There is error in files");
                    files.forEach(function(file){
                        should.equal(grunt.file.read(file), grunt.file.read(path.resolve(__dirname + "/target/compiled/", path.basename(file))), "Files are not same (target and expected)");
                    });
                });
            });
        });

        describe("Optimization module", function(){
            var module = require(plugin.configuration.modulePath + path.sep + "optimization" + path.sep + "main").init(grunt);
            module.modulePath = path.dirname(plugin.configuration.builderPath);
            module.environment = plugin.environment;
            it("Run", function(){
                module.run();
            });
            it("Checking for files", function(){
                glob(path.normalize(__dirname + "/expected/target/optimization/**/*.js"), function(err, files){
                    should.not.exist(err, "There is error in files");
                    files.forEach(function(file){
                        should.equal(grunt.file.read(file), grunt.file.read(path.resolve(__dirname + "/target/optimization/", path.basename(file))), "Files are not same (target and expected)");
                    });
                });
            });
        });

        describe("Finalization module", function(){
            var module3 = require(plugin.configuration.modulePath + path.sep + "finalization" + path.sep + "main").init(grunt);
            module3.modulePath = path.dirname(plugin.configuration.builderPath);
            module3.environment = plugin.environment;
            it("Run", function(){
                module3.run();
            });
        });
    });

});<commit_msg>BugFix<commit_after>/**
 * Created by pkotov on 03.02.2015.
 */

var grunt = require("grunt");
var path = require("path");
var glob = require("glob");
var kelper = require(path.normalize(process.cwd() + "/tasks/kelper"));
var assert = require('chai').assert;
var expect = require('chai').expect;
var should = require('chai').should();

describe("Kelper", function(){

    var lastPhase = "finalization";

    // Setting up Test options
    grunt.file.setBase(__dirname);
    grunt.file.delete("target", {force: true});
    grunt.test = true;

    // Run base setup
    describe("Task setup", function(){

        var plugin = {};
        it('Run plugin base', function(){
            plugin = kelper(grunt);
        });

        it('Check plugin for being registered itself with Grunt', function(){
            should.exist(grunt.task._tasks["kelper"]);
        });

        it('Check module phases', function(){
            var modules = plugin.configuration.phase[lastPhase];
            assert.deepEqual(modules, plugin.configuration.modules, "Finalization phase doesn't include all phases");
        });

    });

    // Checking modules for errors

    var plugin = kelper(grunt);
    var modules = plugin.configuration.phase[lastPhase];

    describe("Checking modules", function(){
        modules.forEach(function(module){
            it(module, function(){
                module = require(plugin.configuration.modulePath + path.sep + module + path.sep + "main").init(grunt);
                assert.ok(module, " works fine");
            });
        });
    });

    // Run modules and watch for results
    describe("Run modules and watch for results", function(){
        describe("Compile module", function(){
            var module = require(plugin.configuration.modulePath + path.sep + "compile" + path.sep + "main").init(grunt);
            module.modulePath = path.dirname(plugin.configuration.builderPath);
            module.environment = plugin.environment;
            it("Run", function(done){
                module.run();
                process.nextTick(function () {
                    expect(true).to.equal(true);
                    done();
                });
            });
            it("Checking for files", function(){
                glob(path.normalize(__dirname + "/expected/target/compiled/**/*.js"), function(err, files){
                    should.not.exist(err, "There is error in files");
                    files.forEach(function(file){
                        should.equal(grunt.file.read(file), grunt.file.read(path.resolve(__dirname + "/target/compiled/", path.basename(file))), "Files are not same (target and expected)");
                    });
                });
            });
        });

        describe("Optimization module", function(){
            var module = require(plugin.configuration.modulePath + path.sep + "optimization" + path.sep + "main").init(grunt);
            module.modulePath = path.dirname(plugin.configuration.builderPath);
            module.environment = plugin.environment;
            it("Run", function(done){
                module.run();
                process.nextTick(function () {
                    expect(true).to.equal(true);
                    done();
                });
            });
            it("Checking for files", function(){
                glob(path.normalize(__dirname + "/expected/target/optimization/**/*.js"), function(err, files){
                    should.not.exist(err, "There is error in files");
                    files.forEach(function(file){
                        should.equal(grunt.file.read(file), grunt.file.read(path.resolve(__dirname + "/target/optimization/", path.basename(file))), "Files are not same (target and expected)");
                    });
                });
            });
        });

        describe("Finalization module", function(){
            var module = require(plugin.configuration.modulePath + path.sep + "finalization" + path.sep + "main").init(grunt);
            module.modulePath = path.dirname(plugin.configuration.builderPath);
            module.environment = plugin.environment;
            it("Run", function(done){
                module.run();
                process.nextTick(function () {
                    expect(true).to.equal(true);
                    done();
                });
            });
        });
    });

});<|endoftext|>


<commit_before>'use strict'
/* eslint-env mocha */

const expect = require('chai').expect
const Node = require('../src')
const PeerInfo = require('peer-info')
const multiaddr = require('multiaddr')
const parallel = require('async/parallel')
const map = require('async/map')
const spawn = require('child_process').spawn
const path = require('path')
const pull = require('pull-stream')

describe('libp2p-ipfs-nodejs', () => {
  let nodeA // TCP
  let nodeB // TCP
  let nodeC // TCP
  let nodeD // TCP
  let nodeE // TCP + WebSockets
  let nodeF // WebSockets

  let nodeAMultiaddrTCP
  let nodeBMultiaddrTCP
  let nodeCMultiaddrTCP
  let nodeDMultiaddrTCP
  let nodeEMultiaddrTCP
  let nodeEMultiaddrWebSockets
  let nodeFMultiaddrWebSockets

  let spawnedNode

  it('create 6 nodes', (done) => {
    map([0, 1, 2, 3, 4, 5], (i, cb) => {
      PeerInfo.create(cb)
    }, (err, infos) => {
      if (err) {
        return done(err)
      }

      infos.forEach((info, i) => {
        if (i === 5) {
          return
        }
        info.multiaddr.add(multiaddr('/ip4/0.0.0.0/tcp/0'))
      })

      nodeA = new Node(infos[0])
      nodeB = new Node(infos[1])
      nodeC = new Node(infos[2])
      nodeD = new Node(infos[3])
      nodeE = new Node(infos[4])
      const maddrWS1 = multiaddr('/ip4/127.0.0.1/tcp/25001/ws')
      nodeE.peerInfo.multiaddr.add(maddrWS1)

      nodeEMultiaddrWebSockets = multiaddr(
        nodeE.peerInfo.multiaddrs[1].toString() +
        '/ipfs/' + nodeE.peerInfo.id.toB58String()
      )

      const pInfo = infos[5]
      const maddrWS2 = multiaddr('/ip4/127.0.0.1/tcp/25002/ws')
      pInfo.multiaddr.add(maddrWS2)

      nodeF = new Node(pInfo)

      nodeFMultiaddrWebSockets = multiaddr(
        nodeF.peerInfo.multiaddrs[0].toString() +
        '/ipfs/' + nodeF.peerInfo.id.toB58String()
      )

      done()
    })
  })

  it('start 6 nodes', (done) => {
    parallel([
      (cb) => nodeA.start(cb),
      (cb) => nodeB.start(cb),
      (cb) => nodeC.start(cb),
      (cb) => nodeD.start(cb),
      (cb) => nodeE.start(cb),
      (cb) => nodeF.start(cb)
    ], (err) => {
      expect(err).to.not.exist
      expect(nodeA.peerInfo.multiaddrs.length > 1).to.equal(true)
      expect(nodeB.peerInfo.multiaddrs.length > 1).to.equal(true)
      expect(nodeC.peerInfo.multiaddrs.length > 1).to.equal(true)
      expect(nodeD.peerInfo.multiaddrs.length > 1).to.equal(true)
      expect(nodeE.peerInfo.multiaddrs.length > 2).to.equal(true)
      expect(nodeF.peerInfo.multiaddrs.length).to.equal(1)
      done()
    })
  })

  it('extract TCP multiaddr', () => {
    nodeAMultiaddrTCP = multiaddr((
      nodeA.peerInfo.multiaddrs[0].toString() +
      '/ipfs/' + nodeA.peerInfo.id.toB58String()
      ).replace('0.0.0.0', '127.0.0.1')
    )
    nodeBMultiaddrTCP = multiaddr((
      nodeB.peerInfo.multiaddrs[0].toString() +
      '/ipfs/' + nodeB.peerInfo.id.toB58String()
      ).replace('0.0.0.0', '127.0.0.1')

    )
    nodeCMultiaddrTCP = multiaddr((
      nodeC.peerInfo.multiaddrs[0].toString() +
      '/ipfs/' + nodeC.peerInfo.id.toB58String()
      ).replace('0.0.0.0', '127.0.0.1')

    )
    nodeDMultiaddrTCP = multiaddr((
      nodeD.peerInfo.multiaddrs[0].toString() +
      '/ipfs/' + nodeD.peerInfo.id.toB58String()
      ).replace('0.0.0.0', '127.0.0.1')
    )

    // Note: Here is the multiaddrs[1] again because
    // the .replace in swarm switches the order of
    // the TCP and WS addr
    nodeEMultiaddrTCP = multiaddr((
      nodeE.peerInfo.multiaddrs[1].toString() +
      '/ipfs/' + nodeE.peerInfo.id.toB58String()
      ).replace('0.0.0.0', '127.0.0.1')
    )

    // console.log(nodeAMultiaddrTCP.toString())
    // console.log(nodeBMultiaddrTCP.toString())
    // console.log(nodeCMultiaddrTCP.toString())
    // console.log(nodeDMultiaddrTCP.toString())
    // console.log(nodeEMultiaddrTCP.toString())
  })

  it('handle echo proto in 6 nodes', () => {
    function echo (protocol, conn) {
      pull(conn, conn)
    }

    nodeA.handle('/echo/1.0.0', echo)
    nodeB.handle('/echo/1.0.0', echo)
    nodeC.handle('/echo/1.0.0', echo)
    nodeD.handle('/echo/1.0.0', echo)
    nodeE.handle('/echo/1.0.0', echo)
    nodeF.handle('/echo/1.0.0', echo)
  })

  // General connectivity tests

  it('libp2p.dialByMultiaddr nodeA to nodeB', (done) => {
    nodeA.dialByMultiaddr(nodeBMultiaddrTCP, (err) => {
      expect(err).to.not.exist
      // Some time for Identify to finish
      setTimeout(check, 500)

      function check () {
        parallel([
          (cb) => {
            const peers = nodeA.peerBook.getAll()
            expect(err).to.not.exist
            expect(Object.keys(peers)).to.have.length(1)
            cb()
          },
          (cb) => {
            const peers = nodeB.peerBook.getAll()
            expect(err).to.not.exist
            expect(Object.keys(peers)).to.have.length(1)
            cb()
          }
        ], done)
      }
      // TODO confirm that we got the pubkey through identify
    })
  })

  it('libp2p.dialByMultiaddr on Protocol nodeA to nodeB', (done) => {
    nodeA.dialByMultiaddr(nodeBMultiaddrTCP, '/echo/1.0.0', (err, conn) => {
      expect(err).to.not.exist
      parallel([
        (cb) => {
          const peers = nodeA.peerBook.getAll()
          expect(err).to.not.exist
          expect(Object.keys(peers)).to.have.length(1)
          cb()
        },
        (cb) => {
          const peers = nodeB.peerBook.getAll()
          expect(err).to.not.exist
          expect(Object.keys(peers)).to.have.length(1)
          cb()
        }
      ], () => {
        pull(
          pull.values([Buffer('hey')]),
          conn,
          pull.collect((err, data) => {
            expect(err).to.not.exist
            expect(data).to.be.eql([Buffer('hey')])
            done()
          })
        )
      })
    })
  })

  it('libp2p.hangupByMultiaddr nodeA to nodeB', (done) => {
    nodeA.hangUpByMultiaddr(nodeBMultiaddrTCP, (err) => {
      expect(err).to.not.exist
      setTimeout(check, 500)

      function check () {
        parallel([
          (cb) => {
            const peers = nodeA.peerBook.getAll()
            expect(err).to.not.exist
            expect(Object.keys(peers)).to.have.length(0)
            expect(Object.keys(nodeA.swarm.muxedConns)).to.have.length(0)

            cb()
          },
          (cb) => {
            const peers = nodeB.peerBook.getAll()
            expect(err).to.not.exist
            expect(Object.keys(peers)).to.have.length(0)
            expect(Object.keys(nodeB.swarm.muxedConns)).to.have.length(0)
            cb()
          }
        ], done)
      }
    })
  })

  it('libp2p.dialByPeerInfo nodeA to nodeB', (done) => {
    nodeA.dialByPeerInfo(nodeB.peerInfo, (err) => {
      expect(err).to.not.exist
      // Some time for Identify to finish
      setTimeout(check, 500)

      function check () {
        parallel([
          (cb) => {
            const peers = nodeA.peerBook.getAll()
            expect(err).to.not.exist
            expect(Object.keys(peers)).to.have.length(1)
            cb()
          },
          (cb) => {
            const peers = nodeB.peerBook.getAll()
            expect(err).to.not.exist
            expect(Object.keys(peers)).to.have.length(1)
            cb()
          }
        ], done)
      }
      // TODO confirm that we got the pubkey through identify
    })
  })

  it('libp2p.dialByPeerInfo on Protocol nodeA to nodeB', (done) => {
    nodeA.dialByPeerInfo(nodeB.peerInfo, '/echo/1.0.0', (err, conn) => {
      expect(err).to.not.exist
      parallel([
        (cb) => {
          const peers = nodeA.peerBook.getAll()
          expect(err).to.not.exist
          expect(Object.keys(peers)).to.have.length(1)
          cb()
        },
        (cb) => {
          const peers = nodeB.peerBook.getAll()
          expect(err).to.not.exist
          expect(Object.keys(peers)).to.have.length(1)
          cb()
        }
      ], () => {
        pull(
          pull.values([Buffer('hey')]),
          conn,
          pull.collect((err, data) => {
            expect(err).to.not.exist
            expect(data).to.be.eql([Buffer('hey')])
            done()
          })
        )
      })
    })
  })

  it('libp2p.hangupByPeerInfo nodeA to nodeB', (done) => {
    nodeA.hangUpByPeerInfo(nodeB.peerInfo, (err) => {
      expect(err).to.not.exist
      setTimeout(check, 500)

      function check () {
        parallel([
          (cb) => {
            const peers = nodeA.peerBook.getAll()
            expect(err).to.not.exist
            expect(Object.keys(peers)).to.have.length(0)
            expect(Object.keys(nodeA.swarm.muxedConns)).to.have.length(0)

            cb()
          },
          (cb) => {
            const peers = nodeB.peerBook.getAll()
            expect(err).to.not.exist
            expect(Object.keys(peers)).to.have.length(0)
            expect(Object.keys(nodeB.swarm.muxedConns)).to.have.length(0)
            cb()
          }
        ], done)
      }
    })
  })

  // NOTE, these dialById only works if a previous dial was made
  // until we have PeerRouting
  it.skip('libp2p.dialById nodeA to nodeB', (done) => {})
  it.skip('libp2p.dialById on Protocol nodeA to nodeB', (done) => {})
  it.skip('libp2p.hangupById nodeA to nodeB', (done) => {})

  it('nodeA dial to nodeC and nodeD', (done) => {
    let count = 0
    const next = () => ++count === 2 ? check() : null

    nodeA.dialByMultiaddr(nodeCMultiaddrTCP, next)
    nodeA.dialByMultiaddr(nodeDMultiaddrTCP, next)

    function check () {
      const peers = nodeA.peerBook.getAll()
      expect(Object.keys(peers)).to.have.length(2)
      done()
    }
  })

  // Multiple transport tests

  it('nodeA dial to nodeE', (done) => {
    nodeA.dialByMultiaddr(nodeEMultiaddrTCP, (err) => {
      expect(err).to.not.exist
      const peers = nodeA.peerBook.getAll()
      expect(Object.keys(peers)).to.have.length(3)
      done()
    })
  })

  // Until https://github.com/libp2p/js-libp2p/issues/46 is resolved
  // Everynode will be able to dial in WebSockets
  it.skip('nodeA fails to dial to nodeF', (done) => {
    nodeA.dialByMultiaddr(nodeFMultiaddrWebSockets, (err) => {
      expect(err).to.exist
      const peers = nodeA.peerBook.getAll()
      expect(Object.keys(peers)).to.have.length(3)
      done()
    })
  })

  it('nodeF fails to dial to nodeA', (done) => {
    nodeF.dialByMultiaddr(nodeAMultiaddrTCP, (err) => {
      expect(err).to.exist
      done()
    })
  })

  it('nodeF dial to nodeE', (done) => {
    nodeF.dialByMultiaddr(nodeEMultiaddrWebSockets, (err) => {
      expect(err).to.not.exist
      done()
    })
  })

  // Turbolence tests

  it('spawn a node in a different process', (done) => {
    const filePath = path.join(__dirname, './spawn-libp2p-node.js')
    spawnedNode = spawn(filePath)

    let spawned = false
    spawnedNode.stdout.on('data', (data) => {
      if (!spawned) {
        spawned = true
        done()
      }
    })
  })

  it('connect nodeA to that node', (done) => {
    const spawnedId = require('./test-data/test-id.json')
    const maddr = multiaddr('/ip4/127.0.0.1/tcp/12345/ipfs/' + spawnedId.id)
    nodeA.dialByMultiaddr(maddr, '/echo/1.0.0', (err, conn) => {
      expect(err).to.not.exist
      const peers = nodeA.peerBook.getAll()

      expect(Object.keys(peers)).to.have.length(4)

      pull(
        pull.values([Buffer('hey')]),
        conn,
        pull.collect((err, data) => {
          expect(err).to.not.exist
          expect(data).to.be.eql([Buffer('hey')])
          done()
        })
      )
    })
  })

  it('nodeE ping to nodeF', (done) => {
    nodeE.pingByPeerInfo(nodeF.peerInfo, (err, ping) => {
      expect(err).to.not.exist
      ping.once('ping', (time) => {
        expect(time).to.be.above(0)
        ping.stop()
        done()
      })
    })
  })

  it('crash that node, make sure nodeA continues going steady', (done) => {
    spawnedNode.kill('SIGKILL')

    setTimeout(check, 5000)

    function check () {
      const peers = nodeA.peerBook.getAll()
      expect(Object.keys(peers)).to.have.length(3)
      done()
    }
  })

  it('stop', (done) => {
    parallel([
      (cb) => nodeA.stop(cb),
      (cb) => nodeB.stop(cb),
      (cb) => nodeC.stop(cb),
      (cb) => nodeD.stop(cb),
      (cb) => nodeE.stop(cb),
      (cb) => nodeF.stop(cb)
    ], done)
  })
})
<commit_msg>Use new Buffer instead of Buffer<commit_after>'use strict'
/* eslint-env mocha */

const expect = require('chai').expect
const Node = require('../src')
const PeerInfo = require('peer-info')
const multiaddr = require('multiaddr')
const parallel = require('async/parallel')
const map = require('async/map')
const spawn = require('child_process').spawn
const path = require('path')
const pull = require('pull-stream')

describe('libp2p-ipfs-nodejs', () => {
  let nodeA // TCP
  let nodeB // TCP
  let nodeC // TCP
  let nodeD // TCP
  let nodeE // TCP + WebSockets
  let nodeF // WebSockets

  let nodeAMultiaddrTCP
  let nodeBMultiaddrTCP
  let nodeCMultiaddrTCP
  let nodeDMultiaddrTCP
  let nodeEMultiaddrTCP
  let nodeEMultiaddrWebSockets
  let nodeFMultiaddrWebSockets

  let spawnedNode

  it('create 6 nodes', (done) => {
    map([0, 1, 2, 3, 4, 5], (i, cb) => {
      PeerInfo.create(cb)
    }, (err, infos) => {
      if (err) {
        return done(err)
      }

      infos.forEach((info, i) => {
        if (i === 5) {
          return
        }
        info.multiaddr.add(multiaddr('/ip4/0.0.0.0/tcp/0'))
      })

      nodeA = new Node(infos[0])
      nodeB = new Node(infos[1])
      nodeC = new Node(infos[2])
      nodeD = new Node(infos[3])
      nodeE = new Node(infos[4])
      const maddrWS1 = multiaddr('/ip4/127.0.0.1/tcp/25001/ws')
      nodeE.peerInfo.multiaddr.add(maddrWS1)

      nodeEMultiaddrWebSockets = multiaddr(
        nodeE.peerInfo.multiaddrs[1].toString() +
        '/ipfs/' + nodeE.peerInfo.id.toB58String()
      )

      const pInfo = infos[5]
      const maddrWS2 = multiaddr('/ip4/127.0.0.1/tcp/25002/ws')
      pInfo.multiaddr.add(maddrWS2)

      nodeF = new Node(pInfo)

      nodeFMultiaddrWebSockets = multiaddr(
        nodeF.peerInfo.multiaddrs[0].toString() +
        '/ipfs/' + nodeF.peerInfo.id.toB58String()
      )

      done()
    })
  })

  it('start 6 nodes', (done) => {
    parallel([
      (cb) => nodeA.start(cb),
      (cb) => nodeB.start(cb),
      (cb) => nodeC.start(cb),
      (cb) => nodeD.start(cb),
      (cb) => nodeE.start(cb),
      (cb) => nodeF.start(cb)
    ], (err) => {
      expect(err).to.not.exist
      expect(nodeA.peerInfo.multiaddrs.length > 1).to.equal(true)
      expect(nodeB.peerInfo.multiaddrs.length > 1).to.equal(true)
      expect(nodeC.peerInfo.multiaddrs.length > 1).to.equal(true)
      expect(nodeD.peerInfo.multiaddrs.length > 1).to.equal(true)
      expect(nodeE.peerInfo.multiaddrs.length > 2).to.equal(true)
      expect(nodeF.peerInfo.multiaddrs.length).to.equal(1)
      done()
    })
  })

  it('extract TCP multiaddr', () => {
    nodeAMultiaddrTCP = multiaddr((
      nodeA.peerInfo.multiaddrs[0].toString() +
      '/ipfs/' + nodeA.peerInfo.id.toB58String()
      ).replace('0.0.0.0', '127.0.0.1')
    )
    nodeBMultiaddrTCP = multiaddr((
      nodeB.peerInfo.multiaddrs[0].toString() +
      '/ipfs/' + nodeB.peerInfo.id.toB58String()
      ).replace('0.0.0.0', '127.0.0.1')

    )
    nodeCMultiaddrTCP = multiaddr((
      nodeC.peerInfo.multiaddrs[0].toString() +
      '/ipfs/' + nodeC.peerInfo.id.toB58String()
      ).replace('0.0.0.0', '127.0.0.1')

    )
    nodeDMultiaddrTCP = multiaddr((
      nodeD.peerInfo.multiaddrs[0].toString() +
      '/ipfs/' + nodeD.peerInfo.id.toB58String()
      ).replace('0.0.0.0', '127.0.0.1')
    )

    // Note: Here is the multiaddrs[1] again because
    // the .replace in swarm switches the order of
    // the TCP and WS addr
    nodeEMultiaddrTCP = multiaddr((
      nodeE.peerInfo.multiaddrs[1].toString() +
      '/ipfs/' + nodeE.peerInfo.id.toB58String()
      ).replace('0.0.0.0', '127.0.0.1')
    )

    // console.log(nodeAMultiaddrTCP.toString())
    // console.log(nodeBMultiaddrTCP.toString())
    // console.log(nodeCMultiaddrTCP.toString())
    // console.log(nodeDMultiaddrTCP.toString())
    // console.log(nodeEMultiaddrTCP.toString())
  })

  it('handle echo proto in 6 nodes', () => {
    function echo (protocol, conn) {
      pull(conn, conn)
    }

    nodeA.handle('/echo/1.0.0', echo)
    nodeB.handle('/echo/1.0.0', echo)
    nodeC.handle('/echo/1.0.0', echo)
    nodeD.handle('/echo/1.0.0', echo)
    nodeE.handle('/echo/1.0.0', echo)
    nodeF.handle('/echo/1.0.0', echo)
  })

  // General connectivity tests

  it('libp2p.dialByMultiaddr nodeA to nodeB', (done) => {
    nodeA.dialByMultiaddr(nodeBMultiaddrTCP, (err) => {
      expect(err).to.not.exist
      // Some time for Identify to finish
      setTimeout(check, 500)

      function check () {
        parallel([
          (cb) => {
            const peers = nodeA.peerBook.getAll()
            expect(err).to.not.exist
            expect(Object.keys(peers)).to.have.length(1)
            cb()
          },
          (cb) => {
            const peers = nodeB.peerBook.getAll()
            expect(err).to.not.exist
            expect(Object.keys(peers)).to.have.length(1)
            cb()
          }
        ], done)
      }
      // TODO confirm that we got the pubkey through identify
    })
  })

  it('libp2p.dialByMultiaddr on Protocol nodeA to nodeB', (done) => {
    nodeA.dialByMultiaddr(nodeBMultiaddrTCP, '/echo/1.0.0', (err, conn) => {
      expect(err).to.not.exist
      parallel([
        (cb) => {
          const peers = nodeA.peerBook.getAll()
          expect(err).to.not.exist
          expect(Object.keys(peers)).to.have.length(1)
          cb()
        },
        (cb) => {
          const peers = nodeB.peerBook.getAll()
          expect(err).to.not.exist
          expect(Object.keys(peers)).to.have.length(1)
          cb()
        }
      ], () => {
        pull(
          pull.values([new Buffer('hey')]),
          conn,
          pull.collect((err, data) => {
            expect(err).to.not.exist
            expect(data).to.be.eql([new Buffer('hey')])
            done()
          })
        )
      })
    })
  })

  it('libp2p.hangupByMultiaddr nodeA to nodeB', (done) => {
    nodeA.hangUpByMultiaddr(nodeBMultiaddrTCP, (err) => {
      expect(err).to.not.exist
      setTimeout(check, 500)

      function check () {
        parallel([
          (cb) => {
            const peers = nodeA.peerBook.getAll()
            expect(err).to.not.exist
            expect(Object.keys(peers)).to.have.length(0)
            expect(Object.keys(nodeA.swarm.muxedConns)).to.have.length(0)

            cb()
          },
          (cb) => {
            const peers = nodeB.peerBook.getAll()
            expect(err).to.not.exist
            expect(Object.keys(peers)).to.have.length(0)
            expect(Object.keys(nodeB.swarm.muxedConns)).to.have.length(0)
            cb()
          }
        ], done)
      }
    })
  })

  it('libp2p.dialByPeerInfo nodeA to nodeB', (done) => {
    nodeA.dialByPeerInfo(nodeB.peerInfo, (err) => {
      expect(err).to.not.exist
      // Some time for Identify to finish
      setTimeout(check, 500)

      function check () {
        parallel([
          (cb) => {
            const peers = nodeA.peerBook.getAll()
            expect(err).to.not.exist
            expect(Object.keys(peers)).to.have.length(1)
            cb()
          },
          (cb) => {
            const peers = nodeB.peerBook.getAll()
            expect(err).to.not.exist
            expect(Object.keys(peers)).to.have.length(1)
            cb()
          }
        ], done)
      }
      // TODO confirm that we got the pubkey through identify
    })
  })

  it('libp2p.dialByPeerInfo on Protocol nodeA to nodeB', (done) => {
    nodeA.dialByPeerInfo(nodeB.peerInfo, '/echo/1.0.0', (err, conn) => {
      expect(err).to.not.exist
      parallel([
        (cb) => {
          const peers = nodeA.peerBook.getAll()
          expect(err).to.not.exist
          expect(Object.keys(peers)).to.have.length(1)
          cb()
        },
        (cb) => {
          const peers = nodeB.peerBook.getAll()
          expect(err).to.not.exist
          expect(Object.keys(peers)).to.have.length(1)
          cb()
        }
      ], () => {
        pull(
          pull.values([new Buffer('hey')]),
          conn,
          pull.collect((err, data) => {
            expect(err).to.not.exist
            expect(data).to.be.eql([new Buffer('hey')])
            done()
          })
        )
      })
    })
  })

  it('libp2p.hangupByPeerInfo nodeA to nodeB', (done) => {
    nodeA.hangUpByPeerInfo(nodeB.peerInfo, (err) => {
      expect(err).to.not.exist
      setTimeout(check, 500)

      function check () {
        parallel([
          (cb) => {
            const peers = nodeA.peerBook.getAll()
            expect(err).to.not.exist
            expect(Object.keys(peers)).to.have.length(0)
            expect(Object.keys(nodeA.swarm.muxedConns)).to.have.length(0)

            cb()
          },
          (cb) => {
            const peers = nodeB.peerBook.getAll()
            expect(err).to.not.exist
            expect(Object.keys(peers)).to.have.length(0)
            expect(Object.keys(nodeB.swarm.muxedConns)).to.have.length(0)
            cb()
          }
        ], done)
      }
    })
  })

  // NOTE, these dialById only works if a previous dial was made
  // until we have PeerRouting
  it.skip('libp2p.dialById nodeA to nodeB', (done) => {})
  it.skip('libp2p.dialById on Protocol nodeA to nodeB', (done) => {})
  it.skip('libp2p.hangupById nodeA to nodeB', (done) => {})

  it('nodeA dial to nodeC and nodeD', (done) => {
    let count = 0
    const next = () => ++count === 2 ? check() : null

    nodeA.dialByMultiaddr(nodeCMultiaddrTCP, next)
    nodeA.dialByMultiaddr(nodeDMultiaddrTCP, next)

    function check () {
      const peers = nodeA.peerBook.getAll()
      expect(Object.keys(peers)).to.have.length(2)
      done()
    }
  })

  // Multiple transport tests

  it('nodeA dial to nodeE', (done) => {
    nodeA.dialByMultiaddr(nodeEMultiaddrTCP, (err) => {
      expect(err).to.not.exist
      const peers = nodeA.peerBook.getAll()
      expect(Object.keys(peers)).to.have.length(3)
      done()
    })
  })

  // Until https://github.com/libp2p/js-libp2p/issues/46 is resolved
  // Everynode will be able to dial in WebSockets
  it.skip('nodeA fails to dial to nodeF', (done) => {
    nodeA.dialByMultiaddr(nodeFMultiaddrWebSockets, (err) => {
      expect(err).to.exist
      const peers = nodeA.peerBook.getAll()
      expect(Object.keys(peers)).to.have.length(3)
      done()
    })
  })

  it('nodeF fails to dial to nodeA', (done) => {
    nodeF.dialByMultiaddr(nodeAMultiaddrTCP, (err) => {
      expect(err).to.exist
      done()
    })
  })

  it('nodeF dial to nodeE', (done) => {
    nodeF.dialByMultiaddr(nodeEMultiaddrWebSockets, (err) => {
      expect(err).to.not.exist
      done()
    })
  })

  // Turbolence tests

  it('spawn a node in a different process', (done) => {
    const filePath = path.join(__dirname, './spawn-libp2p-node.js')
    spawnedNode = spawn(filePath)

    let spawned = false
    spawnedNode.stdout.on('data', (data) => {
      if (!spawned) {
        spawned = true
        done()
      }
    })
  })

  it('connect nodeA to that node', (done) => {
    const spawnedId = require('./test-data/test-id.json')
    const maddr = multiaddr('/ip4/127.0.0.1/tcp/12345/ipfs/' + spawnedId.id)
    nodeA.dialByMultiaddr(maddr, '/echo/1.0.0', (err, conn) => {
      expect(err).to.not.exist
      const peers = nodeA.peerBook.getAll()

      expect(Object.keys(peers)).to.have.length(4)

      pull(
        pull.values([new Buffer('hey')]),
        conn,
        pull.collect((err, data) => {
          expect(err).to.not.exist
          expect(data).to.be.eql([new Buffer('hey')])
          done()
        })
      )
    })
  })

  it('nodeE ping to nodeF', (done) => {
    nodeE.pingByPeerInfo(nodeF.peerInfo, (err, ping) => {
      expect(err).to.not.exist
      ping.once('ping', (time) => {
        expect(time).to.be.above(0)
        ping.stop()
        done()
      })
    })
  })

  it('crash that node, make sure nodeA continues going steady', (done) => {
    spawnedNode.kill('SIGKILL')

    setTimeout(check, 5000)

    function check () {
      const peers = nodeA.peerBook.getAll()
      expect(Object.keys(peers)).to.have.length(3)
      done()
    }
  })

  it('stop', (done) => {
    parallel([
      (cb) => nodeA.stop(cb),
      (cb) => nodeB.stop(cb),
      (cb) => nodeC.stop(cb),
      (cb) => nodeD.stop(cb),
      (cb) => nodeE.stop(cb),
      (cb) => nodeF.stop(cb)
    ], done)
  })
})
<|endoftext|>


<commit_before>var config = require('./webpack.config.js')

config.entry = {
  'vue-color': './src/index.js',
}

config.output = {
  filename: './dist/[name].js',
  library: 'VueColor',
  libraryTarget: 'umd'
}

module.exports = config
<commit_msg>fix lint errors<commit_after>var config = require('./webpack.config.js')

config.entry = {
  'vue-color': './src/index.js'
}

config.output = {
  filename: './dist/[name].js',
  library: 'VueColor',
  libraryTarget: 'umd'
}

module.exports = config
<|endoftext|>


<commit_before><commit_msg>Clean aup<commit_after><|endoftext|>


<commit_before>module.exports = {
  coreFrameworks: ['react', 'vue', 'angular', 'web-components'],
  communityFrameworks: ['ember', 'html', 'mithril', 'marko', 'svelte', 'riot', 'preact', 'rax'],
  featureGroups: [
    {
      name: 'Essentials',
      features: [
        {
          name: 'Actions',
          unsupported: [],
          path: 'essentials/actions',
        },
        {
          name: 'Backgrounds',
          unsupported: [],
          path: 'essentials/backgrounds',
        },
        {
          name: 'Docs',
          unsupported: [],
          path: 'writing-docs/introduction',
        },
        {
          name: 'Viewport',
          unsupported: [],
          path: 'essentials/viewport',
        },
        {
          name: 'Controls',
          supported: ['react', 'vue', 'angular', 'web-components', 'ember'],
          path: 'essentials/controls',
        },
      ],
    },
    {
      name: 'Addons',
      features: [
        {
          name: 'a11y',
          unsupported: [],
        },
        {
          name: 'cssresources',
          unsupported: [],
        },
        {
          name: 'design-assets',
          unsupported: [],
        },
        {
          name: 'events',
          unsupported: ['svelte', 'riot'],
        },
        {
          name: 'google-analytics',
          unsupported: [],
        },
        {
          name: 'graphql',
          supported: ['react', 'angular'],
        },
        {
          name: 'jest',
          unsupported: [],
        },
        {
          name: 'knobs',
          unsupported: [],
        },
        {
          name: 'links',
          unsupported: ['marko'],
        },
        {
          name: 'queryparams',
          unsupported: [],
        },
        {
          name: 'Storyshots',
          unsupported: ['ember', 'mithril', 'marko'],
          path: 'workflows/unit-testing',
        },
        {
          name: 'storysource',
          unsupported: [],
        },
      ],
    },
    {
      name: 'Docs',
      features: [
        {
          name: 'MDX Stories',
          unsupported: [],
          path: 'api/mdx',
        },
        {
          name: 'CSF Stories',
          unsupported: [],
          path: 'api/csf',
        },
        {
          name: 'storiesOf stories',
          unsupported: [],
          repoPath: 'lib/core/docs/storiesOf.md',
        },
        {
          name: 'Source',
          unsupported: [],
          path: 'writing-docs/doc-blocks#source',
        },
        {
          name: 'Dynamic source',
          supported: ['react'],
          path: 'writing-docs/doc-blocks#source',
        },
        {
          name: 'Args Table',
          supported: ['react', 'vue', 'angular', 'html', 'ember', 'web-components'],
          path: 'writing-docs/doc-blocks#argstable',
        },
        {
          name: 'Description',
          supported: ['react', 'vue', 'angular', 'ember', 'web-components'],
          path: 'writing-docs/doc-blocks#description',
        },
        {
          name: 'Inline stories',
          supported: ['react', 'vue', 'web-components', 'html', 'svelte'],
          path: 'writing-docs/doc-blocks#inline-rendering',
        },
      ],
    },
  ],
};
<commit_msg>docs: update framework support<commit_after>module.exports = {
  coreFrameworks: ['react', 'vue', 'angular', 'web-components'],
  communityFrameworks: ['ember', 'html', 'mithril', 'marko', 'svelte', 'riot', 'preact', 'rax'],
  featureGroups: [
    {
      name: 'Essentials',
      features: [
        {
          name: 'Actions',
          unsupported: [],
          path: 'essentials/actions',
        },
        {
          name: 'Backgrounds',
          unsupported: [],
          path: 'essentials/backgrounds',
        },
        {
          name: 'Docs',
          unsupported: [],
          path: 'writing-docs/introduction',
        },
        {
          name: 'Viewport',
          unsupported: [],
          path: 'essentials/viewport',
        },
        {
          name: 'Controls',
          supported: ['react', 'vue', 'angular', 'web-components', 'ember'],
          path: 'essentials/controls',
        },
      ],
    },
    {
      name: 'Addons',
      features: [
        {
          name: 'a11y',
          unsupported: [],
        },
        {
          name: 'cssresources',
          unsupported: [],
        },
        {
          name: 'design-assets',
          unsupported: [],
        },
        {
          name: 'events',
          unsupported: ['svelte', 'riot'],
        },
        {
          name: 'google-analytics',
          unsupported: [],
        },
        {
          name: 'graphql',
          supported: ['react', 'angular'],
        },
        {
          name: 'jest',
          unsupported: [],
        },
        {
          name: 'knobs',
          unsupported: [],
        },
        {
          name: 'links',
          unsupported: ['marko'],
        },
        {
          name: 'queryparams',
          unsupported: [],
        },
        {
          name: 'Storyshots',
          unsupported: ['ember', 'mithril', 'marko'],
          path: 'workflows/unit-testing',
        },
        {
          name: 'storysource',
          unsupported: [],
        },
      ],
    },
    {
      name: 'Docs',
      features: [
        {
          name: 'MDX Stories',
          unsupported: [],
          path: 'api/mdx',
        },
        {
          name: 'CSF Stories',
          unsupported: [],
          path: 'api/csf',
        },
        {
          name: 'storiesOf stories',
          unsupported: [],
          repoPath: 'lib/core/docs/storiesOf.md',
        },
        {
          name: 'Source',
          unsupported: [],
          path: 'writing-docs/doc-blocks#source',
        },
        {
          name: 'Dynamic source',
          supported: ['react', 'vue', 'angular', 'svelte'],
          path: 'writing-docs/doc-blocks#source',
        },
        {
          name: 'Args Table',
          supported: ['react', 'vue', 'angular', 'html', 'ember', 'web-components', 'svelte'],
          path: 'writing-docs/doc-blocks#argstable',
        },
        {
          name: 'Description',
          supported: ['react', 'vue', 'angular', 'ember', 'web-components'],
          path: 'writing-docs/doc-blocks#description',
        },
        {
          name: 'Inline stories',
          supported: ['react', 'vue', 'web-components', 'html', 'svelte', 'angular'],
          path: 'writing-docs/doc-blocks#inline-rendering',
        },
      ],
    },
  ],
};
<|endoftext|>


<commit_before>gfw.ui.model.Wall = Backbone.Model.extend({

  defaults: {
    title: "Sign in",
    subtitle: "Didn't receive your password?",
    hidden: false,
    placeholder: "Enter password",
    mode: "login",
    button_title: "Sign in here",
    help: "Please enter your email address and we will send you an email with the site password"
  }

});

gfw.ui.view.Wall = gfw.ui.view.Widget.extend({

  className: 'wall',

  events: {

    "keyup input":   "_clearErrors",
    "click .invite": "_gotoInvite",
    "click .send":   "_send"

  },

  defaults: {
    speed: 250,
    minHeight: 15
  },

  initialize: function() {

    _.bindAll( this, "toggle", "_toggleMode", "_updateTitle", "_updateHelp", "_updateButtonTitle", "_updateSubtitle", "_updatePlaceholder" );

    this.options = _.extend(this.options, this.defaults);

    this.model = new gfw.ui.model.Wall();

    this.add_related_model(this.model);

    this.model.bind("change:hidden", this.toggle);

    this.model.bind("change:title",         this._updateTitle);
    this.model.bind("change:button_title",  this._updateButtonTitle);
    this.model.bind("change:subtitle",      this._updateSubtitle);
    this.model.bind("change:help",          this._updateHelp);
    this.model.bind("change:placeholder",   this._updatePlaceholder);
    this.model.bind("change:mode",          this._toggleMode);

    //this.model.bind("change:closed",    this.toggleOpen);
    //this.model.bind("change:draggable", this.toggleDraggable);

    this.$backdrop = $(".wall_backdrop");

    var template = $("#wall-template").html();

    this.template = new gfw.core.Template({
      template: template,
      type: 'mustache'
    });

  },

  _checkPass: function() {

    if (this.$el.find("input").val() == "gfw") {
      this.createCookie("pass", "gfw_c");
      this.hide();
    } else {
      this.$el.find(".input-field").addClass("error");
      this.$el.find(".input-field").find(".icon.error").fadeIn(250);
      this.$el.find(".input-field").find(".error_input_label").html("Password not valid");
      this.$el.find(".input-field").find(".error_input_label").fadeIn(250);
    }

  },

  hide: function() {
    this.$el.fadeOut(250);
    this.$backdrop.fadeOut(250);
  },

  _clearErrors: function() {

    this.$el.find(".input-field .icon.error").fadeOut(250);
    this.$el.find(".input-field").removeClass("error");
    this.$el.find(".input-field .error_input_label").fadeOut(250);
    this.$el.find(".input-field .error_input_label").html("");

  },

  _send: function(e) {
    var that = this;

    e.preventDefault();
    e.stopPropagation();

    var mode = this.model.get("mode");
    var error = false;

    if (mode == "request") {

      this._clearErrors();

      if (!validateEmail(this.$el.find("input").val())) {
        this.$el.find(".input-field").addClass("error");
        this.$el.find(".input-field").find(".icon.error").fadeIn(250);
        this.$el.find(".input-field").find(".error_input_label").html("Please enter a valid email");
        this.$el.find(".input-field").find(".error_input_label").fadeIn(250);

        error = true;
      }

      if (!error) {
        $.ajax({ type: "post", url: "/register", data: { email: this.$el.find("input").val() }, success: function() {
          that._setMode("thanks");
        }});
      }

  } else {
    this._checkPass();
  }

},

_gotoInvite: function(e) {
  e.preventDefault();
  e.stopPropagation();

  this._setMode("request");
},

_setMode: function(mode) {

  this._clearErrors();

  if (mode == "login") {
    this.model.set({ title: "Sign in", subtitle: "Don’t you have a password?", button_title: "Sign in", placeholder: "Enter password", mode: mode })
  } else if (mode == "request") {
    this.model.set({ title: "Request an invite", help: "Please, enter your email address to require access to the site", button_title: "Send", placeholder: "Enter your email", mode: mode })
  } else if (mode == "thanks") {
    this.model.set({ title: "Thank you :-)", help: "We sent you an email with the password to access the site", placeholder: "Enter password", button_title: "Sign in", mode: mode })
    this.$("input").val("");
  }

},

_toggleMode: function() {

  var mode = this.model.get("mode");

  if (mode == "login") {
    this.$(".invite").fadeIn(250);
    this.$(".help").fadeOut(250);;
  } else if (mode == "request") {
    this.$(".subtitle").fadeOut(250);;
    this.$(".help").fadeIn(250);
  } else if (mode == "thanks") {
    this.$(".subtitle").fadeOut(250);;
    this.$(".help").fadeIn(250);
  }

},

_updatePlaceholder: function() {
  this.$el.find("input[type='text']").attr("placeholder", this.model.get("placeholder"));
},

_updateHelp: function() {
  this.$el.find(".help").html(this.model.get("help"));
},

_updateSubtitle: function() {
  this.$el.find(".subtitle").html(this.model.get("subtitle"));
},

_updateButtonTitle: function() {
  this.$el.find(".send span").html(this.model.get("button_title"));
},

_updateTitle: function() {
  this.$el.find(".title").html(this.model.get("title"));
},

createCookie: function(name, value, days) {
  if (days) {
    var date = new Date();
    date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
    var expires = "; expires=" + date.toGMTString();
  } else var expires = "";
  document.cookie = escape(name) + "=" + escape(value) + expires + "; path=/";
},

readCookie:function(name) {
  var nameEQ = escape(name) + "=";
  var ca = document.cookie.split(';');
  for (var i = 0; i < ca.length; i++) {
    var c = ca[i];
    while (c.charAt(0) == ' ') c = c.substring(1, c.length);
    if (c.indexOf(nameEQ) == 0) return unescape(c.substring(nameEQ.length, c.length));
  }
  return null;
},

eraseCookie: function(name) {
  this.createCookie(name, "", -1);
},

render: function() {
  var that = this;

  if (this.readCookie("pass") == 'gfw_c') return;

  this.$el.append(this.template.render( this.model.toJSON() ));

  this.$backdrop.fadeIn(250);
  this.$el.fadeIn(250);

  return this.$el;
}

});
<commit_msg>Adds wall to window<commit_after>gfw.ui.model.Wall = Backbone.Model.extend({

  defaults: {
    title: "Sign in",
    subtitle: "Didn't receive your password?",
    hidden: false,
    placeholder: "Enter password",
    mode: "login",
    button_title: "Sign in here",
    help: "Please enter your email address and we will send you an email with the site password"
  }

});

gfw.ui.view.Wall = gfw.ui.view.Widget.extend({

  className: 'wall',

  events: {

    "keyup input":   "_clearErrors",
    "click .invite": "_gotoInvite",
    "click .send":   "_send"

  },

  defaults: {
    speed: 250,
    minHeight: 15
  },

  initialize: function() {

    _.bindAll( this, "toggle", "_toggleMode", "_updateTitle", "_updateHelp", "_updateButtonTitle", "_updateSubtitle", "_updatePlaceholder" );

    this.options = _.extend(this.options, this.defaults);

    this.model = new gfw.ui.model.Wall();

    this.add_related_model(this.model);

    this.model.bind("change:hidden", this.toggle);

    this.model.bind("change:title",         this._updateTitle);
    this.model.bind("change:button_title",  this._updateButtonTitle);
    this.model.bind("change:subtitle",      this._updateSubtitle);
    this.model.bind("change:help",          this._updateHelp);
    this.model.bind("change:placeholder",   this._updatePlaceholder);
    this.model.bind("change:mode",          this._toggleMode);

    //this.model.bind("change:closed",    this.toggleOpen);
    //this.model.bind("change:draggable", this.toggleDraggable);

    this.$backdrop = $(".wall_backdrop");

    var template = $("#wall-template").html();

    this.template = new gfw.core.Template({
      template: template,
      type: 'mustache'
    });

  },

  _checkPass: function() {

    if (this.$el.find("input").val() == "gfw") {
      this.createCookie("pass", "ok");
      this.hide();
    } else {
      this.$el.find(".input-field").addClass("error");
      this.$el.find(".input-field").find(".icon.error").fadeIn(250);
      this.$el.find(".input-field").find(".error_input_label").html("Password not valid");
      this.$el.find(".input-field").find(".error_input_label").fadeIn(250);
    }

  },

  hide: function() {
    this.$el.fadeOut(250);
    this.$backdrop.fadeOut(250);
  },

  _clearErrors: function() {

    this.$el.find(".input-field .icon.error").fadeOut(250);
    this.$el.find(".input-field").removeClass("error");
    this.$el.find(".input-field .error_input_label").fadeOut(250);
    this.$el.find(".input-field .error_input_label").html("");

  },

  _send: function(e) {
    var that = this;

    e.preventDefault();
    e.stopPropagation();

    var mode = this.model.get("mode");
    var error = false;

    if (mode == "request") {

      this._clearErrors();

      if (!validateEmail(this.$el.find("input").val())) {
        this.$el.find(".input-field").addClass("error");
        this.$el.find(".input-field").find(".icon.error").fadeIn(250);
        this.$el.find(".input-field").find(".error_input_label").html("Please enter a valid email");
        this.$el.find(".input-field").find(".error_input_label").fadeIn(250);

        error = true;
      }

      if (!error) {
        $.ajax({ type: "post", url: "/register", data: { email: this.$el.find("input").val() }, success: function() {
          that._setMode("thanks");
        }});
      }

  } else {
    this._checkPass();
  }

},

_gotoInvite: function(e) {
  e.preventDefault();
  e.stopPropagation();

  this._setMode("request");
},

_setMode: function(mode) {

  this._clearErrors();

  if (mode == "login") {
    this.model.set({ title: "Sign in", subtitle: "Don’t you have a password?", button_title: "Sign in", placeholder: "Enter password", mode: mode })
  } else if (mode == "request") {
    this.model.set({ title: "Request an invite", help: "Please, enter your email address to require access to the site", button_title: "Send", placeholder: "Enter your email", mode: mode })
  } else if (mode == "thanks") {
    this.model.set({ title: "Thank you :-)", help: "We sent you an email with the password to access the site", placeholder: "Enter password", button_title: "Sign in", mode: mode })
    this.$("input").val("");
  }

},

_toggleMode: function() {

  var mode = this.model.get("mode");

  if (mode == "login") {
    this.$(".invite").fadeIn(250);
    this.$(".help").fadeOut(250);;
  } else if (mode == "request") {
    this.$(".subtitle").fadeOut(250);;
    this.$(".help").fadeIn(250);
  } else if (mode == "thanks") {
    this.$(".subtitle").fadeOut(250);;
    this.$(".help").fadeIn(250);
  }

},

_updatePlaceholder: function() {
  this.$el.find("input[type='text']").attr("placeholder", this.model.get("placeholder"));
},

_updateHelp: function() {
  this.$el.find(".help").html(this.model.get("help"));
},

_updateSubtitle: function() {
  this.$el.find(".subtitle").html(this.model.get("subtitle"));
},

_updateButtonTitle: function() {
  this.$el.find(".send span").html(this.model.get("button_title"));
},

_updateTitle: function() {
  this.$el.find(".title").html(this.model.get("title"));
},

createCookie: function(name, value, days) {
  if (days) {
    var date = new Date();
    date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
    var expires = "; expires=" + date.toGMTString();
  } else var expires = "";
  document.cookie = escape(name) + "=" + escape(value) + expires + "; path=/";
},

readCookie:function(name) {
  var nameEQ = escape(name) + "=";
  var ca = document.cookie.split(';');
  for (var i = 0; i < ca.length; i++) {
    var c = ca[i];
    while (c.charAt(0) == ' ') c = c.substring(1, c.length);
    if (c.indexOf(nameEQ) == 0) return unescape(c.substring(nameEQ.length, c.length));
  }
  return null;
},

eraseCookie: function(name) {
  this.createCookie(name, "", -1);
},

render: function() {
  var that = this;

  if (this.readCookie("pass") == 'ok') return;

  this.$el.append(this.template.render( this.model.toJSON() ));

  this.$backdrop.fadeIn(250);
  this.$el.fadeIn(250);

  return this.$el;
}

});
<|endoftext|>


<commit_before>import {Origin} from '../src/origin';
import {PLATFORM} from 'aurelia-pal';

describe('origin', () => {
  let origin1;
  let origin2;

  beforeEach(() => {
    origin1 = new Origin('ModuleId1', 'ModuleMember1');
    origin2 = new Origin('ModuleId2', 'ModuleMember2');
  });

  describe('get', () => {
    it('should return an empty origin if not set', () => {
      class HasNoOrigin {}
      expect(Origin.get(HasNoOrigin).moduleId).toBe(undefined);
    });

    it('should return the origin if set', () => {
      class HasOrigin {}
      Origin.set(HasOrigin, origin1);

      expect(Origin.get(HasOrigin)).toBe(origin1);
    });
  });

  describe('get - search modules', () => {
    let modules = {'text-file': 'abcdef', 'real-module':{name:'test', x() {return 'hey'}}};
    beforeEach(()=> {
      spyOn(PLATFORM, 'eachModule').and.callFake((callback) => {
        for (let key in modules) callback(key, modules[key]);
      });
    });

    it('should search modules when called', () => {
      class Test {}
      expect(Origin.get(Test).moduleId).toBe(undefined);
      expect(PLATFORM.eachModule).toHaveBeenCalled();
    });

    it('should find member of loaded module', () => {
      let origin = Origin.get(modules['real-module']['x']);
      expect(origin.moduleId).toBe('real-module');
    });

    it('but it should not search in strings', () => {
      expect(Origin.get('a').moduleId).toBe(undefined);
    });
  });

  describe('set', () => {
    it('should attach an origin if one does not exist', () => {
      class HasNoOrigin {}
      Origin.set(HasNoOrigin, origin2);

      expect(Origin.get(HasNoOrigin)).toBe(origin2);
    });
  });
});
<commit_msg>fix(metadata): IE cross origin frame Access Denied on Window['frameElement'] in Origin.get - add test<commit_after>import {Origin} from '../src/origin';
import {PLATFORM} from 'aurelia-pal';

describe('origin', () => {
  let origin1;
  let origin2;

  beforeEach(() => {
    origin1 = new Origin('ModuleId1', 'ModuleMember1');
    origin2 = new Origin('ModuleId2', 'ModuleMember2');
  });

  describe('get', () => {
    it('should return an empty origin if not set', () => {
      class HasNoOrigin {}
      expect(Origin.get(HasNoOrigin).moduleId).toBe(undefined);
    });

    it('should return the origin if set', () => {
      class HasOrigin {}
      Origin.set(HasOrigin, origin1);

      expect(Origin.get(HasOrigin)).toBe(origin1);
    });
  });

  describe('get - search modules', () => {
    let modules = undefined;
    beforeEach(()=> {
      modules = {'text-file': 'abcdef', 'real-module':{name: 'test', x() { return 'hey' }}};
      spyOn(PLATFORM, 'eachModule').and.callFake((callback) => {
        for (let key in modules) callback(key, modules[key]);
      });
    });

    it('should search modules when called', () => {
      class Test {}
      expect(Origin.get(Test).moduleId).toBe(undefined);
      expect(PLATFORM.eachModule).toHaveBeenCalled();
    });

    it('should find member of loaded module', () => {
      let origin = Origin.get(modules['real-module']['x']);
      expect(origin.moduleId).toBe('real-module');
    });

    it('but it should not search in strings', () => {
      expect(Origin.get('a').moduleId).toBe(undefined);
    });

    it('should not fail on accessing restricted/failing members', () => {
      Object.defineProperty(modules['real-module'], 'restricted1', { get: () => { throw new Error('restricted') }, enumerable: true });
      class Test {}
      expect(Origin.get(Test).moduleId).toBe(undefined);
      expect(PLATFORM.eachModule).toHaveBeenCalled();
    });
  });

  describe('set', () => {
    it('should attach an origin if one does not exist', () => {
      class HasNoOrigin {}
      Origin.set(HasNoOrigin, origin2);

      expect(Origin.get(HasNoOrigin)).toBe(origin2);
    });
  });
});
<|endoftext|>