<commit_before>'use strict';

let expect  = require('chai').expect;
let compute = require('../src/calc').compute;

describe('compute multiplication', () => {

    context('integers', () => {

        it('should multiply "1 * 0"', () => {
            expect(compute('1 * 0')).to.equal(0);
        });

        it('should multiply "0 * 1"', () => {
            expect(compute('0 * 1')).to.equal(0);
        });

        it('should multiply "1 * 1"', () => {
            expect(compute('1 * 1')).to.equal(1);
        });

        it('should multiply "1*1"', () => {
            expect(compute('1*1')).to.equal(1);
        });

        it('should multiply "10 * 0"', () => {
            expect(compute('10 * 0')).to.equal(0);
        });

        it('should multiply "0 * 10', () => {
            expect(compute('0 * 10')).to.equal(0);
        });

        it('should multiply "10 * 1', () => {
            expect(compute('10 * 1')).to.equal(10);
        });

        it('should multiply "1 * 10"', () => {
            expect(compute('1 * 10')).to.equal(10);
        });

        it('should multiply "10 * 10"', () => {
            expect(compute('10 * 10')).to.equal(100);
        });

        it('should multiply "1 * -1"', () => {
            expect(compute('1 * -1')).to.equal(-1);
        });

        it('should multiply "1 * -10"', () => {
            expect(compute('1 * -10')).to.equal(-10);
        });

        it('should multiply "-1 * -1"', () => {
            expect(compute('-1 * -1')).to.equal(1);
        });

        it('should multiply "1 * -(2 * 2)"', () => {
            expect(compute('1 * -(2 * 2)')).to.equal(-4);
        });

        it('should multiply "(6 * 7)"', () => {
            expect(compute('(6 * 7)')).to.equal(42);
        })

        it('should multiply "100 * 1"', () => {
            expect(compute('100 * 1')).to.equal(100);
        });

        it('should multiply "1 * 100"', () => {
            expect(compute('1 * 100')).to.equal(100);
        });

        it('should multiply "-100 * 1"', () => {
            expect(compute('-100 * 1')).to.equal(-100);
        });

        it('should multiply "100 * -1"', () => {
            expect(compute('100 * -1')).to.equal(-100);
        });

        it('should multiply "1 * 2 * 3 * 4 * 5"', () => {
            expect(compute('1 * 2 * 3 * 4 * 5')).to.equal(120);
        });

        it('should multiply "1 * 3 * 2 * 5 * 4"', () => {
            expect(compute('1 * 3 * 2 * 5 * 4')).to.equal(120);
        });

        it('should multiply "100000 * 100 * 20 * 1"', () => {
            expect(compute('100000 * 100 * 20 * 1')).to.equal(200000000);
        });
    });

    context('floats', () => {

        it('should multiply "1.0 * 0.0"', () => {
            expect(compute('1.0 * 0.0')).to.be.closeTo(0.0, 0.01);
        });

        it('should multiply "0.0 * 1.0"', () => {
            expect(compute('0.0 * 1.0')).to.be.closeTo(0.0, 0.01);
        });

        it('should multiply "1.0 * 1.0"', () => {
            expect(compute('1.0 * 1.0')).to.be.closeTo(1.0, 0.01);
        });

        it('should multiply "1.1 * 1.0"', () => {
            expect(compute('1.1 * 1.0')).to.be.closeTo(1.1, 0.01);
        });

        it('should multiply "1.1*1.0"', () => {
            expect(compute('1.1*1.0')).to.be.closeTo(1.1, 0.01);
        });

        it('should multiply "20.123 * 1.2"', () => {
            expect(compute('20.123 * 1.2')).to.be.closeTo(24.1476, 0.0001);
        });

        it('should multiply "11.111 * -12.32"', () => {
            expect(compute('11.111 * -12.32')).to.be.closeTo(-136.88752, 0.0001);
        });

        it('should multiply "1.0 * -1.0"', () => {
            expect(compute('1.0 * -1.0')).to.be.closeTo(-1.0, 0.01);
        });

        it('should multiply "1.1 * -(2.2 * 2.456)"', () => {
            expect(compute('1.1 * -(2.2 * 2.456)')).to.be.closeTo(-5.94352, 0.0001);
        });

        it('should multiply "-4.211 * -3.456"', () => {
            expect(compute('-4.211 * -3.455')).to.be.closeTo(14.549005, 0.0001);
        });

        it('should multiply "102.43123 * 1.00"', () => {
            expect(compute('102.43123 * 1.00')).to.be.closeTo(102.43123, 0.000001);
        });

        it('should multiply "1.00 * 102.43123"', () => {
            expect(compute('1.00 * 102.43123')).to.be.closeTo(102.43123, 0.000001);
        });

        it('should multiply "-102.43123 * 1.00"', () => {
            expect(compute('-102.43123 * 1.00')).to.be.closeTo(-102.43123, 0.000001);
        });

        it('should multiply "1.00 * -102.43123"', () => {
            expect(compute('1.00 * -102.43123')).to.be.closeTo(-102.43123, 0.000001);
        });

        it('should multiply "1.1 * 2.3 * 5.234 * 5.567"', () => {
            expect(compute('1.1 * 2.3 * 5.234 * 5.567')).to.be.closeTo(73.71832534, 0.0001);
        });

        it('should multiply "5.567 * 1.1 * 5.234 * 2.3"', () => {
            expect(compute('5.567 * 1.1 * 5.234 * 2.3')).to.be.closeTo(73.71832534, 0.0001);
        });

        it('should multiply "89.234 * 1999999.123 * -823472.234234"', () => {
            expect(compute('89.234 * 1999999.123 * -823472.234234')).to.be.closeTo(-146963378255803.888368564988, 0.0000000000001);
        });

    });

    context('integers + floats', () => {

        it('should multiply "1 * 0.0"', () => {
            expect(compute('1 * 0.0')).to.closeTo(0.0, 0.01);
        });

        it('should multiply "0.0 * 1"', () => {
            expect(compute('0.0 * 1')).to.closeTo(0.0, 0.01);
        });

        it('should multiply "1.0 * 0"', () => {
            expect(compute('1.0 * 0')).to.closeTo(0.0, 0.01);
        });

        it('should multiply "0 * 1.0"', () => {
            expect(compute('0 * 1.0')).to.closeTo(0.0, 0.01);
        });

        it('should multiply "1 * 1.0"', () => {
            expect(compute('1 * 1.0')).to.be.closeTo(1.0, 0.01);
        });

        it('should multiply "1.0 * 1"', () => {
            expect(compute('1.0 * 1')).to.be.closeTo(1.0, 0.01);
        });

        it('should multiply "1*1.0"', () => {
            expect(compute('1*1.0')).to.be.closeTo(1.0, 0.01);
        });

        it('should multiply "1.0*1"', () => {
            expect(compute('1.0*1')).to.be.closeTo(1.0, 0.01);
        });

        it('should multiply "10 * 1.0"', () => {
            expect(compute('10 * 1.0')).to.be.closeTo(10.0, 0.01);
        });

        it('should multiply "1.0 * 10"', () => {
            expect(compute('1.0 * 10')).to.be.closeTo(10.0, 0.01);
        });

        it('should multiply "1 * -1.0"', () => {
            expect(compute('1 * -1.0')).to.be.closeTo(-1.0, 0.01);
        });

        it('should multiply "-1.0 * 1"', () => {
            expect(compute('-1.0 * 1')).to.be.closeTo(-1.0, 0.01);
        });

        it('should multiply "10.0 * 10"', () => {
            expect(compute('10.0 * 10')).to.be.closeTo(100.0, 0.01);
        });

        it('should multiply "10 * 10.0"', () => {
            expect(compute('10 * 10.0')).to.be.closeTo(100.0, 0.01);
        });

        it('should multiply "-1 * -1.0"', () => {
            expect(compute('-1 * -1.0')).to.be.closeTo(1.0, 0.01);
        });

        it('should multiply "-1.0 * -1"', () => {
            expect(compute('-1.0 * -1')).to.be.closeTo(1.0, 0.01);
        });

        it('should multiply "1.0 * -(2.0 * 2)"', () => {
            expect(compute('1.0 * -(2.0 * 2)')).to.be.closeTo(-4.0, 0.01);
        });

        it('should multiply "-100 * 0.923123"', () => {
            expect(compute('-100 * 0.923123')).to.be.closeTo(-92.3123, 0.00001);
        });

        it('should multiply "0.923123 * -100"', () => {
            expect(compute('0.923123 * -100')).to.be.closeTo(-92.3123, 0.00001);
        });

        it('should multiply "0.131234 * 5 * 6 * 13123.123994"', () => {
            expect(compute('0.131234 * 5 * 6 * 13123.123994')).to.be.closeTo(51666.00162685788, 0.00000000001);
        });

        it('should multiply "5 * 0.131234 * 6 * 13123.123994"', () => {
            expect(compute('5 * 0.131234 * 6 * 13123.123994')).to.be.closeTo(51666.00162685788, 0.00000000001);
        });

        it('should multiply "4234 * -42343.123123 * 999999.999999"', () => {
            expect(compute('4234 * -42343.123123 * 999999.999999')).to.be.closeTo(-179280783302602.719216697218, 0.0000000000001);
        });

        it('should multiply "-42343.123123 * 4234 * 999999.999999"', () => {
            expect(compute('-42343.123123 * 4234 * 999999.999999')).to.be.closeTo(-179280783302602.719216697218, 0.0000000000001);
        });
    });

    context('junk values', () => {

       it('should evaluate expression "4 *" to be NaN', () => {
           expect(compute('4 *')).to.be.NaN;
       });

       it('should evaluate expression "4**" to be NaN', () => {
           expect(compute('4**')).to.be.NaN;
       });

       it('should evaluate expression "*4" to be NaN', () => {
           expect(compute('*4')).to.be.NaN;
       });

       it('should evaluate "a * b * c" to be NaN', () => {
           expect(compute('a * b * c')).to.be.NaN;
       });

       it('should evaluate "5 * NaN" to be NaN', () => {
           expect(compute('5 * NaN')).to.be.NaN;
       });

       it('should evaluate "(5 * 4" to be NaN', () => {
           expect(compute('(5 * 4')).to.be.NaN;
       });

       it('should evaluate "5 * 4)" to be NaN', () => {
           expect(compute('5 * 4)')).to.be.NaN;
       });

       it('should evaluate ")5 * 4(" to be NaN', () => {
           expect(compute(')5 * 4(')).to.be.NaN;
       });
    });
});<commit_msg>Add order of operation tests for multiplication.<commit_after>'use strict';

let expect  = require('chai').expect;
let compute = require('../src/calc').compute;

