<commit_before>/**
 * Module dependencies.
 */
var mongoose = require('mongoose'),
    env = process.env.NODE_ENV || 'development',
    config = require('../../config/config')[env],
    Schema = mongoose.Schema,
    _ = require('lodash'),
    numeral = require('numeral');

var customNameSchema = new Schema({
    type: Schema.ObjectId,
    displayName: String
});

/**
 * Vendor Schema
 * @todo refactor tools to be use slug as keys? is this possible?
 */
var VendorSchema = new Schema({
    "created": {
        type: Date,
        "default": Date.now
    },
    "searchString" : {
        type: String,
        "default": ''
    },
    "name": {
        type: String,
        "default": '',
        trim: true
    },
    "contactPerson": {
        "name": {
            type: String,
            "default": '',
            trim: true
        },
        "email": {
            type: String,
            "default": '',
            trim: true
        },
        "phone": {
            type: String,
            "default": '',
            trim: true
        }
    },
    "salesRep": {
        type: Schema.ObjectId,
        ref: 'User'
    },
    "vendorRep": {
        type: Schema.ObjectId,
        ref: 'User'
    },
    "logo": {
        "original": {
            type: String,
            "default": '',
            trim: true
        }
    },
    "website": {
        type: String,
        "default": '',
        trim: true
    },
    "legalTerms": {
        type: String,
        "default": '',
        trim: true
    },
    "whiteLabel": {
        type: Boolean,
        "default": false,
        trim: true
    },
    "businessPhone": {
        type: String,
        "default": '',
        trim: true
    },
    "range": {},
    "businessAddress": {
        "address1": {
            type: String,
            "default": '',
            trim: true
        },
        "address2": {
            type: String,
            "default": '',
            trim: true
        },
        "city": {
            type: String,
            "default": '',
            trim: true
        },
        "state": {
            type: String,
            "default": '',
            trim: true
        },
        "zip": {
            type: String,
            "default": '',
            trim: true
        }
    },
    "geo": {
        "latitude": {
            type: Number,
            "default": null
        },
        "longitude": {
            type: Number,
            "default": null
        }
    },
    "tools": {
        'locator': {
            'enabled' : { type: Boolean, "default" : false },
            'display' : String
        },
        'quoter': {
            'enabled' : { type: Boolean, "default" : false },
            'display' : String
        },
        'api': {
            'enabled' : { type: Boolean, "default" : false },
            'display' : String
        }
    },
    "programs": [{
        type: Schema.ObjectId,
        ref: 'Program'
    }],
    "programCustomNames": [customNameSchema],
    "customField": {
        required: {
            type: Boolean,
            "default": false
        },
        enabled: {
            type: Boolean,
            "default": false
        },
        displayName: {
            type: String,
            "default": '',
            trim: true
        }
    },
    "apiKey" : {
        type: String,
        "default": null
    },
    "creditEmailAddress": {
        type: String,
        "default": '',
        trim: true
    }
});

var troop = require('mongoose-troop');
VendorSchema.plugin(troop.merge);

var taggable = require('mongoose-taggable');
VendorSchema.plugin(taggable, {'path':'tags'});
VendorSchema.plugin(taggable, {'path':'industryTags'});

/**
 * Statics
 */
VendorSchema.statics = {

    // this gets called when a vendorId is present in the req.params
    // its a clever way to be able to access req.vendor in the next middlewares
    //
    load: function(id, cb) {
        this.findOne({
            _id: id
        }).populate('programs salesRep vendorRep').exec(cb);
    }
};

/**
 * Runs similar to "after get" callback
 *
 */
VendorSchema.pre('init', function(next, data) {

    // iterate through each program and replace its name with custom name if set
    // @todo not the most effecient
    // attempts to just "merge" the 2 datasets failed, and replaced all the props
    // of programs with custom name
    _.each(data.programs, function(item) {
        var customName = _.where(data.programCustomNames, {
            _id: item._id
        });
        item.displayName = customName.length ? customName[0].displayName : null;
    });

    next();
});

function convertToSlug(Text) {
    return Text
        .toLowerCase()
        .replace(/ /g, '-')
        .replace(/[^\w\-]+/g, '');
}

/**
 * Runs similar to "after get" callback
 *
 */
VendorSchema.post('init', function() {

    // set display name for tools
    // seems silly to save this within the vendor
    // however the model objects needs these props anyway for it to work
    // so its redundent then to set here.
    if(this.tools) {
        this.tools.locator.display = 'Vendor Locator';
        this.tools.quoter.display = 'Quoter';
        this.tools.api.display = 'API';
    }

});

/**
* ----------------------------------------
* Formats and rounds currecny
* ----------------------------------------
*/
var formatPayment = function(payment) {

    return numeral(payment).format('$0,0.00');

};

// function that returns high and low program value given an array of program object
//
var getProgramRange = function(programs) {

    var sheets = _.pluck(programs, 'rateSheet');

    var range = {};
    response = {};

    _.each(sheets, function(item) {
        _.each(item.buyoutOptions, function(item) {
            var costs = item.costs;
            range.min = _.min(_.pluck(costs, 'min'));
            range.max = _.max(_.pluck(costs, 'max'));
        });
    });

    _.each(range, function(item, key) {

        response[key] = {
            display: formatPayment(item / 100),
            value: item / 100
        };

    });

    return response;
};

VendorSchema.pre('save', function(next) {

    /**
    * Process tags from dashboard
    * --------------------------------
    *
    * @note tags are sent as vendorTags which are then saved into vendor.tags
    * @todo refactor with fulltext mondules that @pickle was looking into
    * @note when calling addTag() and removeTag() without a callback, it happens in memory
    *       only and thus will not be refrected in vendor.tags until vendor.save() is complete
    *
    */
    var vendor = this;
    vendor.searchString = '';

    // the tags that are present on the vendor model
    var tagTypes = {'tags' : 'vendorTags', 'industryTags' : 'vendorIndustryTags'};

    _.each(tagTypes, function(type, path) {

        var vendorTags = [];  // tags that are currently being passed from the vendor
        var newTags = [];
        var removeTags = [];

        // create a unified array of current vendor tags
        _.each(vendor[type], function(item) {
            vendorTags.push(item.text);
        });

        newTags = _.difference(vendorTags, vendor[path]);
        removeTags = _.difference(vendor[path], vendorTags);

        _.each(newTags, function(item) {
            vendor.addTag(path, item, function(err, addedTag) {
                console.log('Added: ' + item);
            });
        });

        _.each(removeTags, function(item) {
            vendor.removeTag(path, item, function(err, removedTag) {
                console.log('Removed: ' + item);
            });
        });

        /**
        * A nice way to create a search string that we can use on the dealer locator
        * --------------------------------
        *
        * @todo refactor with fulltext mondules that @pickle was looking into
        *       with a fultext search in place, we could just send tag searches as get queries
        *       and let the server do all the work.
        *
        */

        // will be present when updating from dashboard
        if(vendor[type]) {

            _.each(vendor[type], function(tag) {
                vendor.searchString += tag.text + ' ';
            });

        // on seed data
        } else {
            _.each(vendor[path], function(tag) {
                vendor.searchString += tag + ' ';
            });
        }
    });

    /**
    * Standardize tool slugs
    *
    */
/*
    _.each(vendor.tools, function(item) {
        item.slug = convertToSlug(item.name);
    });
*/

    /**
    * Generate API key if api tool is enabled and no key exists
    *
    * @note to change the API key enable and then disable
    *
    */
    if(this.isModified('tools') && this.tools.api.enabled === true && !this.isNew) {
        var key = require('node-uuid')();
        this.apiKey = key;
    }

    // find a range, min and max value, for this program
    // we'll use this to quickly check if a quote value is within range
    //

    console.log('Generating ranges for vendor???');
    console.log(vendor.programs);
    if(vendor.programs) {

        console.log('Generating ranges for vendor');
        mongoose.models.Program
            .find({_id: { $in: vendor.programs }})
            .exec(function(err, data) {

                console.log(data);

                if(data) {
                    vendor.range = getProgramRange(data);
                }

                next();

            });

    } else {
        next();
    }

});

VendorSchema.statics = {

    getCurrentReps: function(vendorId, cb) {

        // attempt to get the sales rep, which we save with the quote
        // for easy geting from the database
        return this.findOne({
            _id: vendorId
        }).populate('vendorRep').exec(function(err, result) {
            if (err) return cb(err);
            if (result && result._id) {
                return cb(null, result);
            } else {
                return cb(new Error(vendorId + ' is Not a valid vendor id'));
            }
        });
    },
    load: function(id, cb) {
        this.findOne({
            _id: id
        }).populate('programs salesRep vendorRep').exec(cb);
    }
};

mongoose.model('Vendor', VendorSchema);
<commit_msg>Remove console logs<commit_after>/**
 * Module dependencies.
 */
var mongoose = require('mongoose'),
    env = process.env.NODE_ENV || 'development',
    config = require('../../config/config')[env],
    Schema = mongoose.Schema,
    _ = require('lodash'),
    numeral = require('numeral');

var customNameSchema = new Schema({
    type: Schema.ObjectId,
    displayName: String
});

/**
 * Vendor Schema
 * @todo refactor tools to be use slug as keys? is this possible?
 */
var VendorSchema = new Schema({
    "created": {
        type: Date,
        "default": Date.now
    },
    "searchString" : {
        type: String,
        "default": ''
    },
    "name": {
        type: String,
        "default": '',
        trim: true
    },
    "contactPerson": {
        "name": {
            type: String,
            "default": '',
            trim: true
        },
        "email": {
            type: String,
            "default": '',
            trim: true
        },
        "phone": {
            type: String,
            "default": '',
            trim: true
        }
    },
    "salesRep": {
        type: Schema.ObjectId,
        ref: 'User'
    },
    "vendorRep": {
        type: Schema.ObjectId,
        ref: 'User'
    },
    "logo": {
        "original": {
            type: String,
            "default": '',
            trim: true
        }
    },
    "website": {
        type: String,
        "default": '',
        trim: true
    },
    "legalTerms": {
        type: String,
        "default": '',
        trim: true
    },
    "whiteLabel": {
        type: Boolean,
        "default": false,
        trim: true
    },
    "businessPhone": {
        type: String,
        "default": '',
        trim: true
    },
    "range": {},
    "businessAddress": {
        "address1": {
            type: String,
            "default": '',
            trim: true
        },
        "address2": {
            type: String,
            "default": '',
            trim: true
        },
        "city": {
            type: String,
            "default": '',
            trim: true
        },
        "state": {
            type: String,
            "default": '',
            trim: true
        },
        "zip": {
            type: String,
            "default": '',
            trim: true
        }
    },
    "geo": {
        "latitude": {
            type: Number,
            "default": null
        },
        "longitude": {
            type: Number,
            "default": null
        }
    },
    "tools": {
        'locator': {
            'enabled' : { type: Boolean, "default" : false },
            'display' : String
        },
        'quoter': {
            'enabled' : { type: Boolean, "default" : false },
            'display' : String
        },
        'api': {
            'enabled' : { type: Boolean, "default" : false },
            'display' : String
        }
    },
    "programs": [{
        type: Schema.ObjectId,
        ref: 'Program'
    }],
    "programCustomNames": [customNameSchema],
    "customField": {
        required: {
            type: Boolean,
            "default": false
        },
        enabled: {
            type: Boolean,
            "default": false
        },
        displayName: {
            type: String,
            "default": '',
            trim: true
        }
    },
    "apiKey" : {
        type: String,
        "default": null
    },
    "creditEmailAddress": {
        type: String,
        "default": '',
        trim: true
    }
});

var troop = require('mongoose-troop');
VendorSchema.plugin(troop.merge);

var taggable = require('mongoose-taggable');
VendorSchema.plugin(taggable, {'path':'tags'});
VendorSchema.plugin(taggable, {'path':'industryTags'});

/**
 * Statics
 */
VendorSchema.statics = {

    // this gets called when a vendorId is present in the req.params
    // its a clever way to be able to access req.vendor in the next middlewares
    //
    load: function(id, cb) {
        this.findOne({
            _id: id
        }).populate('programs salesRep vendorRep').exec(cb);
    }
};