describe('compute multiplication', () => {

    context('integers', () => {

        it('should multiply "1 * 0"', () => {
            expect(compute('1 * 0')).to.equal(0);
        });

        it('should multiply "0 * 1"', () => {
            expect(compute('0 * 1')).to.equal(0);
        });

        it('should multiply "1 * 1"', () => {
            expect(compute('1 * 1')).to.equal(1);
        });

        it('should multiply "1*1"', () => {
            expect(compute('1*1')).to.equal(1);
        });

        it('should multiply "10 * 0"', () => {
            expect(compute('10 * 0')).to.equal(0);
        });

        it('should multiply "0 * 10', () => {
            expect(compute('0 * 10')).to.equal(0);
        });

        it('should multiply "10 * 1', () => {
            expect(compute('10 * 1')).to.equal(10);
        });

        it('should multiply "1 * 10"', () => {
            expect(compute('1 * 10')).to.equal(10);
        });

        it('should multiply "10 * 10"', () => {
            expect(compute('10 * 10')).to.equal(100);
        });

        it('should multiply "1 * -1"', () => {
            expect(compute('1 * -1')).to.equal(-1);
        });

        it('should multiply "1 * -10"', () => {
            expect(compute('1 * -10')).to.equal(-10);
        });

        it('should multiply "-1 * -1"', () => {
            expect(compute('-1 * -1')).to.equal(1);
        });

        it('should multiply "1 * -(2 * 2)"', () => {
            expect(compute('1 * -(2 * 2)')).to.equal(-4);
        });

        it('should multiply "(6 * 7)"', () => {
            expect(compute('(6 * 7)')).to.equal(42);
        })

        it('should multiply "100 * 1"', () => {
            expect(compute('100 * 1')).to.equal(100);
        });

        it('should multiply "1 * 100"', () => {
            expect(compute('1 * 100')).to.equal(100);
        });

        it('should multiply "-100 * 1"', () => {
            expect(compute('-100 * 1')).to.equal(-100);
        });

        it('should multiply "100 * -1"', () => {
            expect(compute('100 * -1')).to.equal(-100);
        });

        it('should multiply "1 * 2 * 3 * 4 * 5"', () => {
            expect(compute('1 * 2 * 3 * 4 * 5')).to.equal(120);
        });

        it('should multiply "1 * 3 * 2 * 5 * 4"', () => {
            expect(compute('1 * 3 * 2 * 5 * 4')).to.equal(120);
        });

        it('should multiply "100000 * 100 * 20 * 1"', () => {
            expect(compute('100000 * 100 * 20 * 1')).to.equal(200000000);
        });
    });

    context('floats', () => {

        it('should multiply "1.0 * 0.0"', () => {
            expect(compute('1.0 * 0.0')).to.be.closeTo(0.0, 0.01);
        });

        it('should multiply "0.0 * 1.0"', () => {
            expect(compute('0.0 * 1.0')).to.be.closeTo(0.0, 0.01);
        });

        it('should multiply "1.0 * 1.0"', () => {
            expect(compute('1.0 * 1.0')).to.be.closeTo(1.0, 0.01);
        });

        it('should multiply "1.1 * 1.0"', () => {
            expect(compute('1.1 * 1.0')).to.be.closeTo(1.1, 0.01);
        });

        it('should multiply "1.1*1.0"', () => {
            expect(compute('1.1*1.0')).to.be.closeTo(1.1, 0.01);
        });

        it('should multiply "20.123 * 1.2"', () => {
            expect(compute('20.123 * 1.2')).to.be.closeTo(24.1476, 0.0001);
        });

        it('should multiply "11.111 * -12.32"', () => {
            expect(compute('11.111 * -12.32')).to.be.closeTo(-136.88752, 0.0001);
        });

        it('should multiply "1.0 * -1.0"', () => {
            expect(compute('1.0 * -1.0')).to.be.closeTo(-1.0, 0.01);
        });

        it('should multiply "1.1 * -(2.2 * 2.456)"', () => {
            expect(compute('1.1 * -(2.2 * 2.456)')).to.be.closeTo(-5.94352, 0.0001);
        });

        it('should multiply "-4.211 * -3.456"', () => {
            expect(compute('-4.211 * -3.455')).to.be.closeTo(14.549005, 0.0001);
        });

        it('should multiply "102.43123 * 1.00"', () => {
            expect(compute('102.43123 * 1.00')).to.be.closeTo(102.43123, 0.000001);
        });

        it('should multiply "1.00 * 102.43123"', () => {
            expect(compute('1.00 * 102.43123')).to.be.closeTo(102.43123, 0.000001);
        });

        it('should multiply "-102.43123 * 1.00"', () => {
            expect(compute('-102.43123 * 1.00')).to.be.closeTo(-102.43123, 0.000001);
        });

        it('should multiply "1.00 * -102.43123"', () => {
            expect(compute('1.00 * -102.43123')).to.be.closeTo(-102.43123, 0.000001);
        });

        it('should multiply "1.1 * 2.3 * 5.234 * 5.567"', () => {
            expect(compute('1.1 * 2.3 * 5.234 * 5.567')).to.be.closeTo(73.71832534, 0.0001);
        });

        it('should multiply "5.567 * 1.1 * 5.234 * 2.3"', () => {
            expect(compute('5.567 * 1.1 * 5.234 * 2.3')).to.be.closeTo(73.71832534, 0.0001);
        });

        it('should multiply "89.234 * 1999999.123 * -823472.234234"', () => {
            expect(compute('89.234 * 1999999.123 * -823472.234234')).to.be.closeTo(-146963378255803.888368564988, 0.0000000000001);
        });

    });

    context('integers + floats', () => {

        it('should multiply "1 * 0.0"', () => {
            expect(compute('1 * 0.0')).to.closeTo(0.0, 0.01);
        });

        it('should multiply "0.0 * 1"', () => {
            expect(compute('0.0 * 1')).to.closeTo(0.0, 0.01);
        });

        it('should multiply "1.0 * 0"', () => {
            expect(compute('1.0 * 0')).to.closeTo(0.0, 0.01);
        });

        it('should multiply "0 * 1.0"', () => {
            expect(compute('0 * 1.0')).to.closeTo(0.0, 0.01);
        });

        it('should multiply "1 * 1.0"', () => {
            expect(compute('1 * 1.0')).to.be.closeTo(1.0, 0.01);
        });

        it('should multiply "1.0 * 1"', () => {
            expect(compute('1.0 * 1')).to.be.closeTo(1.0, 0.01);
        });

        it('should multiply "1*1.0"', () => {
            expect(compute('1*1.0')).to.be.closeTo(1.0, 0.01);
        });

        it('should multiply "1.0*1"', () => {
            expect(compute('1.0*1')).to.be.closeTo(1.0, 0.01);
        });

        it('should multiply "10 * 1.0"', () => {
            expect(compute('10 * 1.0')).to.be.closeTo(10.0, 0.01);
        });

        it('should multiply "1.0 * 10"', () => {
            expect(compute('1.0 * 10')).to.be.closeTo(10.0, 0.01);
        });

        it('should multiply "1 * -1.0"', () => {
            expect(compute('1 * -1.0')).to.be.closeTo(-1.0, 0.01);
        });

        it('should multiply "-1.0 * 1"', () => {
            expect(compute('-1.0 * 1')).to.be.closeTo(-1.0, 0.01);
        });

        it('should multiply "10.0 * 10"', () => {
            expect(compute('10.0 * 10')).to.be.closeTo(100.0, 0.01);
        });

        it('should multiply "10 * 10.0"', () => {
            expect(compute('10 * 10.0')).to.be.closeTo(100.0, 0.01);
        });

        it('should multiply "-1 * -1.0"', () => {
            expect(compute('-1 * -1.0')).to.be.closeTo(1.0, 0.01);
        });

        it('should multiply "-1.0 * -1"', () => {
            expect(compute('-1.0 * -1')).to.be.closeTo(1.0, 0.01);
        });

        it('should multiply "1.0 * -(2.0 * 2)"', () => {
            expect(compute('1.0 * -(2.0 * 2)')).to.be.closeTo(-4.0, 0.01);
        });

        it('should multiply "-100 * 0.923123"', () => {
            expect(compute('-100 * 0.923123')).to.be.closeTo(-92.3123, 0.00001);
        });

        it('should multiply "0.923123 * -100"', () => {
            expect(compute('0.923123 * -100')).to.be.closeTo(-92.3123, 0.00001);
        });

        it('should multiply "0.131234 * 5 * 6 * 13123.123994"', () => {
            expect(compute('0.131234 * 5 * 6 * 13123.123994')).to.be.closeTo(51666.00162685788, 0.00000000001);
        });

        it('should multiply "5 * 0.131234 * 6 * 13123.123994"', () => {
            expect(compute('5 * 0.131234 * 6 * 13123.123994')).to.be.closeTo(51666.00162685788, 0.00000000001);
        });

        it('should multiply "4234 * -42343.123123 * 999999.999999"', () => {
            expect(compute('4234 * -42343.123123 * 999999.999999')).to.be.closeTo(-179280783302602.719216697218, 0.0000000000001);
        });

        it('should multiply "-42343.123123 * 4234 * 999999.999999"', () => {
            expect(compute('-42343.123123 * 4234 * 999999.999999')).to.be.closeTo(-179280783302602.719216697218, 0.0000000000001);
        });
    });

    context('junk values', () => {

       it('should evaluate expression "4 *" to be NaN', () => {
           expect(compute('4 *')).to.be.NaN;
       });

       it('should evaluate expression "4**" to be NaN', () => {
           expect(compute('4**')).to.be.NaN;
       });

       it('should evaluate expression "*4" to be NaN', () => {
           expect(compute('*4')).to.be.NaN;
       });

       it('should evaluate "a * b * c" to be NaN', () => {
           expect(compute('a * b * c')).to.be.NaN;
       });

       it('should evaluate "5 * NaN" to be NaN', () => {
           expect(compute('5 * NaN')).to.be.NaN;
       });

       it('should evaluate "(5 * 4" to be NaN', () => {
           expect(compute('(5 * 4')).to.be.NaN;
       });

       it('should evaluate "5 * 4)" to be NaN', () => {
           expect(compute('5 * 4)')).to.be.NaN;
       });

       it('should evaluate ")5 * 4(" to be NaN', () => {
           expect(compute(')5 * 4(')).to.be.NaN;
       });
    });

    context('order of operations', () => {

        it('should multiply "1 * 2 * (3 * 4)"', () => {
            expect(compute('1 * 2 * (3 * 4)')).to.equal(24);
        });

        it('should multiply "(1) * (2) * (3 * 4)"', () => {
            expect(compute('1 * 2 * (3 * 4)')).to.equal(24);
        });

        it('should compute "((1 * 2) * (3 * 4))"', () => {
            expect(compute('((1 * 2) * (3 * 4))')).to.equal(24);
        });

        it('should compute "(1 * 2) * (3 * 4)"', () => {
            expect(compute('(1 * 2) * (3 * 4)')).to.equal(24);
        });

        it('should compute "1 * (2 * (3 * 4))"', () => {
            expect(compute('1 * (2 * (3 * 4))')).to.equal(24);
        });

        it('should compute "1 * (2 * 3) * 4"', () => {
            expect(compute('1 * (2 * 3) * 4')).to.equal(24);
        });

    });
});<|endoftext|>


<commit_before>var makeRestRequest = require('./make-rest-request');

var metric = {
	getValue: getValue,
    getValues: getValues,
    setValue: setValue,
    getMetrics: getMetrics,
    addMetric: addMetric,
    updateMetric: updateMetric
};

function getValue(options,callback)
{
    options.url="/{chumblr}/metrics/{metricId}/entities/{entityId}/value";
    options.verb="get";
    makeRestRequest(options,callback);
}

function getValues(options,callback)
{
    options.url="/{chumblr}/metrics/{metricId}/values";
    options.verb="get";
    makeRestRequest(options,callback);
}

function setValue(options,callback)
{
    options.url="/{chumblr}/metrics/{metricId}/entities/{entityId}/value";
    options.verb="post";
    makeRestRequest(options,callback);
}

function getMetrics(options,callback)
{
    options.url="/{chumblr}/metrics";
    options.verb="get";
    makeRestRequest(options,callback);
}

function getMetric(options,callback)
{
    options.url="/{chumblr}/metrics/{metricId}";
    options.verb="get";
    makeRestRequest(options,callback);
}

function addMetric(options,callback)
{
    options.url="/{chumblr}/metrics";
    options.verb="post";
    options.data=options.metric;
    makeRestRequest(options,callback);
}

function updateMetric(options,callback)
{
    options.url="/{chumblr}/metrics/{metricId}";
    options.verb="put";
    options.data=options.metric;
    makeRestRequest(options,callback);
}

module.exports = metric;
<commit_msg>Add function for getting a metric<commit_after>var makeRestRequest = require('./make-rest-request');

var metric = {
	getValue: getValue,
    getValues: getValues,
    setValue: setValue,
    getMetric: getMetric,
    getMetrics: getMetrics,
    addMetric: addMetric,
    updateMetric: updateMetric
};

function getValue(options,callback)
{
    options.url="/{chumblr}/metrics/{metricId}/entities/{entityId}/value";
    options.verb="get";
    makeRestRequest(options,callback);
}

function getValues(options,callback)
{
    options.url="/{chumblr}/metrics/{metricId}/values";
    options.verb="get";
    makeRestRequest(options,callback);
}

function setValue(options,callback)
{
    options.url="/{chumblr}/metrics/{metricId}/entities/{entityId}/value";
    options.verb="post";
    makeRestRequest(options,callback);
}

function getMetrics(options,callback)
{
    options.url="/{chumblr}/metrics";
    options.verb="get";
    makeRestRequest(options,callback);
}

function getMetric(options,callback)
{
    options.url="/{chumblr}/metrics/{metricId}";
    options.verb="get";
    makeRestRequest(options,callback);
}

function addMetric(options,callback)
{
    options.url="/{chumblr}/metrics";
    options.verb="post";
    options.data=options.metric;
    makeRestRequest(options,callback);
}

function updateMetric(options,callback)
{
    options.url="/{chumblr}/metrics/{metricId}";
    options.verb="put";
    options.data=options.metric;
    makeRestRequest(options,callback);
}

module.exports = metric;
<|endoftext|>


<commit_before>import webpack from 'webpack'
import cssnano from 'cssnano'
import HtmlWebpackPlugin from 'html-webpack-plugin'
import ExtractTextPlugin from 'extract-text-webpack-plugin'
import config from '../config'
import _debug from 'debug'

const debug = _debug('app:webpack:config')
const paths = config.utils_paths
const {__DEV__, __PROD__, __TEST__} = config.globals

debug('Create configuration.')
const webpackConfig = {
  name: 'client',
  target: 'web',
  devtool: config.compiler_devtool,
  resolve: {
    root: paths.base(config.dir_client),
    extensions: ['', '.js', '.jsx', '.json']
  },
  module: {}
}
// ------------------------------------
// Entry Points
// ------------------------------------
const APP_ENTRY_PATH = paths.base(config.dir_client) + '/main.js'

webpackConfig.entry = {
  app: __DEV__
    ? [APP_ENTRY_PATH, `webpack-hot-middleware/client?path=${config.compiler_public_path}__webpack_hmr`]
    : [APP_ENTRY_PATH],
  vendor: config.compiler_vendor
}

// ------------------------------------
// Bundle Output
// ------------------------------------
webpackConfig.output = {
  filename: `[name].[${config.compiler_hash_type}].js`,
  path: paths.base(config.dir_dist),
  publicPath: config.compiler_public_path
}

// ------------------------------------
// Plugins
// ------------------------------------
webpackConfig.plugins = [
  new webpack.DefinePlugin(config.globals),
  new HtmlWebpackPlugin({
    template: paths.client('index.html'),
    hash: false,
    favicon: paths.client('static/favicon.ico'),
    filename: 'index.html',
    inject: 'body',
    minify: {
      collapseWhitespace: true
    }
  })
]

if (__DEV__) {
  debug('Enable plugins for live development (HMR, NoErrors).')
  webpackConfig.plugins.push(
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NoErrorsPlugin()
  )
} else if (__PROD__) {
  debug('Enable plugins for production (OccurenceOrder, Dedupe & UglifyJS).')
  webpackConfig.plugins.push(
    new webpack.optimize.OccurrenceOrderPlugin(),
    new webpack.optimize.DedupePlugin(),
    new webpack.optimize.UglifyJsPlugin({
      compress: {
        unused: true,
        dead_code: true,
        warnings: false
      }
    })
  )
}

// Don't split bundles during testing, since we only want import one bundle
if (!__TEST__) {
  webpackConfig.plugins.push(new webpack.optimize.CommonsChunkPlugin({
    names: ['vendor']
  }))
}

// ------------------------------------
// Pre-Loaders
// ------------------------------------
webpackConfig.module.preLoaders = [{
  test: /\.(js|jsx)$/,
  loader: 'eslint',
  exclude: /node_modules/
}]

webpackConfig.eslint = {
  configFile: paths.base('.eslintrc'),
  emitWarning: __DEV__
}

// ------------------------------------
// Loaders
// ------------------------------------
// JavaScript / JSON
webpackConfig.module.loaders = [{
  test: /\.(js|jsx)$/,
  exclude: /node_modules/,
  loader: 'babel',
  query: {
    cacheDirectory: true,
    plugins: ['transform-runtime'],
    presets: ['es2015', 'react', 'stage-0'],
    env: {
      development: {
        plugins: [
          ['react-transform', {
            transforms: [{
              transform: 'react-transform-hmr',
              imports: ['react'],
              locals: ['module']
            }, {
              transform: 'react-transform-catch-errors',
              imports: ['react', 'redbox-react']
            }]
          }]
        ]
      },
      production: {
        plugins: [
          'transform-react-remove-prop-types',
          'transform-react-constant-elements'
        ]
      }
    }
  }
},
{
  test: /\.json$/,
  loader: 'json'
}]

// ------------------------------------
// Style Loaders
// ------------------------------------
// We use cssnano with the postcss loader, so we tell
// css-loader not to duplicate minimization.
const BASE_CSS_LOADER = 'css?sourceMap&-minimize'

// Add any packge names here whose styles need to be treated as CSS modules.
// These paths will be combined into a single regex.
const PATHS_TO_TREAT_AS_CSS_MODULES = [
  // 'react-toolbox', (example)
]

// If config has CSS modules enabled, treat this project's styles as CSS modules.
if (config.compiler_css_modules) {
  PATHS_TO_TREAT_AS_CSS_MODULES.push(
    paths.base(config.dir_client).replace(/[\^\$\.\*\+\-\?\=\!\:\|\\\/\(\)\[\]\{\}\,]/g, '\\$&')
  )
}

const isUsingCSSModules = !!PATHS_TO_TREAT_AS_CSS_MODULES.length
const cssModulesRegex = new RegExp(`(${PATHS_TO_TREAT_AS_CSS_MODULES.join('|')})`)

// Loaders for styles that need to be treated as CSS modules.
if (isUsingCSSModules) {
  const cssModulesLoader = [
    BASE_CSS_LOADER,
    'modules',
    'importLoaders=1',
    'localIdentName=[name]__[local]___[hash:base64:5]'
  ].join('&')

  webpackConfig.module.loaders.push({
    test: /\.scss$/,
    include: cssModulesRegex,
    loaders: [
      'style',
      cssModulesLoader,
      'postcss',
      'sass?sourceMap'
    ]
  })

  webpackConfig.module.loaders.push({
    test: /\.css$/,
    include: cssModulesRegex,
    loaders: [
      'style',
      cssModulesLoader,
      'postcss'
    ]
  })
}

// Loaders for files that should not be treated as CSS modules.
const excludeCSSModules = isUsingCSSModules ? cssModulesRegex : false
webpackConfig.module.loaders.push({
  test: /\.scss$/,
  exclude: excludeCSSModules,
  loaders: [
    'style',
    BASE_CSS_LOADER,
    'postcss',
    'sass?sourceMap'
  ]
})
webpackConfig.module.loaders.push({
  test: /\.css$/,
  exclude: excludeCSSModules,
  loaders: [
    'style',
    BASE_CSS_LOADER,
    'postcss'
  ]
})

// ------------------------------------
// Style Configuration
// ------------------------------------
webpackConfig.sassLoader = {
  includePaths: paths.client('styles')
}

webpackConfig.postcss = [
  cssnano({
    autoprefixer: {
      add: true,
      remove: true,
      browsers: ['last 2 versions']
    },
    discardComments: {
      removeAll: true
    },
    safe: true,
    sourcemap: true
  })
]

// File loaders
/* eslint-disable */
webpackConfig.module.loaders.push(
  { test: /\.woff(\?.*)?$/,  loader: 'url?prefix=fonts/&name=[path][name].[ext]&limit=10000&mimetype=application/font-woff' },
  { test: /\.woff2(\?.*)?$/, loader: 'url?prefix=fonts/&name=[path][name].[ext]&limit=10000&mimetype=application/font-woff2' },
  { test: /\.otf(\?.*)?$/,   loader: 'file?prefix=fonts/&name=[path][name].[ext]&limit=10000&mimetype=font/opentype' },
  { test: /\.ttf(\?.*)?$/,   loader: 'url?prefix=fonts/&name=[path][name].[ext]&limit=10000&mimetype=application/octet-stream' },
  { test: /\.eot(\?.*)?$/,   loader: 'file?prefix=fonts/&name=[path][name].[ext]' },
  { test: /\.svg(\?.*)?$/,   loader: 'url?prefix=fonts/&name=[path][name].[ext]&limit=10000&mimetype=image/svg+xml' },
  { test: /\.(png|jpg)$/,    loader: 'url?limit=8192' }
)
/* eslint-enable */

// ------------------------------------
// Finalize Configuration
// ------------------------------------
// when we don't know the public path (we know it only when HMR is enabled [in development]) we
// need to use the extractTextPlugin to fix this issue:
// http://stackoverflow.com/questions/34133808/webpack-ots-parsing-error-loading-fonts/34133809#34133809
if (!__DEV__) {
  debug('Apply ExtractTextPlugin to CSS loaders.')
  webpackConfig.module.loaders.filter((loader) =>
    loader.loaders && loader.loaders.find((name) => /css/.test(name.split('?')[0]))
  ).forEach((loader) => {
    const [first, ...rest] = loader.loaders
    loader.loader = ExtractTextPlugin.extract(first, rest.join('!'))
    delete loader.loaders
  })

  webpackConfig.plugins.push(
    new ExtractTextPlugin('[name].[contenthash].css', {
      allChunks: true
    })
  )
}

export default webpackConfig
<commit_msg>fix(css-modules): disable conflicting cssnano options<commit_after>import webpack from 'webpack'
import cssnano from 'cssnano'
import HtmlWebpackPlugin from 'html-webpack-plugin'
import ExtractTextPlugin from 'extract-text-webpack-plugin'
import config from '../config'
import _debug from 'debug'

const debug = _debug('app:webpack:config')
const paths = config.utils_paths
const {__DEV__, __PROD__, __TEST__} = config.globals

debug('Create configuration.')
const webpackConfig = {
  name: 'client',
  target: 'web',
  devtool: config.compiler_devtool,
  resolve: {
    root: paths.base(config.dir_client),
    extensions: ['', '.js', '.jsx', '.json']
  },
  module: {}
}
// ------------------------------------
// Entry Points
// ------------------------------------
const APP_ENTRY_PATH = paths.base(config.dir_client) + '/main.js'

webpackConfig.entry = {
  app: __DEV__
    ? [APP_ENTRY_PATH, `webpack-hot-middleware/client?path=${config.compiler_public_path}__webpack_hmr`]
    : [APP_ENTRY_PATH],
  vendor: config.compiler_vendor
}

// ------------------------------------
// Bundle Output
// ------------------------------------
webpackConfig.output = {
  filename: `[name].[${config.compiler_hash_type}].js`,
  path: paths.base(config.dir_dist),
  publicPath: config.compiler_public_path
}

// ------------------------------------
// Plugins
// ------------------------------------
webpackConfig.plugins = [
  new webpack.DefinePlugin(config.globals),
  new HtmlWebpackPlugin({
    template: paths.client('index.html'),
    hash: false,
    favicon: paths.client('static/favicon.ico'),
    filename: 'index.html',
    inject: 'body',
    minify: {
      collapseWhitespace: true
    }
  })
]