/**
 * Runs similar to "after get" callback
 *
 */
VendorSchema.pre('init', function(next, data) {

    // iterate through each program and replace its name with custom name if set
    // @todo not the most effecient
    // attempts to just "merge" the 2 datasets failed, and replaced all the props
    // of programs with custom name
    _.each(data.programs, function(item) {
        var customName = _.where(data.programCustomNames, {
            _id: item._id
        });
        item.displayName = customName.length ? customName[0].displayName : null;
    });

    next();
});

function convertToSlug(Text) {
    return Text
        .toLowerCase()
        .replace(/ /g, '-')
        .replace(/[^\w\-]+/g, '');
}

/**
 * Runs similar to "after get" callback
 *
 */
VendorSchema.post('init', function() {

    // set display name for tools
    // seems silly to save this within the vendor
    // however the model objects needs these props anyway for it to work
    // so its redundent then to set here.
    if(this.tools) {
        this.tools.locator.display = 'Vendor Locator';
        this.tools.quoter.display = 'Quoter';
        this.tools.api.display = 'API';
    }

});

/**
* ----------------------------------------
* Formats and rounds currecny
* ----------------------------------------
*/
var formatPayment = function(payment) {

    return numeral(payment).format('$0,0.00');

};

// function that returns high and low program value given an array of program object
//
var getProgramRange = function(programs) {

    var sheets = _.pluck(programs, 'rateSheet');

    var range = {};
    response = {};

    _.each(sheets, function(item) {
        _.each(item.buyoutOptions, function(item) {
            var costs = item.costs;
            range.min = _.min(_.pluck(costs, 'min'));
            range.max = _.max(_.pluck(costs, 'max'));
        });
    });

    _.each(range, function(item, key) {

        response[key] = {
            display: formatPayment(item / 100),
            value: item / 100
        };

    });

    return response;
};

VendorSchema.pre('save', function(next) {

    /**
    * Process tags from dashboard
    * --------------------------------
    *
    * @note tags are sent as vendorTags which are then saved into vendor.tags
    * @todo refactor with fulltext mondules that @pickle was looking into
    * @note when calling addTag() and removeTag() without a callback, it happens in memory
    *       only and thus will not be refrected in vendor.tags until vendor.save() is complete
    *
    */
    var vendor = this;
    vendor.searchString = '';

    // the tags that are present on the vendor model
    var tagTypes = {'tags' : 'vendorTags', 'industryTags' : 'vendorIndustryTags'};

    _.each(tagTypes, function(type, path) {

        var vendorTags = [];  // tags that are currently being passed from the vendor
        var newTags = [];
        var removeTags = [];

        // create a unified array of current vendor tags
        _.each(vendor[type], function(item) {
            vendorTags.push(item.text);
        });

        newTags = _.difference(vendorTags, vendor[path]);
        removeTags = _.difference(vendor[path], vendorTags);

        _.each(newTags, function(item) {
            vendor.addTag(path, item, function(err, addedTag) {
                console.log('Added: ' + item);
            });
        });

        _.each(removeTags, function(item) {
            vendor.removeTag(path, item, function(err, removedTag) {
                console.log('Removed: ' + item);
            });
        });

        /**
        * A nice way to create a search string that we can use on the dealer locator
        * --------------------------------
        *
        * @todo refactor with fulltext mondules that @pickle was looking into
        *       with a fultext search in place, we could just send tag searches as get queries
        *       and let the server do all the work.
        *
        */

        // will be present when updating from dashboard
        if(vendor[type]) {

            _.each(vendor[type], function(tag) {
                vendor.searchString += tag.text + ' ';
            });

        // on seed data
        } else {
            _.each(vendor[path], function(tag) {
                vendor.searchString += tag + ' ';
            });
        }
    });

    /**
    * Standardize tool slugs
    *
    */
/*
    _.each(vendor.tools, function(item) {
        item.slug = convertToSlug(item.name);
    });
*/

    /**
    * Generate API key if api tool is enabled and no key exists
    *
    * @note to change the API key enable and then disable
    *
    */
    if(this.isModified('tools') && this.tools.api.enabled === true && !this.isNew) {
        var key = require('node-uuid')();
        this.apiKey = key;
    }

    // find a range, min and max value, for this program
    // we'll use this to quickly check if a quote value is within range
    //

    if(vendor.programs) {

        mongoose.models.Program
            .find({_id: { $in: vendor.programs }})
            .exec(function(err, data) {

                if(data) {
                    vendor.range = getProgramRange(data);
                }

                next();

            });

    } else {
        next();
    }

});

VendorSchema.statics = {

    getCurrentReps: function(vendorId, cb) {

        // attempt to get the sales rep, which we save with the quote
        // for easy geting from the database
        return this.findOne({
            _id: vendorId
        }).populate('vendorRep').exec(function(err, result) {
            if (err) return cb(err);
            if (result && result._id) {
                return cb(null, result);
            } else {
                return cb(new Error(vendorId + ' is Not a valid vendor id'));
            }
        });
    },
    load: function(id, cb) {
        this.findOne({
            _id: id
        }).populate('programs salesRep vendorRep').exec(cb);
    }
};

mongoose.model('Vendor', VendorSchema);
<|endoftext|>


<commit_before>dbs_nav = function(pId) {
	var xNav = $(pId);

	$(window).resize(function(){
		dbsfaces.nav.resized(xNav);
	});

	dbsfaces.nav.initialize(xNav);

	$(pId + " > .-container > .-icon").on("mousedown touchstart", function(e){
		dbsfaces.nav.show(xNav);
		return false;
	});

	$(pId + " > .-container > .-mask").on("mousedown touchstart", function(e){
		dbsfaces.nav.show(xNav);
		return false;
	});

	$(pId + " > .-container > .-nav").on("mousewheel touchmove", function(e){
		e.stopImmediatePropagation();
	});
	$(pId + " > .-container > .-mask").on("mousewheel touchmove", function(e){
//		e.preventDefault();
//		e.stopPropagation();
		e.stopImmediatePropagation();
//		return false;
	});

	$(pId + " > .-container > .-nav > .-iconclose").on("mousedown touchstart", function(e){
		dbsfaces.nav.show(xNav);
		return false;
	});

};

dbsfaces.nav = {
	initialize: function(pNav){
		dbsfaces.nav.pvInitializeData(pNav);
		dbsfaces.nav.pvInitializeLayout(pNav);
	},

	pvInitializeData: function(pNav){
		var xTop = pNav.hasClass("-tlh")
		        || pNav.hasClass("-tlv")
		        || pNav.hasClass("-trh")
		        || pNav.hasClass("-trv");

		var xLeft = pNav.hasClass("-tlh")
		         || pNav.hasClass("-tlv")
		         || pNav.hasClass("-blh")
		         || pNav.hasClass("-blt");

		var xVertical = pNav.hasClass("-tlv")
		         	 || pNav.hasClass("-trv")
		         	 || pNav.hasClass("-blv")
		         	 || pNav.hasClass("-brv");

		pNav.data("t", xTop);
		pNav.data("l", xLeft);
		pNav.data("v", xVertical);
		pNav.data("navgroup", pNav.find("> .-container > .-nav"));
		pNav.data("container", pNav.data("navgroup").children(".-container"));
		pNav.data("content", pNav.data("container").children(".-content"));
		pNav.data("nav", pNav.data("content").find("> div > nav"));
		pNav.data("header", pNav.data("navgroup").children(".-header"));
		pNav.data("footer", pNav.data("navgroup").children(".-footer"));
//		pNav.data("foocaption", pNav.data("container").children(".-foocaption"));
		pNav.data("icon", pNav.find("> .-container > .-icon"));
		pNav.data("mask", pNav.find("> .-container > .-mask"));
		pNav.data("iconclose", pNav.data("navgroup").children(".-iconclose"));
		pNav.data("padding", parseFloat(pNav.data("mask").css("padding-left")));
	},

	pvInitializeLayout: function(pNav){
		if (!pNav.hasClass("-closed")){
			dbsfaces.nav.pvOpen(pNav);
		}
		pNav.children(".-container").css("opacity", "");
		var xColor = tinycolor(pNav.data("navgroup").css("background-color"));
		xColor.setAlpha(.5);
		pNav.data("iconclose").css("background-color", xColor.toRgbString());
	},

	resized: function(pNav){
		if (!pNav.hasClass("-closed")){
			dbsfaces.nav.pvAjustLayout(pNav);
		}
	},

	show: function(pNav, p){
		//Está fechado e vai abrir
		if (pNav.hasClass("-closed")){
			dbsfaces.nav.pvOpen(pNav);
		}else{
			dbsfaces.nav.pvClose(pNav);
		}
		pNav.toggleClass("-closed -th_i");
	},

	pvOpen: function(pNav){
		dbsfaces.nav.pvAjustLayout(pNav);
		dbsfaces.ui.disableBackgroundInputs(pNav);
		$("html").addClass("dbs_nav-freeze");
	},

	pvClose: function(pNav){
		pNav.data("navgroup").css("height", "")
		 					 .css("width", "");
		dbsfaces.ui.enableForegroundInputs($("body"));
		$("html").removeClass("dbs_nav-freeze");
	},

	pvAjustLayout: function(pNav){
//		var xPadding = pNav.data("padding");
		var xLimit = 95;
		var xPadding = 0;
		var xMask = pNav.data("mask");
		var xHeader = pNav.data("header");
		var xFooter = pNav.data("footer");
		var xContainer = pNav.data("container");
		var xMaskWidth = xMask.get(0).getBoundingClientRect().width * (xLimit / 100);
		var xMaskHeight = xMask.get(0).getBoundingClientRect().height * (xLimit / 100);
		var xHeaderWidth = pNav.data("iconclose").get(0).getBoundingClientRect().width;
		var xHeaderHeight = pNav.data("iconclose").get(0).getBoundingClientRect().height;
		var xFooterWidth = null;
		var xFooterHeight = null;
		if (xHeader.length > 0){
			xHeaderWidth = xHeader.get(0).getBoundingClientRect().width;
			xHeaderHeight = xHeader.get(0).getBoundingClientRect().height;
		}
		if (xFooter.length > 0){
			xFooterWidth = xFooter.get(0).getBoundingClientRect().width;
			xFooterHeight = xFooter.get(0).getBoundingClientRect().height;
		}

		//Limita dimensão
		if (pNav.data("v")){
			pNav.data("navgroup").css("width", "");
			var xWidth = pNav.data("nav").get(0).getBoundingClientRect().width + (xPadding * 2);
			//Utiliza largura do caption se este for maior que largura do conteúdo do nav
			if (xHeaderWidth > xWidth){
				xWidth = xHeaderWidth;
			}
//			xWidth += (xPadding * 2);
			//Força largura máxima em 95% caso largura seja superior a largura da tela
			if (xWidth > xMaskWidth){
				xWidth = xLimit + "%";
			}
			//Limita largura a largura do conteúdo do nav
			pNav.data("navgroup").css("width", xWidth);
//			pNav.data("foocaption").css("height", xHeaderHeight + xPadding);
			if (pNav.data("t")){
//				if (xHeaderHeight != null){
					xContainer.css("padding-top", xHeaderHeight + xPadding);
//				}
				if (xFooterHeight != null){
					xContainer.css("padding-bottom", xFooterHeight + xPadding);
				}
			}else{
//				if (xHeaderHeight != null){
					xContainer.css("padding-bottom", xHeaderHeight + xPadding);
//				}
				if (xFooterHeight != null){
					xContainer.css("padding-top", xFooterHeight + xPadding);
				}
			}
		}else{
			pNav.data("navgroup").css("height", "");
			var xHeight = pNav.data("nav").get(0).getBoundingClientRect().height + (xPadding * 2);
			if (xHeight > xMaskHeight){
				xHeight = xLimit + "%";
			}
//			xHeight += (xPadding * 2);
			//Limita altura a altura do conteúdo do nav
			pNav.data("navgroup").css("height", xHeight);
//			pNav.data("foocaption").css("width", xHeaderHeight + xPadding);
			if (pNav.data("l")){
//				if (xHeaderWidth != null){
					xContainer.css("padding-left", xHeaderWidth + xPadding);
//				}
				if (xFooterWidth != null){
					xContainer.css("padding-right", xFooterWidth + xPadding);
				}
			}else{
//				if (xHeaderWidth != null){
					xContainer.css("padding-right", xHeaderWidth + xPadding);
//				}
				if (xFooterWidth != null){
					xContainer.css("padding-left", xFooterWidth + xPadding);
				}
			}
		}

	}

};