if (__DEV__) {
  debug('Enable plugins for live development (HMR, NoErrors).')
  webpackConfig.plugins.push(
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NoErrorsPlugin()
  )
} else if (__PROD__) {
  debug('Enable plugins for production (OccurenceOrder, Dedupe & UglifyJS).')
  webpackConfig.plugins.push(
    new webpack.optimize.OccurrenceOrderPlugin(),
    new webpack.optimize.DedupePlugin(),
    new webpack.optimize.UglifyJsPlugin({
      compress: {
        unused: true,
        dead_code: true,
        warnings: false
      }
    })
  )
}

// Don't split bundles during testing, since we only want import one bundle
if (!__TEST__) {
  webpackConfig.plugins.push(new webpack.optimize.CommonsChunkPlugin({
    names: ['vendor']
  }))
}

// ------------------------------------
// Pre-Loaders
// ------------------------------------
webpackConfig.module.preLoaders = [{
  test: /\.(js|jsx)$/,
  loader: 'eslint',
  exclude: /node_modules/
}]

webpackConfig.eslint = {
  configFile: paths.base('.eslintrc'),
  emitWarning: __DEV__
}

// ------------------------------------
// Loaders
// ------------------------------------
// JavaScript / JSON
webpackConfig.module.loaders = [{
  test: /\.(js|jsx)$/,
  exclude: /node_modules/,
  loader: 'babel',
  query: {
    cacheDirectory: true,
    plugins: ['transform-runtime'],
    presets: ['es2015', 'react', 'stage-0'],
    env: {
      development: {
        plugins: [
          ['react-transform', {
            transforms: [{
              transform: 'react-transform-hmr',
              imports: ['react'],
              locals: ['module']
            }, {
              transform: 'react-transform-catch-errors',
              imports: ['react', 'redbox-react']
            }]
          }]
        ]
      },
      production: {
        plugins: [
          'transform-react-remove-prop-types',
          'transform-react-constant-elements'
        ]
      }
    }
  }
},
{
  test: /\.json$/,
  loader: 'json'
}]

// ------------------------------------
// Style Loaders
// ------------------------------------
// We use cssnano with the postcss loader, so we tell
// css-loader not to duplicate minimization.
const BASE_CSS_LOADER = 'css?sourceMap&-minimize'

// Add any packge names here whose styles need to be treated as CSS modules.
// These paths will be combined into a single regex.
const PATHS_TO_TREAT_AS_CSS_MODULES = [
  // 'react-toolbox', (example)
]

// If config has CSS modules enabled, treat this project's styles as CSS modules.
if (config.compiler_css_modules) {
  PATHS_TO_TREAT_AS_CSS_MODULES.push(
    paths.base(config.dir_client).replace(/[\^\$\.\*\+\-\?\=\!\:\|\\\/\(\)\[\]\{\}\,]/g, '\\$&')
  )
}

const isUsingCSSModules = !!PATHS_TO_TREAT_AS_CSS_MODULES.length
const cssModulesRegex = new RegExp(`(${PATHS_TO_TREAT_AS_CSS_MODULES.join('|')})`)

// Loaders for styles that need to be treated as CSS modules.
if (isUsingCSSModules) {
  const cssModulesLoader = [
    BASE_CSS_LOADER,
    'modules',
    'importLoaders=1',
    'localIdentName=[name]__[local]___[hash:base64:5]'
  ].join('&')

  webpackConfig.module.loaders.push({
    test: /\.scss$/,
    include: cssModulesRegex,
    loaders: [
      'style',
      cssModulesLoader,
      'postcss',
      'sass?sourceMap'
    ]
  })

  webpackConfig.module.loaders.push({
    test: /\.css$/,
    include: cssModulesRegex,
    loaders: [
      'style',
      cssModulesLoader,
      'postcss'
    ]
  })
}

// Loaders for files that should not be treated as CSS modules.
const excludeCSSModules = isUsingCSSModules ? cssModulesRegex : false
webpackConfig.module.loaders.push({
  test: /\.scss$/,
  exclude: excludeCSSModules,
  loaders: [
    'style',
    BASE_CSS_LOADER,
    'postcss',
    'sass?sourceMap'
  ]
})
webpackConfig.module.loaders.push({
  test: /\.css$/,
  exclude: excludeCSSModules,
  loaders: [
    'style',
    BASE_CSS_LOADER,
    'postcss'
  ]
})

// ------------------------------------
// Style Configuration
// ------------------------------------
webpackConfig.sassLoader = {
  includePaths: paths.client('styles')
}

webpackConfig.postcss = [
  cssnano({
    autoprefixer: {
      add: true,
      remove: true,
      browsers: ['last 2 versions']
    },
    discardComments: {
      removeAll: true
    },
    discardUnused: false,
    mergeIdents: false,
    reduceIdents: false,
    safe: true,
    sourcemap: true
  })
]

// File loaders
/* eslint-disable */
webpackConfig.module.loaders.push(
  { test: /\.woff(\?.*)?$/,  loader: 'url?prefix=fonts/&name=[path][name].[ext]&limit=10000&mimetype=application/font-woff' },
  { test: /\.woff2(\?.*)?$/, loader: 'url?prefix=fonts/&name=[path][name].[ext]&limit=10000&mimetype=application/font-woff2' },
  { test: /\.otf(\?.*)?$/,   loader: 'file?prefix=fonts/&name=[path][name].[ext]&limit=10000&mimetype=font/opentype' },
  { test: /\.ttf(\?.*)?$/,   loader: 'url?prefix=fonts/&name=[path][name].[ext]&limit=10000&mimetype=application/octet-stream' },
  { test: /\.eot(\?.*)?$/,   loader: 'file?prefix=fonts/&name=[path][name].[ext]' },
  { test: /\.svg(\?.*)?$/,   loader: 'url?prefix=fonts/&name=[path][name].[ext]&limit=10000&mimetype=image/svg+xml' },
  { test: /\.(png|jpg)$/,    loader: 'url?limit=8192' }
)
/* eslint-enable */

// ------------------------------------
// Finalize Configuration
// ------------------------------------
// when we don't know the public path (we know it only when HMR is enabled [in development]) we
// need to use the extractTextPlugin to fix this issue:
// http://stackoverflow.com/questions/34133808/webpack-ots-parsing-error-loading-fonts/34133809#34133809
if (!__DEV__) {
  debug('Apply ExtractTextPlugin to CSS loaders.')
  webpackConfig.module.loaders.filter((loader) =>
    loader.loaders && loader.loaders.find((name) => /css/.test(name.split('?')[0]))
  ).forEach((loader) => {
    const [first, ...rest] = loader.loaders
    loader.loader = ExtractTextPlugin.extract(first, rest.join('!'))
    delete loader.loaders
  })

  webpackConfig.plugins.push(
    new ExtractTextPlugin('[name].[contenthash].css', {
      allChunks: true
    })
  )
}

export default webpackConfig
<|endoftext|>


<commit_before>(function() {
    'use strict';

    var DIR         = __dirname + '/',
        os          = require('os'),
        crypto      = require('crypto'),
        fs          = require('fs'),
        path        = require('path'),

        mkdirp      = require('mkdirp'),
        ischanged   = require('ischanged'),
        Util        = require('util-io'),
        type        = Util.type,
        ponse       = require('ponse'),

        WIN         = process.platform === 'win32',

        MinFolder   = getDir() || DIR + 'min/';

    module.exports  = minify;

    function getModule(name) {
        return require(DIR + name);
    }

    function optimizeData(params, callback) {
        var p   = params,
            ext = p.ext.slice(1);

        getModule(ext)(p.data, callback);
    }

    function minify(name, options, callback) {
        var isChanged, isExist, ret, ext, is,
            EXT         = ['js', 'html', 'css'],
            isObject    = type.object(name),
            exec        = Util.exec,
            nameMin     = getName(name);

        if (!callback)
            callback = options;

        if (!options && !callback)
            ret = middle.bind(null, name);
        else if (isObject) {
            optimizeData(name, callback);
        } else {
            ext         = path.extname(name).slice(1);
            is          = ~EXT.indexOf(ext);

            if (!is) {
                callback(Error('Supported file types: ' + EXT.join(', ')));
            } else {
                isChanged   = exec.with(ischanged, name),
                isExist     = exec.with(fs.lstat, nameMin);

                exec.parallel([isChanged, isExist], function(error, changed, exists) {
                    if (changed || !exists)
                        optimize(name, options, callback);
                    else
                        if (options.returnName)
                            callback(null, nameMin);
                        else
                            fs.readFile(nameMin, 'utf8', callback);
                });
            }
        }

        return ret;
    }

    function getDir() {
        var dir;

        if (os.tmpdir) {
            dir     = os.tmpdir();
            dir     += '/minify';

            if (!WIN)
                dir += '/' + process.getuid();

            dir     += '/';
        }

        return dir;
    }

    function makeDir(callback) {
        var ANY_MASK    = 0,
            umask       = process.umask(ANY_MASK);

        mkdirp(MinFolder, function(error) {
            process.umask(umask);

            if (error && error.code === 'EEXIST')
                callback();
            else
                callback(error);
        });
    }

    function middle(options, req, res, next) {
        var isMinify, dir, is, isFunction,
            name        = req.url,
            isExt       = Util.checkExt(name, ['js', 'css', 'html']);

        Util.checkArgs([options], ['options']);

        is              = options.is;
        dir             = options.dir || './';

        isFunction      = type.function(is);
        name            = path.join(dir, name);

        if (isFunction)
            isMinify    = is();
        else
            isMinify    = is || type.undefined(is);

        if (!isExt || !isMinify)
            next();
        else
            minify(name, {
                log         : options.log,
                returnName  : true
            }, function(error, name) {
                if (error)
                    next();
                else
                    ponse.sendFile({
                        request: req,
                        response: res,
                        name: name,
                        gzip: true,
                        cache:true,
                    });
            });
    }

    /**
     * function minificate js,css and html files
     *
     * @param files     -   js, css or html file path
     * @param options   -   object contain main options
     */
    function optimize(file, options, callback) {
        if (!callback)
            callback = options;

        Util.checkArgs(arguments, ['file', 'callback']);

        makeDir(function(error) {
            var name, basename, msg,
                islog   = options.log,
                isObj   = type.object(file);

            if (error)
                log(error, islog);

            if (isObj)
                name    = Object.keys(file)[0];
            else
                name    = file;

            basename    = path.basename(name);
            msg         = 'minify: reading file ' + basename + '...';

            log(msg, islog);

            fs.readFile(name, 'utf8', function(error, data) {
                if (error)
                    callback(error);
                else
                    onDataRead(file, data, options, callback);
            });
        });
    }

   /**
    * Processing of files
    * @param fileData {name, data}
    */
    function onDataRead(filename, data, options, callback) {
        var ext, minFileName,
            readFilesCount  = 0,
            isLog           = options.log,
            returnName      = options.returnName,
            basename        = path.basename(filename);

        log('minify: file ' + basename + ' read', isLog);

        ext         = path.extname(filename);
        minFileName = getName(filename, ext);

        optimizeData({
            ext : ext,
            data: data
        }, function(error, data) {
            if (error)
                callback(error);
            else
                Util.exec.if(ext !== '.css', function(error, optimizedData) {
                    var isStr   = type.string(optimizedData);

                    if (isStr)
                        data    = optimizedData;

                    ++readFilesCount;

                    writeFile(minFileName, data, isLog, function(dataMin) {
                        if (returnName)
                            callback(null, minFileName);
                        else
                            callback(null, dataMin);
                        });
                    }, function(callback) {
                        var img = getModule('img');
                        img.optimize(filename, data, callback);
                    });
            });
    }

    /**
     * function get name of file in min folder
     *
     * @param name
     * @param ext
     */
    function getName(name, ext) {
        var ret, minFileName;

        if (type.string(name)) {
            if (!ext)
                ext         = path.extname(name);

            minFileName = crypto.createHash('sha1')
                .update(name)
                .digest('hex') + ext;

            ret = MinFolder + minFileName;
        }

        return ret;
    }

    /*
     * Функция записывает файла
     * и выводит ошибку или сообщает,
     * что файл успешно записан
     */
    function writeFile(name, data, isLog, callback) {
        fs.writeFile(name, data, function(error) {
            var basename = path.basename(name),
                msg = 'minify: file ' + basename + ' written...';

            log(error || msg, isLog);

            Util.exec(callback, data);
        });
    }

    function log(msg, isLog) {
        if (isLog)
            Util.log(msg);
    }

})();
<commit_msg>feature(minify) "Supported file types" -> "File type not supported"<commit_after>(function() {
    'use strict';

    var DIR         = __dirname + '/',
        os          = require('os'),
        crypto      = require('crypto'),
        fs          = require('fs'),
        path        = require('path'),

        mkdirp      = require('mkdirp'),
        ischanged   = require('ischanged'),
        Util        = require('util-io'),
        type        = Util.type,
        ponse       = require('ponse'),

        WIN         = process.platform === 'win32',

        ERROR_MSG   = 'File type "{{ ext }}" not supported.',

        MinFolder   = getDir() || DIR + 'min/';

    module.exports  = minify;

    function getModule(name) {
        return require(DIR + name);
    }

    function optimizeData(params, callback) {
        var p   = params,
            ext = p.ext.slice(1);

        getModule(ext)(p.data, callback);
    }

    function minify(name, options, callback) {
        var isChanged, isExist, ret, ext, is,
            EXT         = ['js', 'html', 'css'],
            isObject    = type.object(name),
            exec        = Util.exec,
            nameMin     = getName(name);

        if (!callback)
            callback = options;

        if (!options && !callback)
            ret = middle.bind(null, name);
        else if (isObject) {
            optimizeData(name, callback);
        } else {
            ext         = path.extname(name).slice(1);
            is          = ~EXT.indexOf(ext);

            if (!is) {
                callback(Error(Util.render(ERROR_MSG, {
                    ext: ext
                })));
            } else {
                isChanged   = exec.with(ischanged, name),
                isExist     = exec.with(fs.lstat, nameMin);

                exec.parallel([isChanged, isExist], function(error, changed, exists) {
                    if (changed || !exists)
                        optimize(name, options, callback);
                    else
                        if (options.returnName)
                            callback(null, nameMin);
                        else
                            fs.readFile(nameMin, 'utf8', callback);
                });
            }
        }

        return ret;
    }

    function getDir() {
        var dir;

        if (os.tmpdir) {
            dir     = os.tmpdir();
            dir     += '/minify';

            if (!WIN)
                dir += '/' + process.getuid();

            dir     += '/';
        }

        return dir;
    }

    function makeDir(callback) {
        var ANY_MASK    = 0,
            umask       = process.umask(ANY_MASK);

        mkdirp(MinFolder, function(error) {
            process.umask(umask);

            if (error && error.code === 'EEXIST')
                callback();
            else
                callback(error);
        });
    }

    function middle(options, req, res, next) {
        var isMinify, dir, is, isFunction,
            name        = req.url,
            isExt       = Util.checkExt(name, ['js', 'css', 'html']);

        Util.checkArgs([options], ['options']);

        is              = options.is;
        dir             = options.dir || './';

        isFunction      = type.function(is);
        name            = path.join(dir, name);

        if (isFunction)
            isMinify    = is();
        else
            isMinify    = is || type.undefined(is);

        if (!isExt || !isMinify)
            next();
        else
            minify(name, {
                log         : options.log,
                returnName  : true
            }, function(error, name) {
                if (error)
                    next();
                else
                    ponse.sendFile({
                        request: req,
                        response: res,
                        name: name,
                        gzip: true,
                        cache:true,
                    });
            });
    }

    /**
     * function minificate js,css and html files
     *
     * @param files     -   js, css or html file path
     * @param options   -   object contain main options
     */
    function optimize(file, options, callback) {
        if (!callback)
            callback = options;

        Util.checkArgs(arguments, ['file', 'callback']);

        makeDir(function(error) {
            var name, basename, msg,
                islog   = options.log,
                isObj   = type.object(file);

            if (error)
                log(error, islog);

            if (isObj)
                name    = Object.keys(file)[0];
            else
                name    = file;

            basename    = path.basename(name);
            msg         = 'minify: reading file ' + basename + '...';

            log(msg, islog);

            fs.readFile(name, 'utf8', function(error, data) {
                if (error)
                    callback(error);
                else
                    onDataRead(file, data, options, callback);
            });
        });
    }

   /**
    * Processing of files
    * @param fileData {name, data}
    */
    function onDataRead(filename, data, options, callback) {
        var ext, minFileName,
            readFilesCount  = 0,
            isLog           = options.log,
            returnName      = options.returnName,
            basename        = path.basename(filename);

        log('minify: file ' + basename + ' read', isLog);

        ext         = path.extname(filename);
        minFileName = getName(filename, ext);

        optimizeData({
            ext : ext,
            data: data
        }, function(error, data) {
            if (error)
                callback(error);
            else
                Util.exec.if(ext !== '.css', function(error, optimizedData) {
                    var isStr   = type.string(optimizedData);

                    if (isStr)
                        data    = optimizedData;

                    ++readFilesCount;

                    writeFile(minFileName, data, isLog, function(dataMin) {
                        if (returnName)
                            callback(null, minFileName);
                        else
                            callback(null, dataMin);
                        });
                    }, function(callback) {
                        var img = getModule('img');
                        img.optimize(filename, data, callback);
                    });
            });
    }

    /**
     * function get name of file in min folder
     *
     * @param name
     * @param ext
     */
    function getName(name, ext) {
        var ret, minFileName;

        if (type.string(name)) {
            if (!ext)
                ext         = path.extname(name);

            minFileName = crypto.createHash('sha1')
                .update(name)
                .digest('hex') + ext;

            ret = MinFolder + minFileName;
        }

        return ret;
    }

    /*
     * Функция записывает файла
     * и выводит ошибку или сообщает,
     * что файл успешно записан
     */
    function writeFile(name, data, isLog, callback) {
        fs.writeFile(name, data, function(error) {
            var basename = path.basename(name),
                msg = 'minify: file ' + basename + ' written...';

            log(error || msg, isLog);

            Util.exec(callback, data);
        });
    }

    function log(msg, isLog) {
        if (isLog)
            Util.log(msg);
    }

})();
<|endoftext|>


<commit_before>import Phaser from 'phaser'

export default class extends Phaser.Sprite {

    constructor ({ game, id, type, x, y, keys }) {
        let data = game.cache.getJSON("players")[type]
        let orientation = id == 0 ? "right" : "left"

        super(game, x, y, data["sprite"]["asset"], data["sprite"][orientation]["frame"])

        this.health = 100
        this._isActive = false
        this.id = id
        this.orientation = orientation
        this.keys = keys
        this.data = data

        this.speed = data["physics"]["speed"]
        this.game.physics.arcade.enable(this)
        this.body.gravity.y = data["physics"]["gravity"];
        this.body.collideWorldBounds = true

        this.anchor.setTo(0.5)
        this.animations.add('left', data["sprite"]["left"]["animation"], 10, true)
        this.animations.add('right', data["sprite"]["right"]["animation"], 10, true)

        this.weaponSound = this.game.add.audio(data["sfx"]["shoot"]);
        this.hitSound = this.game.add.audio(data["sfx"]["hurt"]);

        this.weapon = this._addWeapon()

        this.fireIsPressed = false
        this.upIsPressed = false
        this.leftIsPressed = false
        this.rightIsPressed = false
    }

    create () {
    }

    update () {
        if (this.leftIsPressed) {
            if (this._isActive) {
                this.body.velocity.x = -(this.speed)
                this.animations.play('left')
                this.orientation = 'left'
            }
        } else if (this.rightIsPressed) {
            if (this._isActive) {
                this.body.velocity.x = this.speed
                this.animations.play('right')
                this.orientation = 'right'
            }
        } else {
            this.animations.stop();
            this.body.velocity.x = 0;
            this.frame = this.data["sprite"][this.orientation]["frame"]
        }
    }

    activate () {
        this._isActive = true
    }

    deactivate () {
        this._isActive = false
    }

    getWeapon () {
        return this.weapon
    }

    getHealth () {
        return this.health
    }

    decreaseHealth (amount) {
        if (this._isActive)
            this.health = Math.max(0, this.health - amount)

        return this.health
    }

    playHitSound () {
        this.hitSound.play()
    }

    keyDown(char) {
        switch (char["code"]) {
            case this.keys["fire"]:
                if (!this.fireIsPressed) {
                    this.fireIsPressed = true;

                    if (this._isActive) {
                        this.weapon.fireAngle = this.orientation == 'left' ? Phaser.ANGLE_LEFT : Phaser.ANGLE_RIGHT

                        if (this.weapon.fire()) {
                            this.weaponSound.play()
                        }
                    }
                }

                break;

            case this.keys["up"]:
                if (!this.upIsPressed) {
                    this.upIsPressed = true;

                    if (this._isActive && this.body.touching.down) {
                        this.body.velocity.y = -(this.data["physics"]["jump"]);
                    }
                }
                break;

            case this.keys["left"]:
                this.leftIsPressed = true
                break;

            case this.keys["right"]:
                this.rightIsPressed = true
                break;
        }
    }

    keyUp(char) {
        switch (char["code"]) {
            case this.keys["fire"]:
                this.fireIsPressed = false;
                break;

            case this.keys["up"]:
                this.upIsPressed = false;
                break;

            case this.keys["left"]:
                this.leftIsPressed = false
                break;

            case this.keys["right"]:
                this.rightIsPressed = false
                break;
        }
    }

    _addWeapon () {
        let data = this.data["weapon"];
        let weapon = this.game.add.weapon(data["max"], data["asset"])

        weapon.bulletKillType = Phaser.Weapon.KILL_WORLD_BOUNDS
        weapon.bulletSpeed = data["speed"]
        weapon.fireRate = data["rate"]
        weapon.trackSprite(this, 0, 0)

        return weapon;
    }
}
<commit_msg>added player animation stop on deactivation<commit_after>import Phaser from 'phaser'

export default class extends Phaser.Sprite {

    constructor ({ game, id, type, x, y, keys }) {
        let data = game.cache.getJSON("players")[type]
        let orientation = id == 0 ? "right" : "left"

        super(game, x, y, data["sprite"]["asset"], data["sprite"][orientation]["frame"])

        this.health = 100
        this._isActive = false
        this.id = id
        this.orientation = orientation
        this.keys = keys
        this.data = data

        this.speed = data["physics"]["speed"]
        this.game.physics.arcade.enable(this)
        this.body.gravity.y = data["physics"]["gravity"];
        this.body.collideWorldBounds = true

        this.anchor.setTo(0.5)
        this.animations.add('left', data["sprite"]["left"]["animation"], 10, true)
        this.animations.add('right', data["sprite"]["right"]["animation"], 10, true)

        this.weaponSound = this.game.add.audio(data["sfx"]["shoot"]);
        this.hitSound = this.game.add.audio(data["sfx"]["hurt"]);

        this.weapon = this._addWeapon()

        this.fireIsPressed = false
        this.upIsPressed = false
        this.leftIsPressed = false
        this.rightIsPressed = false
    }

    create () {
    }

    update () {
        if (this.leftIsPressed) {
            if (this._isActive) {
                this.body.velocity.x = -(this.speed)
                this.animations.play('left')
                this.orientation = 'left'
            }
        } else if (this.rightIsPressed) {
            if (this._isActive) {
                this.body.velocity.x = this.speed
                this.animations.play('right')
                this.orientation = 'right'
            }
        } else {
            this._stopAnimation()
        }
    }

    activate () {
        this._isActive = true
    }

    deactivate () {
        this._isActive = false
        this._stopAnimation()
    }

    getWeapon () {
        return this.weapon
    }

    getHealth () {
        return this.health
    }