<commit_msg>Posiciona no primeiro input<commit_after>dbs_nav = function(pId) {
	var xNav = $(pId);

	$(window).resize(function(){
		dbsfaces.nav.resized(xNav);
	});

	dbsfaces.nav.initialize(xNav);

	$(pId + " > .-container > .-icon").on("mousedown touchstart", function(e){
		dbsfaces.nav.show(xNav);
		return false;
	});

	$(pId + " > .-container > .-mask").on("mousedown touchstart", function(e){
		dbsfaces.nav.show(xNav);
		return false;
	});

	$(pId + " > .-container > .-nav").on("mousewheel touchmove", function(e){
		e.stopImmediatePropagation();
	});
	$(pId + " > .-container > .-mask").on("mousewheel touchmove", function(e){
//		e.preventDefault();
//		e.stopPropagation();
		e.stopImmediatePropagation();
//		return false;
	});

	$(pId + " > .-container > .-nav > .-iconclose").on("mousedown touchstart", function(e){
		dbsfaces.nav.show(xNav);
		return false;
	});

	$(pId + " > .-container > .-nav").on(dbsfaces.EVENT.ON_TRANSITION_END, function(e){
		dbsfaces.ui.focusOnFirstInput($(this));
	});

};

dbsfaces.nav = {
	initialize: function(pNav){
		dbsfaces.nav.pvInitializeData(pNav);
		dbsfaces.nav.pvInitializeLayout(pNav);
	},

	pvInitializeData: function(pNav){
		var xTop = pNav.hasClass("-tlh")
		        || pNav.hasClass("-tlv")
		        || pNav.hasClass("-trh")
		        || pNav.hasClass("-trv");

		var xLeft = pNav.hasClass("-tlh")
		         || pNav.hasClass("-tlv")
		         || pNav.hasClass("-blh")
		         || pNav.hasClass("-blt");

		var xVertical = pNav.hasClass("-tlv")
		         	 || pNav.hasClass("-trv")
		         	 || pNav.hasClass("-blv")
		         	 || pNav.hasClass("-brv");

		pNav.data("t", xTop);
		pNav.data("l", xLeft);
		pNav.data("v", xVertical);
		pNav.data("navgroup", pNav.find("> .-container > .-nav"));
		pNav.data("container", pNav.data("navgroup").children(".-container"));
		pNav.data("content", pNav.data("container").children(".-content"));
		pNav.data("nav", pNav.data("content").find("> div > nav"));
		pNav.data("header", pNav.data("navgroup").children(".-header"));
		pNav.data("footer", pNav.data("navgroup").children(".-footer"));
//		pNav.data("foocaption", pNav.data("container").children(".-foocaption"));
		pNav.data("icon", pNav.find("> .-container > .-icon"));
		pNav.data("mask", pNav.find("> .-container > .-mask"));
		pNav.data("iconclose", pNav.data("navgroup").children(".-iconclose"));
		pNav.data("padding", parseFloat(pNav.data("mask").css("padding-left")));
	},

	pvInitializeLayout: function(pNav){
		if (!pNav.hasClass("-closed")){
			dbsfaces.nav.pvOpen(pNav);
		}
		pNav.children(".-container").css("opacity", "");
		var xColor = tinycolor(pNav.data("navgroup").css("background-color"));
		xColor.setAlpha(.5);
		pNav.data("iconclose").css("background-color", xColor.toRgbString());
	},

	resized: function(pNav){
		if (!pNav.hasClass("-closed")){
			dbsfaces.nav.pvAjustLayout(pNav);
		}
	},

	show: function(pNav, p){
		//Está fechado e vai abrir
		if (pNav.hasClass("-closed")){
			dbsfaces.nav.pvOpen(pNav);
		}else{
			dbsfaces.nav.pvClose(pNav);
		}
		pNav.toggleClass("-closed -th_i");
	},

	pvOpen: function(pNav){
		dbsfaces.nav.pvAjustLayout(pNav);
		dbsfaces.ui.disableBackgroundInputs(pNav);
		$("html").addClass("dbs_nav-freeze");
	},

	pvClose: function(pNav){
		pNav.data("navgroup").css("height", "")
		 					 .css("width", "");
		dbsfaces.ui.enableForegroundInputs($("body"));
		$("html").removeClass("dbs_nav-freeze");
	},

	pvAjustLayout: function(pNav){
//		var xPadding = pNav.data("padding");
		var xLimit = 95;
		var xPadding = 0;
		var xMask = pNav.data("mask");
		var xHeader = pNav.data("header");
		var xFooter = pNav.data("footer");
		var xContainer = pNav.data("container");
		var xMaskWidth = xMask.get(0).getBoundingClientRect().width * (xLimit / 100);
		var xMaskHeight = xMask.get(0).getBoundingClientRect().height * (xLimit / 100);
		var xHeaderWidth = pNav.data("iconclose").get(0).getBoundingClientRect().width;
		var xHeaderHeight = pNav.data("iconclose").get(0).getBoundingClientRect().height;
		var xFooterWidth = null;
		var xFooterHeight = null;
		if (xHeader.length > 0){
			xHeaderWidth = xHeader.get(0).getBoundingClientRect().width;
			xHeaderHeight = xHeader.get(0).getBoundingClientRect().height;
		}
		if (xFooter.length > 0){
			xFooterWidth = xFooter.get(0).getBoundingClientRect().width;
			xFooterHeight = xFooter.get(0).getBoundingClientRect().height;
		}

		//Limita dimensão
		if (pNav.data("v")){
			pNav.data("navgroup").css("width", "");
			var xWidth = pNav.data("nav").get(0).getBoundingClientRect().width + (xPadding * 2);
			//Utiliza largura do caption se este for maior que largura do conteúdo do nav
			if (xHeaderWidth > xWidth){
				xWidth = xHeaderWidth;
			}
//			xWidth += (xPadding * 2);
			//Força largura máxima em 95% caso largura seja superior a largura da tela
			if (xWidth > xMaskWidth){
				xWidth = xLimit + "%";
			}
			//Limita largura a largura do conteúdo do nav
			pNav.data("navgroup").css("width", xWidth);
//			pNav.data("foocaption").css("height", xHeaderHeight + xPadding);
			if (pNav.data("t")){
				xContainer.css("padding-top", xHeaderHeight + xPadding);
				if (xFooterHeight != null){
					xContainer.css("padding-bottom", xFooterHeight + xPadding);
				}
			}else{
				xContainer.css("padding-bottom", xHeaderHeight + xPadding);
				if (xFooterHeight != null){
					xContainer.css("padding-top", xFooterHeight + xPadding);
				}
			}
		}else{
			pNav.data("navgroup").css("height", "");
			var xHeight = pNav.data("nav").get(0).getBoundingClientRect().height + (xPadding * 2);
			if (xHeight > xMaskHeight){
				xHeight = xLimit + "%";
			}
//			xHeight += (xPadding * 2);
			//Limita altura a altura do conteúdo do nav
			pNav.data("navgroup").css("height", xHeight);
//			pNav.data("foocaption").css("width", xHeaderHeight + xPadding);
			if (pNav.data("l")){
				xContainer.css("padding-left", xHeaderWidth + xPadding);
				if (xFooterWidth != null){
					xContainer.css("padding-right", xFooterWidth + xPadding);
				}
			}else{
				xContainer.css("padding-right", xHeaderWidth + xPadding);
				if (xFooterWidth != null){
					xContainer.css("padding-left", xFooterWidth + xPadding);
				}
			}
		}

	}

};

<|endoftext|>


<commit_before>import { describe, it }   from 'mocha'
import { setupModelTest } from 'ember-mocha'
import { expect }         from 'chai'

describe('Unit | Model | user', function() {
  setupModelTest('user', {
    needs: [
      'model:employment'
    ]
  })

  it('exists', function() {
    let model = this.subject()

    expect(model).to.be.ok
  })

  it('computes a full name', function() {
    let model = this.subject({ firstName: 'Hans', lastName: 'Muster' })

    expect(model).to.be.ok

    expect(model.get('fullName')).to.equal('Hans Muster')
  })

  it('computes a long name with full name', function() {
    let model = this.subject({ username: 'hansm', firstName: 'Hans', lastName: 'Muster' })

    expect(model).to.be.ok

    expect(model.get('longName')).to.equal('Hans Muster (hansm)')
  })

  it('computes a long name without full name', function() {
    let model = this.subject({ username: 'hansm' })

    expect(model).to.be.ok

    expect(model.get('longName')).to.equal('hansm')
  })
})
<commit_msg>Fixed user unit test<commit_after>import { describe, it }   from 'mocha'
import { setupModelTest } from 'ember-mocha'
import { expect }         from 'chai'

describe('Unit | Model | user', function() {
  setupModelTest('user', {
    needs: [
      'model:employment',
      'model:absence-credit'
    ]
  })

  it('exists', function() {
    let model = this.subject()

    expect(model).to.be.ok
  })

  it('computes a full name', function() {
    let model = this.subject({ firstName: 'Hans', lastName: 'Muster' })

    expect(model).to.be.ok

    expect(model.get('fullName')).to.equal('Hans Muster')
  })

  it('computes a long name with full name', function() {
    let model = this.subject({ username: 'hansm', firstName: 'Hans', lastName: 'Muster' })

    expect(model).to.be.ok

    expect(model.get('longName')).to.equal('Hans Muster (hansm)')
  })

  it('computes a long name without full name', function() {
    let model = this.subject({ username: 'hansm' })

    expect(model).to.be.ok

    expect(model.get('longName')).to.equal('hansm')
  })
})
<|endoftext|>


<commit_before>const got = require('got')

module.exports = middleware

async function middleware (ctx, next) {
  if (!ctx.accepts('html')) return next()
  const ip = await resolveIP(ctx.ip)
  const url = `http://api.ipstack.com/${ip}?access_key=${process.env.IPSTACK_KEY}`
  const { body } = await got(url, { json: true })
  ctx.state.geoip = body.success ? body : {}
  return next()
}

async function resolveIP (ip) {
  ip = ip.replace(/^::ffff:/, '')
  if (ip === '::1' || ip.startsWith('172')) {
    // local develoment
    try {
      // try and resolve actual IP
      const { body } = await got('https://ifconfig.me/ip')
      return body
    } catch (err) {
      // fallback to some arbitary IP
      return '185.122.168.227'
    }
  }
  // remove IPv4 prefix
  return ip
}
<commit_msg>Fix geoip false negative response handling<commit_after>const got = require('got')

module.exports = middleware

async function middleware (ctx, next) {
  if (!ctx.accepts('html')) return next()
  const ip = await resolveIP(ctx.ip)
  const url = `http://api.ipstack.com/${ip}?access_key=${process.env.IPSTACK_KEY}`
  const { body } = await got(url, { json: true })
  ctx.state.geoip = body.error ? {} : body
  return next()
}

async function resolveIP (ip) {
  ip = ip.replace(/^::ffff:/, '')
  if (ip === '::1' || ip.startsWith('172')) {
    // local develoment
    try {
      // try and resolve actual IP
      const { body } = await got('https://ifconfig.me/ip')
      return body
    } catch (err) {
      // fallback to some arbitary IP
      return '185.122.168.227'
    }
  }
  // remove IPv4 prefix
  return ip
}
<|endoftext|>


<commit_before>'use strict';

/*
* When adding modules to the namespace, ensure that they are added in alphabetical order according to module name.
*/

// MODULES //