    decreaseHealth (amount) {
        if (this._isActive)
            this.health = Math.max(0, this.health - amount)

        return this.health
    }

    playHitSound () {
        this.hitSound.play()
    }

    keyDown(char) {
        switch (char["code"]) {
            case this.keys["fire"]:
                if (!this.fireIsPressed) {
                    this.fireIsPressed = true;

                    if (this._isActive) {
                        this.weapon.fireAngle = this.orientation == 'left' ? Phaser.ANGLE_LEFT : Phaser.ANGLE_RIGHT

                        if (this.weapon.fire()) {
                            this.weaponSound.play()
                        }
                    }
                }

                break;

            case this.keys["up"]:
                if (!this.upIsPressed) {
                    this.upIsPressed = true;

                    if (this._isActive && this.body.touching.down) {
                        this.body.velocity.y = -(this.data["physics"]["jump"]);
                    }
                }
                break;

            case this.keys["left"]:
                this.leftIsPressed = true
                break;

            case this.keys["right"]:
                this.rightIsPressed = true
                break;
        }
    }

    keyUp(char) {
        switch (char["code"]) {
            case this.keys["fire"]:
                this.fireIsPressed = false;
                break;

            case this.keys["up"]:
                this.upIsPressed = false;
                break;

            case this.keys["left"]:
                this.leftIsPressed = false
                break;

            case this.keys["right"]:
                this.rightIsPressed = false
                break;
        }
    }

    _addWeapon () {
        let data = this.data["weapon"];
        let weapon = this.game.add.weapon(data["max"], data["asset"])

        weapon.bulletKillType = Phaser.Weapon.KILL_WORLD_BOUNDS
        weapon.bulletSpeed = data["speed"]
        weapon.fireRate = data["rate"]
        weapon.trackSprite(this, 0, 0)

        return weapon;
    }

    _stopAnimation () {
        this.animations.stop();
        this.body.velocity.x = 0;
        this.frame = this.data["sprite"][this.orientation]["frame"]
    }
}
<|endoftext|>