var setReadOnly = require( '@stdlib/utils/define-read-only-property' );

// MAIN //

/**
* Top-level namespace.
*
* @namespace chisquare
*/
var chisquare = {};

/**
* @name cdf
* @memberof chisquare
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/base/dist/chisquare/cdf}
*/
setReadOnly( chisquare, 'cdf', require( '@stdlib/math/base/dist/chisquare/cdf' ) );

/**
* @name mgf
* @memberof chisquare
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/base/dist/chisquare/mgf}
*/
setReadOnly( chisquare, 'mgf', require( '@stdlib/math/base/dist/chisquare/mgf' ) );

/**
* @name pdf
* @memberof chisquare
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/base/dist/chisquare/pdf}
*/
setReadOnly( chisquare, 'pdf', require( '@stdlib/math/base/dist/chisquare/pdf' ) );

/**
* @name quantile
* @memberof chisquare
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/base/dist/chisquare/quantile}
*/
setReadOnly( chisquare, 'quantile', require( '@stdlib/math/base/dist/chisquare/quantile' ) );

// EXPORTS //

module.exports = chisquare;
<commit_msg>Add modules to chisquare namespace<commit_after>'use strict';

/*
* When adding modules to the namespace, ensure that they are added in alphabetical order according to module name.
*/

// MODULES //

var setReadOnly = require( '@stdlib/utils/define-read-only-property' );

// MAIN //

/**
* Top-level namespace.
*
* @namespace chisquare
*/
var chisquare = {};

/**
* @name cdf
* @memberof chisquare
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/base/dist/chisquare/cdf}
*/
setReadOnly( chisquare, 'cdf', require( '@stdlib/math/base/dist/chisquare/cdf' ) );

/**
* @name entropy
* @memberof chisquare
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/base/dist/chisquare/entropy}
*/
setReadOnly( chisquare, 'entropy', require( '@stdlib/math/base/dist/chisquare/entropy' ) );

/**
* @name kurtosis
* @memberof chisquare
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/base/dist/chisquare/kurtosis}
*/
setReadOnly( chisquare, 'kurtosis', require( '@stdlib/math/base/dist/chisquare/kurtosis' ) );

/**
* @name mean
* @memberof chisquare
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/base/dist/chisquare/mean}
*/
setReadOnly( chisquare, 'mean', require( '@stdlib/math/base/dist/chisquare/mean' ) );

/**
* @name mgf
* @memberof chisquare
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/base/dist/chisquare/mgf}
*/
setReadOnly( chisquare, 'mgf', require( '@stdlib/math/base/dist/chisquare/mgf' ) );

/**
* @name mode
* @memberof chisquare
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/base/dist/chisquare/mode}
*/
setReadOnly( chisquare, 'mode', require( '@stdlib/math/base/dist/chisquare/mode' ) );

/**
* @name pdf
* @memberof chisquare
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/base/dist/chisquare/pdf}
*/
setReadOnly( chisquare, 'pdf', require( '@stdlib/math/base/dist/chisquare/pdf' ) );

/**
* @name quantile
* @memberof chisquare
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/base/dist/chisquare/quantile}
*/
setReadOnly( chisquare, 'quantile', require( '@stdlib/math/base/dist/chisquare/quantile' ) );

/**
* @name skewness
* @memberof chisquare
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/base/dist/chisquare/skewness}
*/
setReadOnly( chisquare, 'skewness', require( '@stdlib/math/base/dist/chisquare/skewness' ) );

/**
* @name variance
* @memberof chisquare
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/base/dist/chisquare/variance}
*/
setReadOnly( chisquare, 'variance', require( '@stdlib/math/base/dist/chisquare/variance' ) );

// EXPORTS //

module.exports = chisquare;
<|endoftext|>


<commit_before>(function() {
  angular.module('meganote.notes', ['ui.router'])
  .config(notesConfig)
  .controller('NotesController', NotesController);

  notesConfig.$inject = ['$stateProvider'];
  function notesConfig($stateProvider) {
    $stateProvider

    .state('notes', {
      url: '/notes',
      templateUrl: 'notes/notes.html',
      controller: 'NotesController'
    })

    .state('notes.form', {
      url: '/:noteId',
      templateUrl: 'notes/notes-form.html'
    });
  }

  NotesController.$inject = ['$state', '$scope', 'NotesService']
  function NotesController($state, $scope, NotesService) {
    $state.go('notes.form');

    NotesService.getNotes()
      .then(function() {
        $scope.notes = NotesService.notes;
      });

    $scope.note = {};
    // $scope.message = "seperate controller";
    $scope.saveNote = function() {
      NotesService.create($scope.note)
      $scope.note = { title: '', body_html: ''};
    }
    $scope.editNote = function (note) {
            // $scope.editing = true;
      $scope.note = note;
    }
    $scope.removeNote = function(index) {
      $scope.notes.splice(index, 1);
    }
  };
})();
<commit_msg>Allows user to clear form.<commit_after>(function() {
  angular.module('meganote.notes', ['ui.router'])
  .config(notesConfig)
  .controller('NotesController', NotesController);

  notesConfig.$inject = ['$stateProvider'];
  function notesConfig($stateProvider) {
    $stateProvider

    .state('notes', {
      url: '/notes',
      templateUrl: 'notes/notes.html',
      controller: 'NotesController'
    })

    .state('notes.form', {
      url: '/:noteId',
      templateUrl: 'notes/notes-form.html'
    });
  }

  NotesController.$inject = ['$state', '$scope', 'NotesService']
  function NotesController($state, $scope, NotesService) {
    $state.go('notes.form');

    NotesService.getNotes()
      .then(function() {
        $scope.notes = NotesService.notes;
      });

    $scope.clearForm = function() {
      $scope.note = { title: '', body_html: ''};
    };

    $scope.note = {};
    // $scope.message = "seperate controller";
    $scope.saveNote = function() {
      NotesService.create($scope.note)
      $scope.clearForm();
    }
    $scope.editNote = function (note) {
            // $scope.editing = true;
      $scope.note = note;
    }
    $scope.removeNote = function(index) {
      $scope.notes.splice(index, 1);
    }

  };
})();
<|endoftext|>


<commit_before>/* eslint-disable import/no-dynamic-require, react/no-danger, import/no-mutable-exports */
import webpack from 'webpack'
import path from 'path'
import formatWebpackMessages from 'react-dev-utils/formatWebpackMessages'
import chalk from 'chalk'
import WebpackDevServer from 'webpack-dev-server'
import io from 'socket.io'
import fs from 'fs-extra'
// import errorOverlayMiddleware from 'react-dev-utils/errorOverlayMiddleware'
//
import { getStagedRules } from './rules'
import { findAvailablePort, time, timeEnd } from '../../utils'
import { cleanPath, getPluginHooks } from '../../utils/shared'
import { prepareRoutes } from '..'

let resolvedReloadRoutes
let reloadWebpackRoutes

let devServer

const reloadRoutes = (...args) => {
  if (!resolvedReloadRoutes) {
    // Not ready yet, so just wait
    return
  }
  resolvedReloadRoutes(...args)
}

export { reloadRoutes }

// Builds a compiler using a stage preset, then allows extension via
// webpackConfigurator
export function webpackConfig({ config, stage }) {
  let webpackConfig
  if (stage === 'dev') {
    webpackConfig = require('./webpack.config.dev').default({ config })
  } else if (stage === 'prod') {
    webpackConfig = require('./webpack.config.prod').default({
      config,
    })
  } else if (stage === 'node') {
    webpackConfig = require('./webpack.config.prod').default({
      config,
      isNode: true,
    })
  } else {
    throw new Error('A stage is required when building a compiler.')
  }

  const defaultLoaders = getStagedRules({ config, stage })

  const transformers = getPluginHooks(config.plugins, 'webpack').reduce(
    (all, curr) => {
      if (Array.isArray(curr)) {
        return [...all, ...curr]
      }
      return [...all, curr]
    },
    []
  )

  transformers.forEach(transformer => {
    const modifiedConfig = transformer(webpackConfig, {
      stage,
      defaultLoaders,
    })
    if (modifiedConfig) {
      webpackConfig = modifiedConfig
    }
  })
  return webpackConfig
}

export async function buildCompiler({ config, stage }) {
  return webpack(webpackConfig({ config, stage }))
}

// Starts the development server
export async function startDevServer({ config }) {
  if (devServer) {
    return devServer
  }

  const devCompiler = await buildCompiler({ config, stage: 'dev' })

  // Default to localhost:3000, or use a custom combo if defined in static.config.js
  // or environment variables
  const intendedPort =
    (config.devServer && config.devServer.port) || process.env.PORT || 3000
  const port = await findAvailablePort(Number(intendedPort))
  // Find an available port for messages, as long as it's not the devServer port
  const messagePort = await findAvailablePort(4000, [port])
  if (intendedPort !== port) {
    time(
      chalk.red(
        `=> Warning! Port ${intendedPort} is not available. Using port ${chalk.green(
          intendedPort
        )} instead!`
      )
    )
  }
  const host =
    (config.devServer && config.devServer.host) ||
    process.env.HOST ||
    'http://localhost'

  const devServerConfig = {
    hot: true,
    disableHostCheck: true,
    contentBase: [config.paths.PUBLIC, config.paths.DIST],
    publicPath: '/',
    historyApiFallback: true,
    compress: false,
    quiet: true,
    ...config.devServer,
    watchOptions: {
      ignored: 'node_modules',
      // ignored: new RegExp(`(node_modules|${config.paths.PAGES})`),
      ...(config.devServer ? config.devServer.watchOptions || {} : {}),
    },
    before: app => {
      // Serve the site data
      app.get('/__react-static__/getMessagePort', async (req, res) => {
        res.json({
          port: messagePort,
        })
      })

      app.get('/__react-static__/siteData', async (req, res, next) => {
        try {
          const siteData = await config.getSiteData({ dev: true })
          res.json(siteData)
        } catch (err) {
          res.status(500)
          res.json(err)
          next(err)
        }
      })

      // Since routes may change during dev, this function can rebuild all of the config
      // routes. It also references the original config when possible, to make sure it
      // uses any up to date getData callback generated from new or replacement routes.
      reloadWebpackRoutes = config => {
        // Serve each routes data
        config.routes.forEach(({ path: routePath }) => {
          app.get(
            `/__react-static__/routeInfo/${encodeURI(
              routePath === '/' ? '' : routePath
            )}`,
            async (req, res, next) => {
              // Make sure we have the most up to date route from the config, not
              // an out of dat object.
              const route = config.routes.find(d => d.path === routePath)
              try {
                if (!route) {
                  throw new Error('Route could not be found!')
                }
                const allProps = route.getData
                  ? await route.getData({ route, dev: true })
                  : {}
                res.json({
                  ...route,
                  allProps,
                })
              } catch (err) {
                res.status(500)
                next(err)
              }
            }
          )
        })
      }

      reloadWebpackRoutes(config)

      if (config.devServer && config.devServer.before) {
        config.devServer.before(app)
      }
    },
    port,
    host,
  }

  let first = true
  console.log('=> Building App Bundle...')
  time(chalk.green('=> [\u2713] Build Complete'))

  devCompiler.hooks.invalid.tap(
    {
      name: 'React-Static',
    },
    file => {
      console.log('=> File changed:', file.replace(config.paths.ROOT, ''))
      console.log('=> Updating build...')
      time(chalk.green('=> [\u2713] Build Updated'))
    }
  )

  devCompiler.hooks.done.tap(
    {
      name: 'React-Static',
    },
    stats => {
      const messages = formatWebpackMessages(stats.toJson({}, true))
      const isSuccessful = !messages.errors.length && !messages.warnings.length

      if (isSuccessful) {
        if (first) {
          timeEnd(chalk.green('=> [\u2713] Build Complete'))
          console.log(
            chalk.green('=> [\u2713] App serving at'),
            `${host}:${port}`
          )
        } else {
          timeEnd(chalk.green('=> [\u2713] Build Updated'))
        }
        if (first && config.onStart) {
          config.onStart({ devServerConfig })
        }
      }

      first = false

      if (messages.errors.length) {
        console.log(chalk.red('Failed to build! Fix any errors and try again!'))
        messages.errors.forEach(message => {
          console.log(message)
          console.log()
        })
      }

      if (messages.warnings.length) {
        console.log(chalk.yellow('Build complete with warnings.'))
        console.log()
        messages.warnings.forEach(message => {
          console.log(message)
          console.log()
        })
      }
    }
  )

  // Start the webpack dev server
  devServer = new WebpackDevServer(devCompiler, devServerConfig)

  // Start the messages socket
  const socket = io()
  socket.listen(messagePort)

  resolvedReloadRoutes = async paths => {
    await prepareRoutes(
      { config, opts: { dev: true }, silent: true },
      async config => {
        if (!paths) {
          paths = config.routes.map(route => route.path)
        }
        paths = paths.map(cleanPath)
        reloadWebpackRoutes(config)
        socket.emit('message', { type: 'reloadRoutes', paths })
      }
    )
  }

  await new Promise((resolve, reject) => {
    devServer.listen(port, null, err => {
      if (err) {
        return reject(err)
      }
      resolve()
    })
  })

  return devServer
}