<commit_before>(function(window, angular, undefined){
  'use strict';

  var module = angular.module('nsPopover', []);
  var $el = angular.element;
  var isDef = angular.isDefined;
  var forEach = angular.forEach;

  /**
   * Extends the destination objec 'dst' by copying all of the properties from the 'src' object(s)
   * to 'dst'. Multiple src objects could be specified. 'undefined' values are not copied.
   *
   * @param {Object} dst The destination object.
   * @param {Object} src The spurce object.
   * @returns {Object} Reference to 'dst'.
   */
  var extend_ = function extend(dst, src) {
    forEach(arguments, function(obj) {
      if (obj !== src) {
        forEach(obj, function(value, key) {
          if (isDef(value)) {
            dst[key] = value;
          }
        });
      }
    });
  };

  module.directive('nsPopover', function($timeout, $templateCache, $q, $http, $compile, $document) {
    return {
      restrict: 'A',
      link: function(scope, elm, attrs) {
        var options = {
          template: attrs.nsPopoverTemplate,
          theme: attrs.nsPopoverTheme || 'ns-popover-default-theme',
          plain: attrs.nsPopoverPlain,
          trigger: attrs.nsPopoverTrigger || 'click',
          container: attrs.nsPopoverContainer,
          placement: attrs.nsPopoverPlacement || 'bottom|left'
        };

        var timeoutId_ = {};

        var $container = $el(options.container);
        if (!$container.length) {
          $container = $document.find('body');
        }

        var $popover = $el('

');
        var placement_;
        var align_;

        var match = options.placement
          .match(/^(top|bottom|left|right)$|((top|bottom)\|(center|left|right)+)|((left|right)\|(center|top|bottom)+)/);

        if (!match) {
          throw new Error('"' + options.placement + '" is not a valid placement or has a invalid combination of placements.');
        }

        placement_ = match[3] || match[1];
        align_ = match[4] || match[2] || 'center';

        $q.when(loadTemplate(options.template, options.plain)).then(function(template) {
          template = angular.isString(template) ?
            template :
            template.data && angular.isString(template.data) ?
              template.data :
              '';

          $popover.html(template);

          if (options.theme) {
            $popover.addClass(options.theme);
          }

          $timeout(function() {
            $compile($popover)(scope);
          });

          scope.$on('$destroy', function() {
            $popover.remove();
          });

          $popover
            .css('position', 'absolute')
            .css('display', 'none');

          $container.append($popover);
        });

        elm.on(options.trigger, function(e) {
          e.preventDefault();

          $timeout.cancel(timeoutId_);

          $popover.css('display', 'block');

          // position the popover accordingly to the defined placement around the
          // |elm|.
          move($popover, placement_, align_, elm[0].getBoundingClientRect());

          // Hide the popover without delay on click events.
          $popover.on('click', function() {
            timeoutId_ = hide($popover, 0);
          });
        });

        elm.on('mouseout', function() {
          timeoutId_ = hide($popover);
        });

        $popover
          .on('mouseout', function(e) {
            timeoutId_ = hide($popover);
          })
          .on('mouseover', function() {
            $timeout.cancel(timeoutId_);
          });

        /**
         * Move the popover to the |placement| position of the object located on the |rect|.
         *
         * @param popover {Object} The popover object to be moved.
         * @param placement {String} The relative position to move the popover - top | bottom | left | right.
         * @param rect {ClientRect} The ClientRect of the object to move the popover around.
         */
        function move(popover, placement, align, rect) {
          var popoverRect = popover[0].getBoundingClientRect();
          var top, left;

          var positionX = function() {
            if (align === 'center') {
              return Math.round(rect.left + rect.width/2 - popoverRect.width/2);
            } else {
              return rect[align];
            }
          };

          var positionY = function() {
            if (align === 'center') {
              return Math.round(rect.top + rect.height/2 - popoverRect.height/2);
            } else {
              return rect[align];
            }
          };

          if (placement === 'top') {
            top = rect.top - popoverRect.height - 1;
            left = positionX();
          } else if (placement === 'right') {
            top = positionY();
            left = rect.right +1;
          } else if (placement === 'bottom') {
            top = rect.bottom + 1;
            left = positionX(align);
          } else if (placement === 'left') {
            top = positionY(align);
            left = rect.left - popoverRect.width - 1;
          }
          popover
            .css('top', top.toString() + 'px')
            .css('left', left.toString() + 'px');
        }

        /**
         * Set the display property of the popover to 'none' after |delay| milliseconds.
         *
         * @param popover {Object} The popover to set the display property.
         * @param delay {Number}  The time (in milliseconds) to wait before set the display property.
         * @returns {Object|promise} A promise returned from the $timeout service that can be used
         *                           to cancel the hiding operation.
         */
        function hide(popover, delay) {
          $timeout.cancel(timeoutId_);

          // delay the hiding operation for 1.5s by default.
          if (!isDef(delay)) {
            delay = 1500;
          }

          return $timeout(function() {
            popover.css('display', 'none');
          }, delay);
        }

        /**
         * Load the given template in the cache if it is not already loaded.
         *
         * @param template The URI of the template to be loaded.
         * @returns {String} A promise that the template will be loaded.
         * @remarks If the template is null or undefined a empty string will be returned.
         */
        function loadTemplate(template, plain) {
          if (!template) {
            return '';
          }

          if (angular.isString(template) && plain) {
            return template;
          }

          return $templateCache.get(template) || $http.get(template, { cache : true });
        }
      }
    };
  });
})(window, window.angular);<commit_msg>Fix a bug that causes the popover to not recognize the left|* and right|* placements<commit_after>(function(window, angular, undefined){
  'use strict';

  var module = angular.module('nsPopover', []);
  var $el = angular.element;
  var isDef = angular.isDefined;
  var forEach = angular.forEach;

  /**
   * Extends the destination objec 'dst' by copying all of the properties from the 'src' object(s)
   * to 'dst'. Multiple src objects could be specified. 'undefined' values are not copied.
   *
   * @param {Object} dst The destination object.
   * @param {Object} src The spurce object.
   * @returns {Object} Reference to 'dst'.
   */
  var extend_ = function extend(dst, src) {
    forEach(arguments, function(obj) {
      if (obj !== src) {
        forEach(obj, function(value, key) {
          if (isDef(value)) {
            dst[key] = value;
          }
        });
      }
    });
  };

  module.directive('nsPopover', function($timeout, $templateCache, $q, $http, $compile, $document) {
    return {
      restrict: 'A',
      link: function(scope, elm, attrs) {
        var options = {
          template: attrs.nsPopoverTemplate,
          theme: attrs.nsPopoverTheme || 'ns-popover-default-theme',
          plain: attrs.nsPopoverPlain,
          trigger: attrs.nsPopoverTrigger || 'click',
          container: attrs.nsPopoverContainer,
          placement: attrs.nsPopoverPlacement || 'bottom|left'
        };

        var timeoutId_ = {};

        var $container = $el(options.container);
        if (!$container.length) {
          $container = $document.find('body');
        }

        var $popover = $el('

');
        var placement_;
        var align_;

        var match = options.placement
          .match(/^(top|bottom|left|right)$|((top|bottom)\|(center|left|right)+)|((left|right)\|(center|top|bottom)+)/);

        if (!match) {
          throw new Error('"' + options.placement + '" is not a valid placement or has a invalid combination of placements.');
        }

        placement_ = match[6] || match[3] || match[1];
        align_ = match[8] | match[4] || match[2] || 'center';

        $q.when(loadTemplate(options.template, options.plain)).then(function(template) {
          template = angular.isString(template) ?
            template :
            template.data && angular.isString(template.data) ?
              template.data :
              '';

          $popover.html(template);

          if (options.theme) {
            $popover.addClass(options.theme);
          }

          $timeout(function() {
            $compile($popover)(scope);
          });

          scope.$on('$destroy', function() {
            $popover.remove();
          });

          $popover
            .css('position', 'absolute')
            .css('display', 'none');

          $container.append($popover);
        });

        elm.on(options.trigger, function(e) {
          e.preventDefault();

          $timeout.cancel(timeoutId_);

          $popover.css('display', 'block');

          // position the popover accordingly to the defined placement around the
          // |elm|.
          move($popover, placement_, align_, elm[0].getBoundingClientRect());

          // Hide the popover without delay on click events.
          $popover.on('click', function() {
            timeoutId_ = hide($popover, 0);
          });
        });

        elm.on('mouseout', function() {
          timeoutId_ = hide($popover);
        });

        $popover
          .on('mouseout', function(e) {
            timeoutId_ = hide($popover);
          })
          .on('mouseover', function() {
            $timeout.cancel(timeoutId_);
          });

        /**
         * Move the popover to the |placement| position of the object located on the |rect|.
         *
         * @param popover {Object} The popover object to be moved.
         * @param placement {String} The relative position to move the popover - top | bottom | left | right.
         * @param rect {ClientRect} The ClientRect of the object to move the popover around.
         */
        function move(popover, placement, align, rect) {
          var popoverRect = popover[0].getBoundingClientRect();
          var top, left;

          var positionX = function() {
            if (align === 'center') {
              return Math.round(rect.left + rect.width/2 - popoverRect.width/2);
            } else {
              return rect[align];
            }
          };

          var positionY = function() {
            if (align === 'center') {
              return Math.round(rect.top + rect.height/2 - popoverRect.height/2);
            } else {
              return rect[align];
            }
          };

          if (placement === 'top') {
            top = rect.top - popoverRect.height - 1;
            left = positionX();
          } else if (placement === 'right') {
            top = positionY();
            left = rect.right +1;
          } else if (placement === 'bottom') {
            top = rect.bottom + 1;
            left = positionX(align);
          } else if (placement === 'left') {
            top = positionY(align);
            left = rect.left - popoverRect.width - 1;
          }
          popover
            .css('top', top.toString() + 'px')
            .css('left', left.toString() + 'px');
        }

        /**
         * Set the display property of the popover to 'none' after |delay| milliseconds.
         *
         * @param popover {Object} The popover to set the display property.
         * @param delay {Number}  The time (in milliseconds) to wait before set the display property.
         * @returns {Object|promise} A promise returned from the $timeout service that can be used
         *                           to cancel the hiding operation.
         */
        function hide(popover, delay) {
          $timeout.cancel(timeoutId_);

          // delay the hiding operation for 1.5s by default.
          if (!isDef(delay)) {
            delay = 1500;
          }

          return $timeout(function() {
            popover.css('display', 'none');
          }, delay);
        }

        /**
         * Load the given template in the cache if it is not already loaded.
         *
         * @param template The URI of the template to be loaded.
         * @returns {String} A promise that the template will be loaded.
         * @remarks If the template is null or undefined a empty string will be returned.
         */
        function loadTemplate(template, plain) {
          if (!template) {
            return '';
          }

          if (angular.isString(template) && plain) {
            return template;
          }

          return $templateCache.get(template) || $http.get(template, { cache : true });
        }
      }
    };
  });
})(window, window.angular);<|endoftext|>


<commit_before>"use strict";

var mongoose = require('mongoose');
var _ = require('underscore');

var Schema = mongoose.Schema;
var ObjectId = Schema.ObjectId;

var bbTypeToMongoose = {
    string: function() {
        return {type: String};
    },
    datetime: function() {
        return {type: Date};
    },
    number: function() {
        return {type: Number};
    },
    boolean: function() {
        return {type: Boolean};
    },
    any: function() {
        return {};
    }
};

var bbToMongoose = function(description) {
    if (!description) {
        return null;
    }
    if (Array.isArray(description)) {
        var elem = bbToMongoose(description[0]);
        if (!elem) {
            throw new Error('unknown description in array: ' + description);
        }
        if (typeof description[0] === "object") {
            return [new Schema(elem, {_id: false})];
        } else {
            return [elem];
        }
    } else if (typeof description === "object") {
        var result = Object.keys(description).reduce(function(r, key) {
            var elem = bbToMongoose(description[key]);
            if (!elem) {
                throw new Error('unknown description in object: ' + description);
            }
            r[key] = elem;
            return r;
        }, {});
        return result;
    } else {
        var f = bbTypeToMongoose[description];
        if (f) {
            return f();
        } else {
            throw new Error('unknown description: ' + description);
        }
    }
};

var storageColName = 'storage.files';

exports.models = function(connection, schemas, matchFields) {
    var result = {
        merge: {},
        clinical: {},
        match: {}
    };
    schemas.forEach(function(secName) {
        var mergeColName = secName + 'merges';
        var mergeSchema = new Schema({
            entry_type: String,
            pat_key: String,
            entry: ObjectId,
            record: {
                type: ObjectId,
                ref: storageColName
            },
            merged: Date,
            merge_reason: String,
            archived: Boolean
        });
        result.merge[secName] = connection.model(mergeColName, mergeSchema);

        var matchColName = secName + 'matches';
        var matchSchemaDesc = {
            entry_type: String,
            pat_key: String,
            entry: ObjectId,
            match_entry: ObjectId,
            determination: String //Can be 1) Merged, 2) Added, 3) Ignored.
        };
        var matchFieldDesc = bbToMongoose(matchFields);
        _.extend(matchSchemaDesc, matchFieldDesc);
         var matchSchema = new Schema(matchSchemaDesc);
        result.match[secName] = connection.model(matchColName, matchSchema);

        var desc = {};
        desc.data = {};
        desc.pat_key = String;
        desc.metadata = {
            attribution: [{
                type: ObjectId,
                ref: mergeColName
            }]
        };
        desc.reviewed = Boolean;
        desc.archived = Boolean;
        var schema = new Schema(desc);

        result.clinical[secName] = connection.model(secName, schema);
    });
    return result;
};

exports.storageModel = function(connection) {
    if (!connection) {
        connection = mongoose;
    }
    //GridFS will automatically make this, but a schema is needed for population/refs.
    var schema = new Schema({
        pat_key: String,
        metadata: {
            class: String
        },
        md5: String,
        uploadDate: Date,
        chunkSize: Number,
        length: Number,
        contentType: String,
        filename: String,
    });

    var model = connection.model(storageColName, schema);
    return model;
};
<commit_msg>forgotten file<commit_after>"use strict";

var mongoose = require('mongoose');
var _ = require('underscore');

var Schema = mongoose.Schema;
var ObjectId = Schema.ObjectId;

var bbTypeToMongoose = {
    string: function() {
        return {type: String};
    },
    datetime: function() {
        return {type: Date};
    },
    number: function() {
        return {type: Number};
    },
    boolean: function() {
        return {type: Boolean};
    },
    any: function() {
        return {};
    }
};

var bbToMongoose = function(description) {
    if (!description) {
        return null;
    }
    if (Array.isArray(description)) {
        var elem = bbToMongoose(description[0]);
        if (!elem) {
            throw new Error('unknown description in array: ' + description);
        }
        if (typeof description[0] === "object") {
            return [new Schema(elem, {_id: false})];
        } else {
            return [elem];
        }
    } else if (typeof description === "object") {
        var result = Object.keys(description).reduce(function(r, key) {
            var elem = bbToMongoose(description[key]);
            if (!elem) {
                throw new Error('unknown description in object: ' + description);
            }
            r[key] = elem;
            return r;
        }, {});
        return result;
    } else {
        var f = bbTypeToMongoose[description];
        if (f) {
            return f();
        } else {
            throw new Error('unknown description: ' + description);
        }
    }
};

var storageColName = 'storage.files';

exports.models = function(connection, supportedSections, matchFields) {
    var result = {
        merge: {},
        clinical: {},
        match: {}
    };
    supportedSections.forEach(function(secName) {
        var mergeColName = secName + 'merges';
        var mergeSchema = new Schema({
            entry_type: String,
            pat_key: String,
            entry: ObjectId,
            record: {
                type: ObjectId,
                ref: storageColName
            },
            merged: Date,
            merge_reason: String,
            archived: Boolean
        });
        result.merge[secName] = connection.model(mergeColName, mergeSchema);

        var matchColName = secName + 'matches';
        var matchSchemaDesc = {
            entry_type: String,
            pat_key: String,
            entry: ObjectId,
            match_entry: ObjectId,
            determination: String //Can be 1) Merged, 2) Added, 3) Ignored.
        };
        var matchFieldDesc = bbToMongoose(matchFields);
        _.extend(matchSchemaDesc, matchFieldDesc);
         var matchSchema = new Schema(matchSchemaDesc);
        result.match[secName] = connection.model(matchColName, matchSchema);

        var desc = {};
        desc.data = {};
        desc.pat_key = String;
        desc.metadata = {
            attribution: [{
                type: ObjectId,
                ref: mergeColName
            }]
        };
        desc.reviewed = Boolean;
        desc.archived = Boolean;
        var schema = new Schema(desc);

        result.clinical[secName] = connection.model(secName, schema);
    });
    return result;
};

exports.storageModel = function(connection) {
    if (!connection) {
        connection = mongoose;
    }
    //GridFS will automatically make this, but a schema is needed for population/refs.
    var schema = new Schema({
        pat_key: String,
        metadata: {
            class: String
        },
        md5: String,
        uploadDate: Date,
        chunkSize: Number,
        length: Number,
        contentType: String,
        filename: String,
    });

    var model = connection.model(storageColName, schema);
    return model;
};
<|endoftext|>


<commit_before>import webpack from 'webpack'
import cssnano from 'cssnano'
import HtmlWebpackPlugin from 'html-webpack-plugin'
import ExtractTextPlugin from 'extract-text-webpack-plugin'
import PurifyCssPlugin from 'purifycss-webpack-plugin'
import config from '../config'
import _debug from 'debug'

const debug = _debug('app:webpack:config')
const paths = config.utils_paths
const {__DEV__, __PROD__, __TEST__} = config.globals

debug('Create configuration.')
const webpackConfig = {
  name: 'client',
  target: 'web',
  devtool: config.compiler_devtool,
  resolve: {
    root: paths.base(config.dir_client),
    extensions: ['', '.js', '.jsx']
  },
  module: {}
}
// ------------------------------------
// Entry Points
// ------------------------------------
const APP_ENTRY_PATH = paths.base(config.dir_client) + '/index.jsx'

webpackConfig.entry = {
  app: __DEV__
    ? [APP_ENTRY_PATH, `webpack-hot-middleware/client?path=${config.compiler_public_path}__webpack_hmr`]
    : [APP_ENTRY_PATH],
  vendor: config.compiler_vendor
}

// ------------------------------------
// Bundle Output
// ------------------------------------
webpackConfig.output = {
  filename: `[name].[${config.compiler_hash_type}].js`,
  chunkFilename: '[chunkhash].js',
  path: paths.base(config.dir_dist),
  publicPath: config.compiler_public_path
}

// ------------------------------------
// Plugins
// ------------------------------------
if (__DEV__ || __TEST__) {
  webpackConfig.plugins = [
    new webpack.DefinePlugin(config.globals),
    new HtmlWebpackPlugin({
      template: paths.client('index.html'),
      hash: false,
      favicon: paths.client('static/favicon.ico'),
      filename: 'index.html',
      inject: 'body',
      minify: {
        collapseWhitespace: true
      }
    })
  ]
} else if (__PROD__) {
  webpackConfig.plugins = [
    new webpack.DefinePlugin(config.globals),
    new HtmlWebpackPlugin({
      title: 'Dictybase stock center',
      template: paths.client('index.ejs'),
      inject: false,
      hash: false,
      favicon: paths.client('static/favicon.ico'),
      base: process.env.BASENAME || '/',
      minify: {
        collapseWhitespace: true
      }
    })
  ]
}

if (__DEV__) {
  debug('Enable plugins for live development (HMR, NoErrors).')
  webpackConfig.plugins.push(
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NoErrorsPlugin()
  )
} else if (__PROD__) {
  debug('Enable plugins for production (OccurenceOrder, Dedupe & UglifyJS).')
  webpackConfig.plugins.push(
    new webpack.optimize.OccurrenceOrderPlugin(),
    new webpack.optimize.DedupePlugin(),
    new webpack.optimize.UglifyJsPlugin({
      compress: {
        drop_console: true,
        unused: true,
        dead_code: true,
        warnings: false
      }
    })
  )
}

// Don't split bundles during testing, since we only want import one bundle
if (!__TEST__) {
  webpackConfig.plugins.push(new webpack.optimize.CommonsChunkPlugin({
    names: ['vendor'],
    minChunks: Infinity
  }))
}

// ------------------------------------
// Pre-Loaders
// ------------------------------------
webpackConfig.module.preLoaders = [{
  test: /\.(js|jsx)$/,
  loader: 'eslint',
  exclude: /node_modules/
}]

webpackConfig.eslint = {
  configFile: paths.base('.eslintrc'),
  emitWarning: __DEV__
}

// ------------------------------------
// Loaders
// ------------------------------------
// JavaScript / JSON
webpackConfig.module.loaders = [{
  test: /\.(js|jsx)$/,
  exclude: /node_modules/,
  loader: 'babel',
  query: {
    cacheDirectory: true,
    plugins: ['transform-runtime', 'transform-decorators-legacy'],
    presets: __DEV__
      ? ['es2015', 'react', 'stage-0', 'react-hmre']
      : ['es2015', 'react', 'stage-0']
  }
},
{
  test: /\.json$/,
  loader: 'json'
},
{
  test: /\.(js|jsx)$/,
  include: /dicty-react-components/,
  loader: 'babel',
  query: {
    cacheDirectory: true,
    plugins: ['transform-runtime', 'transform-decorators-legacy'],
    presets: __DEV__
      ? ['es2015', 'react', 'stage-0', 'react-hmre']
      : ['es2015', 'react', 'stage-0']
  }
}
]

// Styles
const cssLoader = !config.compiler_css_modules
  ? 'css?sourceMap'
  : [
    'css?modules',
    'sourceMap',
    'importLoaders=1',
    'localIdentName=[name]__[local]___[hash:base64:5]'
  ].join('&')

webpackConfig.module.loaders.push({
  test: /\.scss$/,
  include: /src/,
  loaders: [
    'style',
    cssLoader,
    'postcss',
    'sass?sourceMap'
  ]
})

webpackConfig.module.loaders.push({
  test: /\.css$/,
  include: /src/,
  loaders: [
    'style',
    cssLoader,
    'postcss'
  ]
})

// Don't treat global SCSS as modules
webpackConfig.module.loaders.push({
  test: /\.scss$/,
  exclude: /src/,
  loaders: [
    'style',
    'css?sourceMap',
    'postcss',
    'sass?sourceMap'
  ]
})

// Don't treat global, third-party CSS as modules
webpackConfig.module.loaders.push({
  test: /\.css$/,
  exclude: /src/,
  loaders: [
    'style',
    'css?sourceMap',
    'postcss'
  ]
})

webpackConfig.sassLoader = {
  includePaths: paths.client('styles')
}

webpackConfig.postcss = [
  cssnano({
    sourcemap: true,
    autoprefixer: {
      add: true,
      remove: true,
      browsers: ['last 2 versions']
    },
    safe: true,
    discardComments: {
      removeAll: true
    }
  })
]

// File loaders
/* eslint-disable */
webpackConfig.module.loaders.push(
  { test: /\.woff(\?.*)?$/,  loader: 'url?prefix=fonts/&name=[path][name].[ext]&limit=10000&mimetype=application/font-woff' },
  { test: /\.woff2(\?.*)?$/, loader: 'url?prefix=fonts/&name=[path][name].[ext]&limit=10000&mimetype=application/font-woff2' },
  { test: /\.otf(\?.*)?$/,   loader: 'file?prefix=fonts/&name=[path][name].[ext]&limit=10000&mimetype=font/opentype' },
  { test: /\.ttf(\?.*)?$/,   loader: 'url?prefix=fonts/&name=[path][name].[ext]&limit=10000&mimetype=application/octet-stream' },
  { test: /\.eot(\?.*)?$/,   loader: 'file?prefix=fonts/&name=[path][name].[ext]' },
  { test: /\.svg(\?.*)?$/,   loader: 'url?prefix=fonts/&name=[path][name].[ext]&limit=10000&mimetype=image/svg+xml' },
  { test: /\.(png|jpg)$/,    loader: 'url?limit=8192' }
)
/* eslint-enable */

// ------------------------------------
// Finalize Configuration
// ------------------------------------
// when we don't know the public path (we know it only when HMR is enabled [in development]) we
// need to use the extractTextPlugin to fix this issue:
// http://stackoverflow.com/questions/34133808/webpack-ots-parsing-error-loading-fonts/34133809#34133809
if (!__DEV__) {
  debug('Apply ExtractTextPlugin to CSS loaders.')
  webpackConfig.module.loaders.filter(loader =>
    loader.loaders && loader.loaders.find(name => /css/.test(name.split('?')[0]))
  ).forEach(loader => {
    const [first, ...rest] = loader.loaders
    loader.loader = ExtractTextPlugin.extract(first, rest.join('!'))
    delete loader.loaders
  })

  webpackConfig.plugins.push(
    new ExtractTextPlugin('[name].[contenthash].css', {
      allChunks: true
    })
  )

  webpackConfig.plugins.push(
      new PurifyCssPlugin({
          basePath: paths.base(config.dir_client),
          paths: ['src/styles', 'dist']
      })
  )
}

export default webpackConfig
<commit_msg>resolve css files. needed to import dicty header<commit_after>import webpack from 'webpack'
import cssnano from 'cssnano'
import HtmlWebpackPlugin from 'html-webpack-plugin'
import ExtractTextPlugin from 'extract-text-webpack-plugin'
import PurifyCssPlugin from 'purifycss-webpack-plugin'
import config from '../config'
import _debug from 'debug'

const debug = _debug('app:webpack:config')
const paths = config.utils_paths
const {__DEV__, __PROD__, __TEST__} = config.globals

debug('Create configuration.')
const webpackConfig = {
  name: 'client',
  target: 'web',
  devtool: config.compiler_devtool,
  resolve: {
    root: paths.base(config.dir_client),
    extensions: ['', '.js', '.jsx', '.css']
  },
  module: {}
}
// ------------------------------------
// Entry Points
// ------------------------------------
const APP_ENTRY_PATH = paths.base(config.dir_client) + '/index.jsx'

webpackConfig.entry = {
  app: __DEV__
    ? [APP_ENTRY_PATH, `webpack-hot-middleware/client?path=${config.compiler_public_path}__webpack_hmr`]
    : [APP_ENTRY_PATH],
  vendor: config.compiler_vendor
}

// ------------------------------------
// Bundle Output
// ------------------------------------
webpackConfig.output = {
  filename: `[name].[${config.compiler_hash_type}].js`,
  chunkFilename: '[chunkhash].js',
  path: paths.base(config.dir_dist),
  publicPath: config.compiler_public_path
}

// ------------------------------------
// Plugins
// ------------------------------------
if (__DEV__ || __TEST__) {
  webpackConfig.plugins = [
    new webpack.DefinePlugin(config.globals),
    new HtmlWebpackPlugin({
      template: paths.client('index.html'),
      hash: false,
      favicon: paths.client('static/favicon.ico'),
      filename: 'index.html',
      inject: 'body',
      minify: {
        collapseWhitespace: true
      }
    })
  ]
} else if (__PROD__) {
  webpackConfig.plugins = [
    new webpack.DefinePlugin(config.globals),
    new HtmlWebpackPlugin({
      title: 'Dictybase stock center',
      template: paths.client('index.ejs'),
      inject: false,
      hash: false,
      favicon: paths.client('static/favicon.ico'),
      base: process.env.BASENAME || '/',
      minify: {
        collapseWhitespace: true
      }
    })
  ]
}

if (__DEV__) {
  debug('Enable plugins for live development (HMR, NoErrors).')
  webpackConfig.plugins.push(
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NoErrorsPlugin()
  )
} else if (__PROD__) {
  debug('Enable plugins for production (OccurenceOrder, Dedupe & UglifyJS).')
  webpackConfig.plugins.push(
    new webpack.optimize.OccurrenceOrderPlugin(),
    new webpack.optimize.DedupePlugin(),
    new webpack.optimize.UglifyJsPlugin({
      compress: {
        drop_console: true,
        unused: true,
        dead_code: true,
        warnings: false
      }
    })
  )
}

// Don't split bundles during testing, since we only want import one bundle
if (!__TEST__) {
  webpackConfig.plugins.push(new webpack.optimize.CommonsChunkPlugin({
    names: ['vendor'],
    minChunks: Infinity
  }))
}

// ------------------------------------
// Pre-Loaders
// ------------------------------------
webpackConfig.module.preLoaders = [{
  test: /\.(js|jsx)$/,
  loader: 'eslint',
  exclude: /node_modules/
}]

webpackConfig.eslint = {
  configFile: paths.base('.eslintrc'),
  emitWarning: __DEV__
}

// ------------------------------------
// Loaders
// ------------------------------------
// JavaScript / JSON
webpackConfig.module.loaders = [{
  test: /\.(js|jsx)$/,
  exclude: /node_modules/,
  loader: 'babel',
  query: {
    cacheDirectory: true,
    plugins: ['transform-runtime', 'transform-decorators-legacy'],
    presets: __DEV__
      ? ['es2015', 'react', 'stage-0', 'react-hmre']
      : ['es2015', 'react', 'stage-0']
  }
},
{
  test: /\.json$/,
  loader: 'json'
},
{
  test: /\.(js|jsx)$/,
  include: /dicty-react-components/,
  loader: 'babel',
  query: {
    cacheDirectory: true,
    plugins: ['transform-runtime', 'transform-decorators-legacy'],
    presets: __DEV__
      ? ['es2015', 'react', 'stage-0', 'react-hmre']
      : ['es2015', 'react', 'stage-0']
  }
}
]

// Styles
const cssLoader = !config.compiler_css_modules
  ? 'css?sourceMap'
  : [
    'css?modules',
    'sourceMap',
    'importLoaders=1',
    'localIdentName=[name]__[local]___[hash:base64:5]'
  ].join('&')

webpackConfig.module.loaders.push({
  test: /\.scss$/,
  include: /src/,
  loaders: [
    'style',
    cssLoader,
    'postcss',
    'sass?sourceMap'
  ]
})

webpackConfig.module.loaders.push({
  test: /\.css$/,
  include: /src/,
  loaders: [
    'style',
    cssLoader,
    'postcss'
  ]
})

// Don't treat global SCSS as modules
webpackConfig.module.loaders.push({
  test: /\.scss$/,
  exclude: /src/,
  loaders: [
    'style',
    'css?sourceMap',
    'postcss',
    'sass?sourceMap'
  ]
})

// Don't treat global, third-party CSS as modules
webpackConfig.module.loaders.push({
  test: /\.css$/,
  exclude: /src/,
  loaders: [
    'style',
    'css?sourceMap',
    'postcss'
  ]
})

webpackConfig.sassLoader = {
  includePaths: paths.client('styles')
}

webpackConfig.postcss = [
  cssnano({
    sourcemap: true,
    autoprefixer: {
      add: true,
      remove: true,
      browsers: ['last 2 versions']
    },
    safe: true,
    discardComments: {
      removeAll: true
    }
  })
]

// File loaders
/* eslint-disable */
webpackConfig.module.loaders.push(
  { test: /\.woff(\?.*)?$/,  loader: 'url?prefix=fonts/&name=[path][name].[ext]&limit=10000&mimetype=application/font-woff' },
  { test: /\.woff2(\?.*)?$/, loader: 'url?prefix=fonts/&name=[path][name].[ext]&limit=10000&mimetype=application/font-woff2' },
  { test: /\.otf(\?.*)?$/,   loader: 'file?prefix=fonts/&name=[path][name].[ext]&limit=10000&mimetype=font/opentype' },
  { test: /\.ttf(\?.*)?$/,   loader: 'url?prefix=fonts/&name=[path][name].[ext]&limit=10000&mimetype=application/octet-stream' },
  { test: /\.eot(\?.*)?$/,   loader: 'file?prefix=fonts/&name=[path][name].[ext]' },
  { test: /\.svg(\?.*)?$/,   loader: 'url?prefix=fonts/&name=[path][name].[ext]&limit=10000&mimetype=image/svg+xml' },
  { test: /\.(png|jpg)$/,    loader: 'url?limit=8192' }
)
/* eslint-enable */

// ------------------------------------
// Finalize Configuration
// ------------------------------------
// when we don't know the public path (we know it only when HMR is enabled [in development]) we
// need to use the extractTextPlugin to fix this issue:
// http://stackoverflow.com/questions/34133808/webpack-ots-parsing-error-loading-fonts/34133809#34133809
if (!__DEV__) {
  debug('Apply ExtractTextPlugin to CSS loaders.')
  webpackConfig.module.loaders.filter(loader =>
    loader.loaders && loader.loaders.find(name => /css/.test(name.split('?')[0]))
  ).forEach(loader => {
    const [first, ...rest] = loader.loaders
    loader.loader = ExtractTextPlugin.extract(first, rest.join('!'))
    delete loader.loaders
  })

  webpackConfig.plugins.push(
    new ExtractTextPlugin('[name].[contenthash].css', {
      allChunks: true
    })
  )

  webpackConfig.plugins.push(
      new PurifyCssPlugin({
          basePath: paths.base(config.dir_client),
          paths: ['src/styles', 'dist']
      })
  )
}

export default webpackConfig
<|endoftext|>