export async function buildProductionBundles({ config }) {
  return new Promise((resolve, reject) => {
    webpack([
      webpackConfig({ config, stage: 'prod' }),
      webpackConfig({ config, stage: 'node' }),
    ]).run((err, stats) => {
      if (err) {
        console.log(chalk.red(err.stack || err))
        if (err.details) {
          console.log(chalk.red(err.details))
        }
        return reject(err)
      }

      stats.toJson('verbose')

      const [prodStats, nodeStats] = stats.stats

      checkBuildStats('prod', prodStats)
      checkBuildStats('node', nodeStats)

      function checkBuildStats(stage, stageStats) {
        const buildErrors = stageStats.hasErrors()
        const buildWarnings = stageStats.hasWarnings()

        if (buildErrors || buildWarnings) {
          console.log(
            stageStats.toString({
              context: config.context,
              performance: false,
              hash: false,
              timings: true,
              entrypoints: false,
              chunkOrigins: false,
              chunkModules: false,
              colors: true,
            })
          )
          if (buildErrors) {
            console.log(
              chalk.red.bold(`
                => There were ERRORS during the ${stage} build stage! :(
                => Fix them and try again!
              `)
            )
          } else if (buildWarnings) {
            console.log(
              chalk.yellow(`
=> There were WARNINGS during the ${stage} build stage. Your site will still function, but you may achieve better performance by addressing the warnings above.
`)
            )
          }
        }
      }

      const prodStatsJson = prodStats.toJson()

      fs.outputFileSync(
        path.join(config.paths.TEMP, 'client-stats.json'),
        JSON.stringify(prodStatsJson, null, 2)
      )

      fs.outputFileSync(
        path.join(config.paths.TEMP, 'bundle-environment.json'),
        JSON.stringify(process.env, null, 2)
      )

      resolve(prodStatsJson)
    })
  })
}
<commit_msg>Make sure to run the config.webpack hook (#771)<commit_after>/* eslint-disable import/no-dynamic-require, react/no-danger, import/no-mutable-exports */
import webpack from 'webpack'
import path from 'path'
import formatWebpackMessages from 'react-dev-utils/formatWebpackMessages'
import chalk from 'chalk'
import WebpackDevServer from 'webpack-dev-server'
import io from 'socket.io'
import fs from 'fs-extra'
// import errorOverlayMiddleware from 'react-dev-utils/errorOverlayMiddleware'
//
import { getStagedRules } from './rules'
import { findAvailablePort, time, timeEnd } from '../../utils'
import { cleanPath, getPluginHooks } from '../../utils/shared'
import { prepareRoutes } from '..'

let resolvedReloadRoutes
let reloadWebpackRoutes

let devServer

const reloadRoutes = (...args) => {
  if (!resolvedReloadRoutes) {
    // Not ready yet, so just wait
    return
  }
  resolvedReloadRoutes(...args)
}

export { reloadRoutes }

// Builds a compiler using a stage preset, then allows extension via
// webpackConfigurator
export function webpackConfig({ config, stage }) {
  let webpackConfig
  if (stage === 'dev') {
    webpackConfig = require('./webpack.config.dev').default({ config })
  } else if (stage === 'prod') {
    webpackConfig = require('./webpack.config.prod').default({
      config,
    })
  } else if (stage === 'node') {
    webpackConfig = require('./webpack.config.prod').default({
      config,
      isNode: true,
    })
  } else {
    throw new Error('A stage is required when building a compiler.')
  }

  const defaultLoaders = getStagedRules({ config, stage })

  const transformers = getPluginHooks(config.plugins, 'webpack').concat(config.webpack || []).reduce(
    (all, curr) => {
      if (Array.isArray(curr)) {
        return [...all, ...curr]
      }
      return [...all, curr]
    },
    []
  );

  transformers.forEach(transformer => {
    if (typeof transformer === 'function') {
      const modifiedConfig = transformer(webpackConfig, {
        stage,
        defaultLoaders,
      })

      if (modifiedConfig) {
        webpackConfig = modifiedConfig
      }
    }
  })

  return webpackConfig
}

export async function buildCompiler({ config, stage }) {
  return webpack(webpackConfig({ config, stage }))
}

// Starts the development server
export async function startDevServer({ config }) {
  if (devServer) {
    return devServer
  }

  const devCompiler = await buildCompiler({ config, stage: 'dev' })

  // Default to localhost:3000, or use a custom combo if defined in static.config.js
  // or environment variables
  const intendedPort =
    (config.devServer && config.devServer.port) || process.env.PORT || 3000
  const port = await findAvailablePort(Number(intendedPort))
  // Find an available port for messages, as long as it's not the devServer port
  const messagePort = await findAvailablePort(4000, [port])
  if (intendedPort !== port) {
    time(
      chalk.red(
        `=> Warning! Port ${intendedPort} is not available. Using port ${chalk.green(
          intendedPort
        )} instead!`
      )
    )
  }
  const host =
    (config.devServer && config.devServer.host) ||
    process.env.HOST ||
    'http://localhost'

  const devServerConfig = {
    hot: true,
    disableHostCheck: true,
    contentBase: [config.paths.PUBLIC, config.paths.DIST],
    publicPath: '/',
    historyApiFallback: true,
    compress: false,
    quiet: true,
    ...config.devServer,
    watchOptions: {
      ignored: 'node_modules',
      // ignored: new RegExp(`(node_modules|${config.paths.PAGES})`),
      ...(config.devServer ? config.devServer.watchOptions || {} : {}),
    },
    before: app => {
      // Serve the site data
      app.get('/__react-static__/getMessagePort', async (req, res) => {
        res.json({
          port: messagePort,
        })
      })

      app.get('/__react-static__/siteData', async (req, res, next) => {
        try {
          const siteData = await config.getSiteData({ dev: true })
          res.json(siteData)
        } catch (err) {
          res.status(500)
          res.json(err)
          next(err)
        }
      })

      // Since routes may change during dev, this function can rebuild all of the config
      // routes. It also references the original config when possible, to make sure it
      // uses any up to date getData callback generated from new or replacement routes.
      reloadWebpackRoutes = config => {
        // Serve each routes data
        config.routes.forEach(({ path: routePath }) => {
          app.get(
            `/__react-static__/routeInfo/${encodeURI(
              routePath === '/' ? '' : routePath
            )}`,
            async (req, res, next) => {
              // Make sure we have the most up to date route from the config, not
              // an out of dat object.
              const route = config.routes.find(d => d.path === routePath)
              try {
                if (!route) {
                  throw new Error('Route could not be found!')
                }
                const allProps = route.getData
                  ? await route.getData({ route, dev: true })
                  : {}
                res.json({
                  ...route,
                  allProps,
                })
              } catch (err) {
                res.status(500)
                next(err)
              }
            }
          )
        })
      }

      reloadWebpackRoutes(config)

      if (config.devServer && config.devServer.before) {
        config.devServer.before(app)
      }
    },
    port,
    host,
  }

  let first = true
  console.log('=> Building App Bundle...')
  time(chalk.green('=> [\u2713] Build Complete'))

  devCompiler.hooks.invalid.tap(
    {
      name: 'React-Static',
    },
    file => {
      console.log('=> File changed:', file.replace(config.paths.ROOT, ''))
      console.log('=> Updating build...')
      time(chalk.green('=> [\u2713] Build Updated'))
    }
  )

  devCompiler.hooks.done.tap(
    {
      name: 'React-Static',
    },
    stats => {
      const messages = formatWebpackMessages(stats.toJson({}, true))
      const isSuccessful = !messages.errors.length && !messages.warnings.length

      if (isSuccessful) {
        if (first) {
          timeEnd(chalk.green('=> [\u2713] Build Complete'))
          console.log(
            chalk.green('=> [\u2713] App serving at'),
            `${host}:${port}`
          )
        } else {
          timeEnd(chalk.green('=> [\u2713] Build Updated'))
        }
        if (first && config.onStart) {
          config.onStart({ devServerConfig })
        }
      }

      first = false

      if (messages.errors.length) {
        console.log(chalk.red('Failed to build! Fix any errors and try again!'))
        messages.errors.forEach(message => {
          console.log(message)
          console.log()
        })
      }

      if (messages.warnings.length) {
        console.log(chalk.yellow('Build complete with warnings.'))
        console.log()
        messages.warnings.forEach(message => {
          console.log(message)
          console.log()
        })
      }
    }
  )

  // Start the webpack dev server
  devServer = new WebpackDevServer(devCompiler, devServerConfig)

  // Start the messages socket
  const socket = io()
  socket.listen(messagePort)

  resolvedReloadRoutes = async paths => {
    await prepareRoutes(
      { config, opts: { dev: true }, silent: true },
      async config => {
        if (!paths) {
          paths = config.routes.map(route => route.path)
        }
        paths = paths.map(cleanPath)
        reloadWebpackRoutes(config)
        socket.emit('message', { type: 'reloadRoutes', paths })
      }
    )
  }

  await new Promise((resolve, reject) => {
    devServer.listen(port, null, err => {
      if (err) {
        return reject(err)
      }
      resolve()
    })
  })

  return devServer
}

export async function buildProductionBundles({ config }) {
  return new Promise((resolve, reject) => {
    webpack([
      webpackConfig({ config, stage: 'prod' }),
      webpackConfig({ config, stage: 'node' }),
    ]).run((err, stats) => {
      if (err) {
        console.log(chalk.red(err.stack || err))
        if (err.details) {
          console.log(chalk.red(err.details))
        }
        return reject(err)
      }

      stats.toJson('verbose')

      const [prodStats, nodeStats] = stats.stats

      checkBuildStats('prod', prodStats)
      checkBuildStats('node', nodeStats)

      function checkBuildStats(stage, stageStats) {
        const buildErrors = stageStats.hasErrors()
        const buildWarnings = stageStats.hasWarnings()

        if (buildErrors || buildWarnings) {
          console.log(
            stageStats.toString({
              context: config.context,
              performance: false,
              hash: false,
              timings: true,
              entrypoints: false,
              chunkOrigins: false,
              chunkModules: false,
              colors: true,
            })
          )
          if (buildErrors) {
            console.log(
              chalk.red.bold(`
                => There were ERRORS during the ${stage} build stage! :(
                => Fix them and try again!
              `)
            )
          } else if (buildWarnings) {
            console.log(
              chalk.yellow(`
=> There were WARNINGS during the ${stage} build stage. Your site will still function, but you may achieve better performance by addressing the warnings above.
`)
            )
          }
        }
      }

      const prodStatsJson = prodStats.toJson()

      fs.outputFileSync(
        path.join(config.paths.TEMP, 'client-stats.json'),
        JSON.stringify(prodStatsJson, null, 2)
      )

      fs.outputFileSync(
        path.join(config.paths.TEMP, 'bundle-environment.json'),
        JSON.stringify(process.env, null, 2)
      )

      resolve(prodStatsJson)
    })
  })
}
<|endoftext|>


<commit_before>'use strict';

const { isEqual, uniq } = require('lodash');

const { assignArray } = require('../../../../../utilities');
const { ACTIONS } = require('../../../../../constants');
const { isTopLevelAction, getActionConstant } = require('../utilities');

const resolveRead = async function ({
  actions,
  nextLayer,
  mInput,
  responses,
}) {
  // Siblings can be run in parallel
  const responsesPromises = actions
    .map(({ parentAction, childActions }) => resolveSingleRead({
      action: parentAction,
      childActions,
      actions,
      nextLayer,
      mInput,
      responses,
    }));
  const responsesA = await Promise.all(responsesPromises);
  const responsesB = responsesA.reduce(assignArray, []);

  const responsesC = responses || [];
  return [...responsesC, ...responsesB];
};

const resolveSingleRead = async function ({
  action,
  action: {
    actionPath,
    actionConstant: { multiple },
    modelName,
    args,
    select,
    idCheck = true,
    internal = false,
  },
  childActions = [],
  nextLayer,
  mInput,
  responses,
}) {
  const {
    isTopLevel,
    actionConstant,
    parentResponses,
    actionName,
    nestedParentIds,
    parentIds,
  } = getActionInput({ action, responses });

  const argsA = getNestedArg({ args, actionConstant, parentIds, isTopLevel });
  const argsB = { ...argsA, idCheck, internal };

  // Parent actions must be run first
  const response = await fireReadAction({
    mInput,
    nextLayer,
    actionConstant,
    actionPath,
    modelName,
    args: argsB,
  });

  const responsesA = getResponses({
    actionName,
    multiple,
    isTopLevel,
    parentResponses,
    nestedParentIds,
    response,
    select,
    modelName,
  });

  // Child actions must start after their parent ends
  const childResponses = await resolveRead({
    actions: childActions,
    nextLayer,
    mInput,
    responses: responsesA,
  });

  return childResponses;
};

const getActionInput = function ({
  action: {
    actionPath,
    actionConstant: { type: actionType },
  },
  responses,
}) {
  const isTopLevel = isTopLevelAction({ actionPath }) ||
    // When firing read actions in parallel
    responses === undefined;
  const actionConstant = getActionConstant({ actionType, isArray: true });

  const parentPath = actionPath.slice(0, -1);
  const responsesA = responses || [];
  const parentResponses = responsesA.filter(({ path }) => {
    const pathA = path.filter(index => typeof index !== 'number');
    return isEqual(pathA, parentPath);
  });

  const actionName = actionPath[actionPath.length - 1];
  const nestedParentIds = parentResponses.map(({ model }) => model[actionName]);
  const parentIds = nestedParentIds
    .reduce(assignArray, [])
    .filter(ids => ids !== undefined);
  const parentIdsA = uniq(parentIds);

  return {
    isTopLevel,
    actionConstant,
    parentResponses,
    actionName,
    nestedParentIds,
    parentIds: parentIdsA,
  };
};

// Make nested models filtered by their parent model
// E.g. if a model findParent() returns { child: 1 },
// then a nested query findChild() will be filtered by `id: 1`
// If the parent returns nothing|null, the nested query won't be performed
// and null will be returned
const getNestedArg = function ({
  args,
  actionConstant,
  parentIds,
  isTopLevel,
}) {
  const shouldNestArg = !isTopLevel &&
    nestedActionTypes.includes(actionConstant.type);
  if (!shouldNestArg) { return args; }

  const id = parentIds == null ? [] : parentIds;
  return { ...args, filter: { id } };
};

const nestedActionTypes = ['find', 'delete', 'update'];

const fireReadAction = async function ({
  mInput,
  nextLayer,
  actionConstant,
  actionPath,
  modelName,
  args,
  args: { filter: { id } = {} },
}) {
  const { command } = ACTIONS.find(action => actionConstant === action);

  // When parent value is not defined, directly returns empty value
  if (Array.isArray(id) && id.length === 0) { return []; }

  const mInputA = {
    ...mInput,
    action: actionConstant,
    actionPath: actionPath.join('.'),
    modelName,
    args,
    command,
  };

  const { response: { data: response } } = await nextLayer(mInputA);

  return response;
};

const getResponses = function ({
  actionName,
  multiple,
  isTopLevel,
  parentResponses,
  nestedParentIds,
  response,
  select,
  modelName,
}) {
  if (isTopLevel) {
    return response.map((model, index) =>
      getResponse({ model, index, actionName, multiple, select, modelName })
    );
  }

  return nestedParentIds
    .map((ids, index) => {
      const { path } = parentResponses[index];
      return getEachResponses({
        ids,
        actionName,
        select,
        path,
        response,
        modelName,
      });
    })
    .reduce(assignArray, []);
};

const getEachResponses = function ({
  ids,
  actionName,
  select,
  path,
  response,
  modelName,
}) {
  const multiple = Array.isArray(ids);
  return response
    // Make sure response's sorting is kept
    .filter(({ id }) => (multiple ? ids.includes(id) : ids === id))
    .map((model, ind) => getResponse({
      model,
      index: ind,
      path,
      actionName,
      multiple,
      select,
      modelName,
    }));
};

const getResponse = function ({
  model,
  index,
  path = [],
  actionName,
  multiple,
  select,
  modelName,
}) {
  const pathA = multiple
    ? [...path, actionName, index]
    : [...path, actionName];
  return { path: pathA, model, modelName, select };
};

module.exports = {
  resolveRead,
};
<commit_msg>Small refactoring<commit_after>'use strict';

const { isEqual, uniq } = require('lodash');

const { assignArray } = require('../../../../../utilities');
const { ACTIONS } = require('../../../../../constants');
const { isTopLevelAction, getActionConstant } = require('../utilities');

const resolveRead = async function ({
  actions,
  nextLayer,
  mInput,
  responses,
}) {
  // Siblings can be run in parallel
  const responsesPromises = actions.map(({ parentAction, childActions }) =>
    resolveSingleRead({
      action: parentAction,
      childActions,
      actions,
      nextLayer,
      mInput,
      responses,
    })
  );
  const responsesA = await Promise.all(responsesPromises);
  const responsesB = responsesA.reduce(assignArray, []);

  const responsesC = responses || [];
  return [...responsesC, ...responsesB];
};

const resolveSingleRead = async function ({
  action,
  action: {
    actionPath,
    actionConstant: { multiple },
    modelName,
    args,
    select,
    idCheck = true,
    internal = false,
  },
  childActions = [],
  nextLayer,
  mInput,
  responses,
}) {
  const {
    isTopLevel,
    actionConstant,
    parentResponses,
    actionName,
    nestedParentIds,
    parentIds,
  } = getActionInput({ action, responses });

  const argsA = getNestedArg({ args, actionConstant, parentIds, isTopLevel });
  const argsB = { ...argsA, idCheck, internal };

  // Parent actions must be run first
  const response = await fireReadAction({
    mInput,
    nextLayer,
    actionConstant,
    actionPath,
    modelName,
    args: argsB,
  });

  const responsesA = getResponses({
    actionName,
    multiple,
    isTopLevel,
    parentResponses,
    nestedParentIds,
    response,
    select,
    modelName,
  });

  // Child actions must start after their parent ends
  const childResponses = await resolveRead({
    actions: childActions,
    nextLayer,
    mInput,
    responses: responsesA,
  });

  return childResponses;
};

const getActionInput = function ({
  action: {
    actionPath,
    actionConstant: { type: actionType },
  },
  responses,
}) {
  const isTopLevel = isTopLevelAction({ actionPath }) ||
    // When firing read actions in parallel
    responses === undefined;
  const actionConstant = getActionConstant({ actionType, isArray: true });

  const parentPath = actionPath.slice(0, -1);
  const responsesA = responses || [];
  const parentResponses = responsesA.filter(({ path }) => {
    const pathA = path.filter(index => typeof index !== 'number');
    return isEqual(pathA, parentPath);
  });

  const actionName = actionPath[actionPath.length - 1];
  const nestedParentIds = parentResponses.map(({ model }) => model[actionName]);
  const parentIds = nestedParentIds
    .reduce(assignArray, [])
    .filter(ids => ids !== undefined);
  const parentIdsA = uniq(parentIds);

  return {
    isTopLevel,
    actionConstant,
    parentResponses,
    actionName,
    nestedParentIds,
    parentIds: parentIdsA,
  };
};

// Make nested models filtered by their parent model
// E.g. if a model findParent() returns { child: 1 },
// then a nested query findChild() will be filtered by `id: 1`
// If the parent returns nothing|null, the nested query won't be performed
// and null will be returned
const getNestedArg = function ({
  args,
  actionConstant,
  parentIds,
  isTopLevel,
}) {
  const shouldNestArg = !isTopLevel &&
    nestedActionTypes.includes(actionConstant.type);
  if (!shouldNestArg) { return args; }

  const id = parentIds == null ? [] : parentIds;
  return { ...args, filter: { id } };
};

const nestedActionTypes = ['find', 'delete', 'update'];

const fireReadAction = async function ({
  mInput,
  nextLayer,
  actionConstant,
  actionPath,
  modelName,
  args,
  args: { filter: { id } = {} },
}) {
  const { command } = ACTIONS.find(action => actionConstant === action);

  // When parent value is not defined, directly returns empty value
  if (Array.isArray(id) && id.length === 0) { return []; }

  const mInputA = {
    ...mInput,
    action: actionConstant,
    actionPath: actionPath.join('.'),
    modelName,
    args,
    command,
  };

  const { response: { data: response } } = await nextLayer(mInputA);

  return response;
};

const getResponses = function ({
  actionName,
  multiple,
  isTopLevel,
  parentResponses,
  nestedParentIds,
  response,
  select,
  modelName,
}) {
  if (isTopLevel) {
    return response.map((model, index) =>
      getResponse({ model, index, actionName, multiple, select, modelName })
    );
  }

  return nestedParentIds
    .map((ids, index) => {
      const { path } = parentResponses[index];
      return getEachResponses({
        ids,
        actionName,
        select,
        path,
        response,
        modelName,
      });
    })
    .reduce(assignArray, []);
};

const getEachResponses = function ({
  ids,
  actionName,
  select,
  path,
  response,
  modelName,
}) {
  const multiple = Array.isArray(ids);
  return response
    // Make sure response's sorting is kept
    .filter(({ id }) => (multiple ? ids.includes(id) : ids === id))
    .map((model, ind) => getResponse({
      model,
      index: ind,
      path,
      actionName,
      multiple,
      select,
      modelName,
    }));
};

const getResponse = function ({
  model,
  index,
  path = [],
  actionName,
  multiple,
  select,
  modelName,
}) {
  const pathA = multiple
    ? [...path, actionName, index]
    : [...path, actionName];
  return { path: pathA, model, modelName, select };
};

module.exports = {
  resolveRead,
};
<|endoftext|>


<commit_before>const phantomjs = require('phantomjs-prebuilt');
const babel = require('babel-register');
const { SpecReporter } = require('jasmine-spec-reporter');

const { TEST_PORT } = require('../constants');

exports.config = {
  specs: [
    'src/**/*.e2e-spec.js'
  ],
  exclude: [],
  capabilities: {
    'browserName': 'phantomjs',
    'phantomjs.binary.path': phantomjs.path,
    'phantomjs.ghostdriver.cli.args': ['--loglevel=DEBUG']
  },
  baseUrl: `http://localhost:${TEST_PORT}/`,
  onPrepare() {
    babel();
    jasmine.getEnv().addReporter(new SpecReporter({ spec: { displayStacktrace: true } }));
    global.webdriver = browser.driver;
    webdriver.ignoreSynchronization = true;
    webdriver.manage().window().setSize(1280, 1024);
    global.browserGet = (url = '/') => webdriver.get(`http://localhost:${TEST_PORT}${url}`);
  },
  framework: 'jasmine',
  jasmineNodeOpts: {
    isVerbose: false,
    showColors: true,
    includeStackTrace: false
  }
};
<commit_msg>577th Commit<commit_after>const phantomjs = require('phantomjs-prebuilt');
const babel = require('babel-register');
const { SpecReporter } = require('jasmine-spec-reporter');

const { TEST_PORT } = require('../constants');

exports.config = {
  specs: [
    'src/**/*.e2e-spec.js'
  ],
  exclude: [],
  capabilities: {
    'browserName': 'phantomjs',
    'phantomjs.binary.path': phantomjs.path,
    'phantomjs.ghostdriver.cli.args': ['--loglevel=DEBUG']
  },
  baseUrl: `http://localhost:${TEST_PORT}/`,
  onPrepare() {
    babel();
    jasmine.getEnv().addReporter(new SpecReporter({ spec: { displayStacktrace: true } }));
    global.webdriver = browser.driver;
    webdriver.ignoreSynchronization = true;
    webdriver.manage().window().setSize(1280, 1024);
    global.browserGet = (url = '/') => webdriver.get(`http://localhost:${TEST_PORT}${url}`);
  },
  framework: 'jasmine',
  jasmineNodeOpts: {
    print() {}
  }
};
<|endoftext|>


<commit_before>/* global describe, it */

var exec = require('child_process').exec,
  expect = require('chai').expect,
  assert = require('assert')

require('chai').should()
require('tap').mochaGlobals()

process.env.NYC_TEST = 'yep'

describe('signal-exit', function () {
  it('receives an exit event when a process exits normally', function (done) {
    exec(process.execPath + ' ./test/fixtures/end-of-execution.js', function (err, stdout, stderr) {
      expect(err).to.equal(null)
      stdout.should.match(/reached end of execution, 0, undefined/)
      done()
    })
  })

  it('receives an exit event when a process is terminated with sigint', function (done) {
    exec(process.execPath + ' ./test/fixtures/sigint.js', function (err, stdout, stderr) {
      console.log(err, stdout, stderr)
      err.signal.should.equal('SIGINT')
      stdout.should.match(/exited with sigint, 130, SIGINT/)
      done()
    })
  })
/*
  it('receives an exit event when a process is terminated with sigterm', function (done) {
    exec(process.execPath + ' ./test/fixtures/sigterm.js', function (err, stdout, stderr) {
      err.signal.should.equal('SIGTERM')
      stdout.should.match(/exited with sigterm, 143, SIGTERM/)
      done()
    })
  })

  it('receives an exit event when process.exit() is called', function (done) {
    exec(process.execPath + ' ./test/fixtures/exit.js', function (err, stdout, stderr) {
      err.code.should.equal(32)
      stdout.should.match(/exited with process\.exit\(\), 32, undefined/)
      done()
    })
  })

  it('does not exit if user handles signal', function (done) {
    exec(process.execPath + ' ./test/fixtures/signal-listener.js', function (err, stdout, stderr) {
      assert.equal(err.code, null)
      assert.equal(err.signal, 'SIGHUP')
      assert.equal(stdout, 'exited calledListener=4, code=129, signal="SIGHUP"\n')
      done()
    })
  })

  it('ensures that if alwaysLast=true, the handler is run last', function (done) {
    exec(process.execPath + ' ./test/fixtures/signal-last.js', function (err, stdout, stderr) {
      assert.equal(err.code, null)
      assert.equal(err.signal, 'SIGHUP')
      stdout.should.match(/first counter=1/)
      stdout.should.match(/last counter=2/)
      done()
    })
  })*/
})
<commit_msg>figuring out travis<commit_after>/* global describe, it */

var exec = require('child_process').exec,
  expect = require('chai').expect,
  // assert = require('assert')

require('chai').should()
require('tap').mochaGlobals()

process.env.NYC_TEST = 'yep'

describe('signal-exit', function () {
  it('receives an exit event when a process exits normally', function (done) {
    exec(process.execPath + ' ./test/fixtures/end-of-execution.js', function (err, stdout, stderr) {
      expect(err).to.equal(null)
      stdout.should.match(/reached end of execution, 0, undefined/)
      done()
    })
  })

  it('receives an exit event when a process is terminated with sigint', function (done) {
    exec(process.execPath + ' ./test/fixtures/sigint.js', function (err, stdout, stderr) {
      console.log(err, stdout, stderr)
      err.signal.should.equal('SIGINT')
      stdout.should.match(/exited with sigint, 130, SIGINT/)
      done()
    })
  })
/*
  it('receives an exit event when a process is terminated with sigterm', function (done) {
    exec(process.execPath + ' ./test/fixtures/sigterm.js', function (err, stdout, stderr) {
      err.signal.should.equal('SIGTERM')
      stdout.should.match(/exited with sigterm, 143, SIGTERM/)
      done()
    })
  })

  it('receives an exit event when process.exit() is called', function (done) {
    exec(process.execPath + ' ./test/fixtures/exit.js', function (err, stdout, stderr) {
      err.code.should.equal(32)
      stdout.should.match(/exited with process\.exit\(\), 32, undefined/)
      done()
    })
  })

  it('does not exit if user handles signal', function (done) {
    exec(process.execPath + ' ./test/fixtures/signal-listener.js', function (err, stdout, stderr) {
      assert.equal(err.code, null)
      assert.equal(err.signal, 'SIGHUP')
      assert.equal(stdout, 'exited calledListener=4, code=129, signal="SIGHUP"\n')
      done()
    })
  })

  it('ensures that if alwaysLast=true, the handler is run last', function (done) {
    exec(process.execPath + ' ./test/fixtures/signal-last.js', function (err, stdout, stderr) {
      assert.equal(err.code, null)
      assert.equal(err.signal, 'SIGHUP')
      stdout.should.match(/first counter=1/)
      stdout.should.match(/last counter=2/)
      done()
    })
  })*/
})
<|endoftext|>


<commit_before>/*
 * mobile panel unit tests
 */

(function( $ ){

	var defaults = $.mobile.panel.prototype.options,
		classes = defaults.classes;

	function getPageFromPanel( $panel ) {
		return $panel.closest( ":jqmData(role='page')" );
	}

	function getModalFromPanel( $panel ) {
		var $page = getPageFromPanel( $panel );

		return $page.find( "." + defaults.classes.modal ).filter(function() {
			return $( this ).data( "panelid" ) === $panel.attr( "id" );
		});
	}

	function getWrapperFromPage( $page ) {
		return $page.find( "." + defaults.classes.contentWrap );
	}

	module( "stock panel" );

	test( "expected classes on create", function() {

		var $panel = $( "#panel-test-create" ),
			$page = getPageFromPanel( $panel );

		ok( $panel.hasClass( defaults.classes.panel ), "default class is present" );
		ok( $panel.hasClass( "ui-panel-display-" + defaults.display ), "display class is added per the default" );
		ok( $panel.hasClass( "ui-panel-position-" + defaults.position ), "position class is added per the default" );

		equal( $panel.hasClass( "ui-panel-animate" ), $.support.cssTransform3d, "animate class is present by default when supported" );
		equal( $page.hasClass( defaults.classes.pageChildAnimations ), $.support.cssTransform3d, "animation wrapper class added to page" );
		ok( $panel.hasClass( defaults.classes.panelClosed ), "panel is closed by default" );
		equal( $panel.hasClass( defaults.classes.cssTransform3d ), $.support.cssTransform3d, "transforms class added to page" );
	});

	asyncTest( "expected open, close events", function() {

		expect( 4 );

		var $panel = $( "#panel-test-events" );

		$panel.one( "panelbeforeopen panelopen panelbeforeclose panelclose", function( event ) {
			ok( true, event.type + " event." );
		}).one( "panelopen", function() {
			$panel.panel( "close" );
		}).one( "panelclose", function() {
			start();
		});

		$panel.panel( "open" );

	});

	asyncTest( "classes modified by open", function() {
		expect( 14 );

		var $panel = $( "#panel-test-open" ),
			$page = getPageFromPanel( $panel ),
			$wrapper = getWrapperFromPage( $page ),
			$modal = getModalFromPanel( $panel ),
			$openButton = $page.find( "a[href='\\#panel-test-open']" );

		$panel.one( "panelopen", function( event ) {
			ok( !$openButton.hasClass( $.mobile.activeBtnClass ), "button doesn't have active class" );

			ok( $page.hasClass( defaults.classes.pageBlock ), "page block class added to page" );
			ok( !$panel.hasClass( defaults.classes.panelClosed ), "closed class removed" );
			ok( $panel.hasClass( defaults.classes.panelOpen ), "open class added" );

			equal( $wrapper.length, 1, "wrapper exists." );
			ok( !$wrapper.hasClass( defaults.classes.contentWrapClosed ), "wrapper not closed class" );

			ok( $wrapper.hasClass( defaults.classes.contentWrapOpen ), "wrapper open class" );

			var prefix = defaults.classes.contentWrap;
			ok( $wrapper.hasClass( prefix + "-position-left" ), "wrapper position class" );
			ok( $wrapper.hasClass( prefix + "-display-overlay" ), "wrapper display type class" );

			ok( $modal.hasClass( defaults.classes.modalOpen ), "modal open class" );
			prefix = defaults.classes.modal;
			ok( $modal.hasClass( prefix + "-position-left" ), "modal position class" );
			ok( $modal.hasClass( prefix + "-display-overlay" ), "modal display type class" );

			// complete
			ok( $panel.hasClass( defaults.classes.openComplete ), "open complete class" );
			ok( $wrapper.hasClass( defaults.classes.contentWrapOpenComplete ), "wrapper open complete class" );

			// TODO test positioning when panel height > screen height
			// TODO test rebind resize after complete

			$panel.panel( "close" );
		}).one( "panelclose", function() {
			start();
		});

		$panel.panel( "open" );

	});

	asyncTest( "classes modified by close", function() {
		expect( 12 );

		var $panel = $( "#panel-test-close" ),
			$page = getPageFromPanel( $panel ),
			$wrapper = getWrapperFromPage( $page ),
			$modal = getModalFromPanel( $panel ),
			$openButton = $page.find( "a[href='\\#panel-test-close']" );

		$panel.one( "panelopen", function( event ) {
			$panel.panel( "close" );
		}).one( "panelclose", function( event ) {
			ok( !$openButton.hasClass( $.mobile.activeBtnClass ), "button doesn't have active class" );
			ok( !$panel.hasClass( defaults.classes.panelOpen ), "panel not open class" );

			ok( !$modal.hasClass( defaults.classes.modalOpen ), "modal without open class" );
			var prefix = defaults.classes.modal;
			ok( !$modal.hasClass( prefix + "-position-left" ), "modal without position class" );
			ok( !$modal.hasClass( prefix + "-display-overlay" ), "modal without display type class" );

			ok( !$wrapper.hasClass( defaults.classes.contentWrapOpen ), "wrapper open class" );
			ok( !$wrapper.hasClass( defaults.classes.contentWrapOpenComplete ), "wrapper open complete class" );

			// complete
			ok( $panel.hasClass( defaults.classes.panelClosed ), "panel closed class" );

			prefix = defaults.classes.contentWrap;
			ok( !$wrapper.hasClass( prefix + "-position-left" ), "wrapper position class" );
			ok( !$wrapper.hasClass( prefix + "-display-overlay" ), "wrapper display type class" );

			ok( $wrapper.hasClass( defaults.classes.contentWrapClosed ), "wrapper closed class" );
			ok( !$page.hasClass( defaults.classes.pageBlock ), "page block class not added to page" );

			// TODO test positioning when panel height > screen height
			// TODO test rebind resize after complete

			start();
		});

		$panel.panel( "open" );

	});

	asyncTest( "toggle", function() {
		expect( 2 );

		var $panel = $( "#panel-test-toggle" ),
			$page = getPageFromPanel( $panel );

		$panel.one( "panelopen", function( event ) {
			ok( true, "toggle open" );
			$panel.panel( "close" );
		}).one( "panelclose", function( event ) {
			ok( true, "toggle closed" );
			start();
		});

		$panel.panel( "toggle" );

	});

	test( "wrapper exists after create", function() {

		var $page = getPageFromPanel( $( "#panel-test-wrapper" ) ),
			$wrapper = getWrapperFromPage( $page );

		ok( $wrapper.length, "wrapper exists" );
		ok( $wrapper.hasClass( defaults.classes.contentWrapClosed ), "wrapper has closed class" );

	});

	// TODO _bindPageEvents

	test( "destroy method", function() {

		var $panel = $( "#panel-test-destroy" ),
			$page = getPageFromPanel( $panel ),
			$wrapper = getWrapperFromPage( $page );

		$panel.panel( "destroy" );
		// test page without sibling panels

		ok( !$wrapper.hasClass( defaults.classes.contentWrapOpen ) );
		ok( !$wrapper.hasClass( defaults.classes.contentWrapOpenComplete ) );

		ok( !$panel.hasClass( defaults.classes.panel ) );
		ok( !$wrapper.hasClass( "ui-panel-position-left" ) );
		ok( !$wrapper.hasClass( "ui-panel-display-overlay" ) );
		ok( !$panel.hasClass( defaults.classes.panelOpen ) );
		ok( !$panel.hasClass( defaults.classes.panelClosed ) );
		ok( !$panel.hasClass( "ui-body-c" ) );
		ok( !$panel.hasClass( defaults.classes.cssTransform3d ) );
		ok( getModalFromPanel( $panel ).length === 0, "modal was removed" );

		ok( !$panel.hasClass( [ classes.openComplete, classes.panelUnfixed, classes.panelClosed, classes.panelOpen ].join( " " ) ) );
		ok( !$page.hasClass( classes.pageBlock ) );

		$panel.panel();
	});

	module( "dismissable panel" );

	test( "dismissable", function() {
		var $panel = $( "#panel-test-dismiss" );
		equal( getModalFromPanel( $panel ).length, 1, "modal added to page" );
	});

	asyncTest( "click on dismissable modal closes panel", function() {

		expect( 1 );

		var $panel = $( "#panel-test-dismiss" ),
			$modal = getModalFromPanel( $panel );

		$panel.one( "panelopen", function() {

			$modal.trigger( "mousedown" );

		}).one( "panelclose", function() {

			ok( true, "modal is closed" );
			start();

		});

		$panel.panel( "open" );

	});

	module( "panel with non-default theme" );

	test( "expected classes on create", function() {

		var $panel = $( "#panel-test-non-default-theme" );
		ok( $panel.hasClass( "ui-body-" + $panel.jqmData('theme') ), "theme class was added" );

	});

	module( "panel with close button" );

	asyncTest( "panel opens, close button hides panel", function() {
		expect( 2 );

		var $panel = $( "#panel-test-with-close" ),
			$page = getPageFromPanel( $panel ),
			$closeButton = $panel.find( ":jqmData(rel='close')" );

		$panel.one( "panelopen", function() {

			ok( !$panel.hasClass( defaults.classes.panelClosed ), "wrapper opens" );
			$closeButton.trigger( "click" );

		}).one( "panelclose", function() {

			ok( $panel.hasClass( defaults.classes.panelClosed ), "wrapper has closed class" );
			start();
		});

		$panel.panel( "open" );
	});

}( jQuery ));
<commit_msg>Tests: Updated panel unit tests after refactor.<commit_after>/*
 * mobile panel unit tests
 */

(function( $ ){

	var defaults = $.mobile.panel.prototype.options,
		classes = defaults.classes;

	function getPageFromPanel( $panel ) {
		return $panel.closest( ":jqmData(role='page')" );
	}

	function getModalFromPanel( $panel ) {
		var $page = getPageFromPanel( $panel );

		return $page.find( "." + defaults.classes.modal ).filter(function() {
			return $( this ).data( "panelid" ) === $panel.attr( "id" );
		});
	}

	function getWrapperFromPage( $page ) {
		return $page.find( "." + defaults.classes.contentWrap );
	}

	module( "stock panel" );

	test( "expected classes on create", function() {

		var $panel = $( "#panel-test-create" ),
			$page = getPageFromPanel( $panel );

		ok( $panel.hasClass( defaults.classes.panel ), "default class is present" );
		ok( $panel.hasClass( "ui-panel-display-" + defaults.display ), "display class is added per the default" );
		ok( $panel.hasClass( "ui-panel-position-" + defaults.position ), "position class is added per the default" );

		equal( $panel.hasClass( defaults.classes.animate ), $.support.cssTransform3d, "animate class is present by default when supported" );
		ok( $panel.hasClass( defaults.classes.panelClosed ), "panel is closed by default" );
	});

	asyncTest( "expected open, close events", function() {

		expect( 4 );

		var $panel = $( "#panel-test-events" );

		$panel.one( "panelbeforeopen panelopen panelbeforeclose panelclose", function( event ) {
			ok( true, event.type + " event." );
		}).one( "panelopen", function() {
			$panel.panel( "close" );
		}).one( "panelclose", function() {
			start();
		});

		$panel.panel( "open" );

	});

	asyncTest( "classes modified by open", function() {
		expect( 12 );

		var $panel = $( "#panel-test-open" ),
			$page = getPageFromPanel( $panel ),
			$wrapper = getWrapperFromPage( $page ),
			$modal = getModalFromPanel( $panel ),
			$openButton = $page.find( "a[href='\\#panel-test-open']" );

		$panel.one( "panelopen", function( event ) {
			ok( !$openButton.hasClass( $.mobile.activeBtnClass ), "button doesn't have active class" );

			ok( !$panel.hasClass( defaults.classes.panelClosed ), "closed class removed" );
			ok( $panel.hasClass( defaults.classes.panelOpen ), "open class added" );

			equal( $wrapper.length, 1, "wrapper exists." );
			ok( !$wrapper.hasClass( defaults.classes.contentWrapClosed ), "wrapper not closed class" );

			ok( $wrapper.hasClass( defaults.classes.contentWrapOpen ), "wrapper open class" );

			var prefix = defaults.classes.contentWrap;
			ok( $wrapper.hasClass( prefix + "-position-left" ), "wrapper position class" );
			ok( $wrapper.hasClass( prefix + "-display-overlay" ), "wrapper display type class" );

			ok( $modal.hasClass( defaults.classes.modalOpen ), "modal open class" );
			prefix = defaults.classes.modal;
			ok( $modal.hasClass( prefix + "-position-left" ), "modal position class" );
			ok( $modal.hasClass( prefix + "-display-overlay" ), "modal display type class" );

			// complete
			ok( $page.hasClass( defaults.classes.pagePanelOpen ), "page panel open class added to page" );

			// TODO test positioning when panel height > screen height
			// TODO test rebind resize after complete

			$panel.panel( "close" );
		}).one( "panelclose", function() {
			start();
		});

		$panel.panel( "open" );

	});

	asyncTest( "classes modified by close", function() {
		expect( 12 );

		var $panel = $( "#panel-test-close" ),
			$page = getPageFromPanel( $panel ),
			$wrapper = getWrapperFromPage( $page ),
			$modal = getModalFromPanel( $panel ),
			$openButton = $page.find( "a[href='\\#panel-test-close']" );

		$panel.one( "panelopen", function( event ) {
			$panel.panel( "close" );
		}).one( "panelclose", function( event ) {
			ok( !$openButton.hasClass( $.mobile.activeBtnClass ), "button doesn't have active class" );
			ok( !$panel.hasClass( defaults.classes.panelOpen ), "panel not open class" );

			ok( !$modal.hasClass( defaults.classes.modalOpen ), "modal without open class" );
			var prefix = defaults.classes.modal;
			ok( !$modal.hasClass( prefix + "-position-left" ), "modal without position class" );
			ok( !$modal.hasClass( prefix + "-display-overlay" ), "modal without display type class" );

			ok( !$wrapper.hasClass( defaults.classes.contentWrapOpen ), "wrapper open class" );
			ok( !$wrapper.hasClass( defaults.classes.contentWrapOpenComplete ), "wrapper open complete class" );

			// complete
			ok( $panel.hasClass( defaults.classes.panelClosed ), "panel closed class" );

			prefix = defaults.classes.contentWrap;
			ok( !$wrapper.hasClass( prefix + "-position-left" ), "wrapper position class" );
			ok( !$wrapper.hasClass( prefix + "-display-overlay" ), "wrapper display type class" );

			ok( $wrapper.hasClass( defaults.classes.contentWrapClosed ), "wrapper closed class" );
			ok( !$page.hasClass( defaults.classes.pageBlock ), "page block class not added to page" );

			// TODO test positioning when panel height > screen height
			// TODO test rebind resize after complete

			start();
		});

		$panel.panel( "open" );

	});

	asyncTest( "toggle", function() {
		expect( 2 );

		var $panel = $( "#panel-test-toggle" ),
			$page = getPageFromPanel( $panel );

		$panel.one( "panelopen", function( event ) {
			ok( true, "toggle open" );
			$panel.panel( "close" );
		}).one( "panelclose", function( event ) {
			ok( true, "toggle closed" );
			start();
		});

		$panel.panel( "toggle" );

	});

	test( "wrapper exists after create", function() {

		var $page = getPageFromPanel( $( "#panel-test-wrapper" ) ),
			$wrapper = getWrapperFromPage( $page );

		ok( $wrapper.length, "wrapper exists" );
		ok( $wrapper.hasClass( defaults.classes.contentWrapClosed ), "wrapper has closed class" );

	});

	// TODO _bindPageEvents

	test( "destroy method", function() {

		var $panel = $( "#panel-test-destroy" ),
			$page = getPageFromPanel( $panel ),
			$wrapper = getWrapperFromPage( $page );

		$panel.panel( "destroy" );
		// test page without sibling panels

		ok( !$wrapper.hasClass( defaults.classes.contentWrapOpen ) );
		ok( !$wrapper.hasClass( defaults.classes.contentWrapOpenComplete ) );

		ok( !$panel.hasClass( defaults.classes.panel ) );
		ok( !$wrapper.hasClass( "ui-panel-position-left" ) );
		ok( !$wrapper.hasClass( "ui-panel-display-overlay" ) );
		ok( !$panel.hasClass( defaults.classes.panelOpen ) );
		ok( !$panel.hasClass( defaults.classes.panelClosed ) );
		ok( !$panel.hasClass( "ui-body-c" ) );
		ok( !$panel.hasClass( defaults.classes.cssTransform3d ) );
		ok( getModalFromPanel( $panel ).length === 0, "modal was removed" );

		ok( !$panel.hasClass( [ classes.openComplete, classes.panelUnfixed, classes.panelClosed, classes.panelOpen ].join( " " ) ) );
		ok( !$page.hasClass( classes.pageBlock ) );

		$panel.panel();
	});

	module( "dismissable panel" );

	test( "dismissable", function() {
		var $panel = $( "#panel-test-dismiss" );
		equal( getModalFromPanel( $panel ).length, 1, "modal added to page" );
	});

	asyncTest( "click on dismissable modal closes panel", function() {

		expect( 1 );

		var $panel = $( "#panel-test-dismiss" ),
			$modal = getModalFromPanel( $panel );

		$panel.one( "panelopen", function() {

			$modal.trigger( "mousedown" );

		}).one( "panelclose", function() {

			ok( true, "modal is closed" );
			start();

		});

		$panel.panel( "open" );

	});

	module( "panel with non-default theme" );

	test( "expected classes on create", function() {

		var $panel = $( "#panel-test-non-default-theme" );
		ok( $panel.hasClass( "ui-body-" + $panel.jqmData('theme') ), "theme class was added" );

	});

	module( "panel with close button" );

	asyncTest( "panel opens, close button hides panel", function() {
		expect( 2 );

		var $panel = $( "#panel-test-with-close" ),
			$page = getPageFromPanel( $panel ),
			$closeButton = $panel.find( ":jqmData(rel='close')" );

		$panel.one( "panelopen", function() {

			ok( !$panel.hasClass( defaults.classes.panelClosed ), "wrapper opens" );
			$closeButton.trigger( "click" );

		}).one( "panelclose", function() {

			ok( $panel.hasClass( defaults.classes.panelClosed ), "wrapper has closed class" );
			start();
		});

		$panel.panel( "open" );
	});

}( jQuery ));
<|endoftext|>