<commit_before>/*
 Rabbitmq wrapper for promise based connection

 */
const amqp = require('amqplib/callback_api');
let exchange = '';
let exchangeFanout = '';
let channel;
let connection;

const connect = (config) => {
    return new Promise((resolve, reject) => {
        try {
            exchange = config.exchange;
            exchangeFanout = config.exchange + ".fanout";
            amqp.connect(config.url,  (err, conn) => {
                connection = conn;
                if (err) {
                    console.error("[AMQP]", err);
                    reject(err);
                }
                console.log("[AMQP] connected");

                conn.on("error", (err) => {
                    throw err;
                });
                conn.on("close", (err) => {
                    throw err;
                });

                conn.createConfirmChannel(function (err, ch) {
                    console.log("Connected to rabbit");
                    channel = ch;
                    channel.assertExchange(exchange, 'direct', {durable: true});
                    channel.assertExchange(exchangeFanout, 'fanout', {durable: true});
                    resolve(conn);
                });
            });
        } catch (e) {
            reject(e.message);
            console.error("[AMQP] connect", e.message);
        }
    });
};

const publish = (msg, key) => {
    if(typeof msg === 'object') {
        // Json object, must be stringified
        msg = JSON.stringify(msg);
    }
    return new Promise(function(resolve, reject) {
        try {
            channel.publish(exchange, key, new Buffer(msg), {persistent: true}, function (err, ok) {
                    if (err !== null) {
                        reject(err);
                        console.warn(' [*] Message nacked');
                    } else {
                        console.log(' [*] Message acked');
                        resolve("Message sendt");
                    }
                }
            );
        } catch (e) {
            reject(e.message);
            console.error("[AMQP] publish", e.message);
        }
    });
};

// Egen variant for å sende array med (msg,key)-par.
// Kan da sende til forskjellige routing keys per msg.
const publishEvents = (events) => {
    if (!Array.isArray(events))
    {
        let event = events;
        events = [];
        events.push(event);
    }

    return Promise.all(events.map((event) => new Promise((resolve, reject) => {
        try {
            let msg = event.msg;
            if(typeof event.msg === 'object') {
                // Json object, must be stringified
                msg = JSON.stringify(event.msg);
            }
            channel.publish(exchange, event.key, new Buffer(msg), {persistent: true}, function (err, ok) {
                    if (err !== null) {
                        reject(err);
                        console.warn(' [*] Message nacked');
                    } else {
                        console.log(' [*] Message acked');
                        resolve("Message sendt");
                    }
                }
            );
        } catch (e) {
            reject(e.message);
            console.error("[AMQP] publish", e.message);
        }
    })));
};

const fanout = (sendMsg,key) => {
    return new Promise(function(resolve, reject) {
        try {
            if (typeof sendMsg !== 'string') {
                sendMsg = JSON.stringify(sendMsg);
            }
            channel.publish(exchangeFanout, key, new Buffer(sendMsg), {persistent: true}, function (err, ok) {
                    if (err !== null) {
                        reject(err);
                        console.warn(' [*] Message nacked');
                    } else {
                        console.log(' [*] Message acked');
                        resolve("Message sendt");
                    }
                }
            );
        } catch (e) {
            reject(e.message);
            console.error("[AMQP] publish", e.message);
        }
    });
};

const RPC = (queue,service,sendMsg) =>{
    return new Promise(function(resolve, reject) {
        try {
            connection.createChannel((err, ch) => {
                ch.assertQueue('', {exclusive: true,autoDelete:true}, (err, q) => {
                    const corr = generateUuid();
                    ch.consume(q.queue, (msg) => {
                        if (msg.properties.correlationId === corr) {
                            if (msg.content.toString() === 'Unknown service') {
                                reject(new Error("Unknown service: " + service));
                            }
                            else if (typeof msg.content === 'object') {
                                let parsed = JSON.parse(msg.content.toString());

                                // Check for errors
                                if (parsed.errors) {
                                    // This is the correct way to throw Error from promise
                                    reject(new Error(parsed.errors[0].message));
                                }
                                else
                                {
                                    resolve(parsed);
                                }
                            }
                            ch.close();
                        }
                    }, {noAck: true});

                    if (typeof sendMsg !== 'string') {
                        sendMsg = JSON.stringify(sendMsg);
                    }
                    ch.sendToQueue("RPC." + queue,
                        new Buffer(sendMsg),
                        {correlationId: corr, replyTo: q.queue, type: service}
                    );
                });
            })
        } catch(e) {
            console.error(e);
            reject(e.message);
        }
    });
};

// Egen variant for å sende array med (msg,service)-par.
// Kan da sende til forskjellige services per msg.
const RPCMany = (queue, services) => {
    return Promise.all(services.map((service) => new Promise((resolve, reject) => {
        try {
            connection.createChannel((err, ch) => {
                ch.assertQueue('', {exclusive: true,autoDelete:true}, (err, q) => {
                    const corr = generateUuid();
                    ch.consume(q.queue, (msg) => {
                        if (msg.properties.correlationId === corr) {
                            if (msg.content.toString() === 'Unknown service') {
                                reject(new Error("Unknown service: " + service.service));
                            }
                            else if (typeof msg.content === 'object') {
                                let parsed = JSON.parse(msg.content.toString());

                                // Check for errors
                                if (parsed.errors) {
                                    // This is the correct way to throw Error from promise
                                    reject(new Error(parsed.errors[0].message));
                                }
                                else
                                {
                                    resolve(parsed);
                                }
                            }
                            ch.close();
                        }
                    }, {noAck: true});

                    if (typeof service.msg !== 'string') {
                        service.msg = JSON.stringify(service.msg);
                    }
                    ch.sendToQueue("RPC." + queue,
                        new Buffer(service.msg),
                        {correlationId: corr, replyTo: q.queue, type: service.service}
                    );
                });
            })
        } catch(e) {
            console.error(e);
            reject(e.message);
        }
    })));
};

const generateUuid = () => {
    return Math.random().toString() +
        Math.random().toString() +
        Math.random().toString();
};

const RPCListen = (queue,cb, ...args) => {
    const q = "RPC." + queue;
    channel.assertQueue(q, {durable: false});
    channel.prefetch(1);
    console.log(' [x] Awaiting RPC requests on queue:' + q);
    channel.consume(q, (msg) => {
        (function(msg){
            new Promise((resolve, reject) => {
                let services = cb();
                if (services[msg.properties.type] === undefined) {
                    channel.sendToQueue(msg.properties.replyTo,
                        new Buffer("Unknown service"),
                        {correlationId: msg.properties.correlationId});
                    channel.ack(msg);
                }
                else {
                    services[msg.properties.type](msg.content.toString(), resolve, args);
                }
            }).then((sendMsg) => {
                if (typeof sendMsg !== 'string') {
                    sendMsg = JSON.stringify(sendMsg);
                }

                channel.sendToQueue(msg.properties.replyTo,
                    new Buffer(sendMsg),
                    {correlationId: msg.properties.correlationId});
                channel.ack(msg);
            }).catch((msg) => {
                console.error(msg);
            });
        }(msg))
    });
};
const listen = (queue,key,cb) => {
    channel.assertQueue(queue, {durable:true},function(err, q) {
        console.log(' [*] Waiting for data on'+q.queue);
        channel.bindQueue(q.queue, exchange, key);
        //  channel.bindQueue(q.queue, exchangeFanout, key);
        //Fetch 5 messages in a time and wait for ack on those
        channel.prefetch(5);
        channel.consume(q.queue, (msg) => {
            cb(() => {channel.ack(msg);},() => {channel.nack(msg);},msg.content.toString());
        }, {noAck: false});
    });
}

// Set up services (event receivers) server-side
// Use triggers before and after service execution
const useEvents = (queue, services, beforeTrigger, afterTrigger, ...params) => {
    channel.assertQueue(queue, {durable: true});

    // Bind all routing keys
    Object.keys(services.EventTaskMapping).forEach(function(key)
    {
        channel.bindQueue(queue, exchange, key);
    });
    channel.prefetch(5);
    console.log(' [x] Awaiting events on queue:' + queue);
    channel.consume(queue, (msg) => {
        (function(msg){
            if (services.EventTaskMapping[msg.fields.routingKey] === undefined) {
                channel.sendToQueue(msg.properties.replyTo,
                    new Buffer("Unknown event"),
                    {correlationId: msg.properties.correlationId});
            }
            else {

                let task = services.EventTaskMapping[msg.fields.routingKey];
                let service = services.TaskServiceMapping[task];

                if (beforeTrigger)
                {
                    Promise.resolve(beforeTrigger.resolve(task, msg.content.toString(),...params))
                        .then((sendMsg) => {
                        })
                        .catch((err) => console.error(err));
                }

                Promise.resolve(service.resolve(msg.content.toString(), msg.fields.routingKey, ...params))
                    .then((sendMsg) => {
                        if (!sendMsg) {
                            throw new Error("Internal service must return some value");
                        }
                        if (typeof sendMsg !== 'string') {
                            sendMsg = JSON.stringify(sendMsg);
                        }
                        if (afterTrigger)
                        {
                            Promise.resolve(afterTrigger.resolve(task, msg.content.toString(), sendMsg, ...params))
                                .then((sendMsg) => {
                                })
                                .catch((err) => console.error(err));
                        }

                        channel.sendToQueue(msg.properties.replyTo,
                            new Buffer(sendMsg),
                            {correlationId: msg.properties.correlationId});
                    })
                    .catch((err) => {
                        console.log(err);

                        // Returns error message
                        let errors = { errors: [
                                { message: err.message,
                                    detail: err
                                }]};

                        if (afterTrigger)
                        {
                            Promise.resolve(afterTrigger.resolve(task, msg.content.toString(), JSON.stringify(errors), ...params))
                                .then((sendMsg) => {
                                })
                                .catch((err) => console.error(err));
                        }

                        channel.sendToQueue(msg.properties.replyTo,
                            new Buffer(JSON.stringify(errors)),
                            {correlationId: msg.properties.correlationId});
                    });
            }
        }(msg))
        channel.ack(msg);
    });
};
const listenFanout = (queue,key,cb) => {
    channel.assertQueue(queue, {durable:true},function(err, q) {
        console.log(' [*] Waiting for data on'+q.queue);

        channel.bindQueue(q.queue, exchangeFanout, key);
        //Fetch 5 messages in a time and wait for ack on those
        channel.prefetch(5);
        channel.consume(q.queue, function(msg) {
            cb(() => {channel.ack(msg)},msg.content.toString());
        }, {noAck: false});
    });
};

// Set up services (rpc receivers) server-side
// Use triggers before and after service execution
const useRPC = (queue,services, beforeTrigger, afterTrigger, ...params) => {
    const q = "RPC." + queue;
    channel.assertQueue(q, {durable: false});
    channel.prefetch(1);
    console.log(' [x] Awaiting RPC requests on queue:' + q);
    channel.consume(q, (msg) => {
        (function(msg){
            if (services[msg.properties.type] === undefined) {
                channel.sendToQueue(msg.properties.replyTo,
                    new Buffer("Unknown service"),
                    {correlationId: msg.properties.correlationId});
            }
            else {
                if (beforeTrigger)
                {
                    Promise.resolve(beforeTrigger.resolve(msg.properties.type, msg.content.toString(),...params))
                        .then((sendMsg) => {
                        })
                        .catch((err) => console.error(err));
                }

                Promise.resolve(services[msg.properties.type].resolve(msg.content.toString(),
                    msg.properties.type,
                    ...params))
                    .then((sendMsg) => {
                        if (!sendMsg) {
                            throw new Error("Internal service must return some value");
                        }
                        if (typeof sendMsg !== 'string') {
                            sendMsg = JSON.stringify(sendMsg);
                        }
                        if (afterTrigger)
                        {
                            Promise.resolve(afterTrigger.resolve(msg.properties.type, msg.content.toString(), sendMsg, ...params))
                                .then((sendMsg) => {
                                })
                                .catch((err) => console.error(err));
                        }

                        channel.sendToQueue(msg.properties.replyTo,
                            new Buffer(sendMsg),
                            {correlationId: msg.properties.correlationId});
                    })
                    .catch((err) => {
                        console.log(err);

                        // Returns error message
                        let errors = { errors: [
                                { message: err.message,
                                    detail: err
                                }]};

                        if (afterTrigger)
                        {
                            Promise.resolve(afterTrigger.resolve(msg.properties.type, msg.content.toString(), JSON.stringify(errors), ...params))
                                .then((sendMsg) => {
                                })
                                .catch((err) => console.error(err));
                        }

                        channel.sendToQueue(msg.properties.replyTo,
                            new Buffer(JSON.stringify(errors)),
                            {correlationId: msg.properties.correlationId});
                    });
            }
        }(msg))
        channel.ack(msg);
    });
};

module.exports = {
    connect:connect,
    publish:publish,
    publishEvents:publishEvents,
    listen:listen,
    RPCListen:RPCListen,
    RPC:RPC,
    RPCMany:RPCMany,
    fanout:fanout,
    listenFanout:listenFanout,
    disconnect: (cb) => {
        if(connection) {
            connection.close(() => {
                cb();
            })
        } else {cb();}},
    useRPC:useRPC,
    useEvents:useEvents
};<commit_msg>Fixed bug<commit_after>/*
 Rabbitmq wrapper for promise based connection

 */
const amqp = require('amqplib/callback_api');
let exchange = '';
let exchangeFanout = '';
let channel;
let connection;

const connect = (config) => {
    return new Promise((resolve, reject) => {
        try {
            exchange = config.exchange;
            exchangeFanout = config.exchange + ".fanout";
            amqp.connect(config.url,  (err, conn) => {
                connection = conn;
                if (err) {
                    console.error("[AMQP]", err);
                    reject(err);
                }
                console.log("[AMQP] connected");

                conn.on("error", (err) => {
                    throw err;
                });
                conn.on("close", (err) => {
                    throw err;
                });

                conn.createConfirmChannel(function (err, ch) {
                    console.log("Connected to rabbit");
                    channel = ch;
                    channel.assertExchange(exchange, 'direct', {durable: true});
                    channel.assertExchange(exchangeFanout, 'fanout', {durable: true});
                    resolve(conn);
                });
            });
        } catch (e) {
            reject(e.message);
            console.error("[AMQP] connect", e.message);
        }
    });
};

const publish = (msg, key) => {
    if(typeof msg === 'object') {
        // Json object, must be stringified
        msg = JSON.stringify(msg);
    }
    return new Promise(function(resolve, reject) {
        try {
            channel.publish(exchange, key, new Buffer(msg), {persistent: true}, function (err, ok) {
                    if (err !== null) {
                        reject(err);
                        console.warn(' [*] Message nacked');
                    } else {
                        console.log(' [*] Message acked');
                        resolve("Message sendt");
                    }
                }
            );
        } catch (e) {
            reject(e.message);
            console.error("[AMQP] publish", e.message);
        }
    });
};

// Egen variant for å sende array med (msg,key)-par.
// Kan da sende til forskjellige routing keys per msg.
const publishEvents = (events) => {
    if (!Array.isArray(events))
    {
        let event = events;
        events = [];
        events.push(event);
    }

    return Promise.all(events.map((event) => new Promise((resolve, reject) => {
        try {
            let key = event.key;
            if(typeof event === 'object') {
                // Json object, must be stringified
                event = JSON.stringify(event);
            }
            channel.publish(exchange, key, new Buffer(event), {persistent: true}, function (err, ok) {
                    if (err !== null) {
                        reject(err);
                        console.warn(' [*] Message nacked');
                    } else {
                        console.log(' [*] Message acked');
                        resolve("Message sendt");
                    }
                }
            );
        } catch (e) {
            reject(e.message);
            console.error("[AMQP] publish", e.message);
        }
    })));
};

const fanout = (sendMsg,key) => {
    return new Promise(function(resolve, reject) {
        try {
            if (typeof sendMsg !== 'string') {
                sendMsg = JSON.stringify(sendMsg);
            }
            channel.publish(exchangeFanout, key, new Buffer(sendMsg), {persistent: true}, function (err, ok) {
                    if (err !== null) {
                        reject(err);
                        console.warn(' [*] Message nacked');
                    } else {
                        console.log(' [*] Message acked');
                        resolve("Message sendt");
                    }
                }
            );
        } catch (e) {
            reject(e.message);
            console.error("[AMQP] publish", e.message);
        }
    });
};

const RPC = (queue,service,sendMsg) =>{
    return new Promise(function(resolve, reject) {
        try {
            connection.createChannel((err, ch) => {
                ch.assertQueue('', {exclusive: true,autoDelete:true}, (err, q) => {
                    const corr = generateUuid();
                    ch.consume(q.queue, (msg) => {
                        if (msg.properties.correlationId === corr) {
                            if (msg.content.toString() === 'Unknown service') {
                                reject(new Error("Unknown service: " + service));
                            }
                            else if (typeof msg.content === 'object') {
                                let parsed = JSON.parse(msg.content.toString());

                                // Check for errors
                                if (parsed.errors) {
                                    // This is the correct way to throw Error from promise
                                    reject(new Error(parsed.errors[0].message));
                                }
                                else
                                {
                                    resolve(parsed);
                                }
                            }
                            ch.close();
                        }
                    }, {noAck: true});

                    if (typeof sendMsg !== 'string') {
                        sendMsg = JSON.stringify(sendMsg);
                    }
                    ch.sendToQueue("RPC." + queue,
                        new Buffer(sendMsg),
                        {correlationId: corr, replyTo: q.queue, type: service}
                    );
                });
            })
        } catch(e) {
            console.error(e);
            reject(e.message);
        }
    });
};

// Egen variant for å sende array med (msg,service)-par.
// Kan da sende til forskjellige services per msg.
const RPCMany = (queue, services) => {
    return Promise.all(services.map((service) => new Promise((resolve, reject) => {
        try {
            connection.createChannel((err, ch) => {
                ch.assertQueue('', {exclusive: true,autoDelete:true}, (err, q) => {
                    const corr = generateUuid();
                    ch.consume(q.queue, (msg) => {
                        if (msg.properties.correlationId === corr) {
                            if (msg.content.toString() === 'Unknown service') {
                                reject(new Error("Unknown service: " + service.service));
                            }
                            else if (typeof msg.content === 'object') {
                                let parsed = JSON.parse(msg.content.toString());

                                // Check for errors
                                if (parsed.errors) {
                                    // This is the correct way to throw Error from promise
                                    reject(new Error(parsed.errors[0].message));
                                }
                                else
                                {
                                    resolve(parsed);
                                }
                            }
                            ch.close();
                        }
                    }, {noAck: true});

                    if (typeof service.msg !== 'string') {
                        service.msg = JSON.stringify(service.msg);
                    }
                    ch.sendToQueue("RPC." + queue,
                        new Buffer(service.msg),
                        {correlationId: corr, replyTo: q.queue, type: service.service}
                    );
                });
            })
        } catch(e) {
            console.error(e);
            reject(e.message);
        }
    })));
};

const generateUuid = () => {
    return Math.random().toString() +
        Math.random().toString() +
        Math.random().toString();
};

const RPCListen = (queue,cb, ...args) => {
    const q = "RPC." + queue;
    channel.assertQueue(q, {durable: false});
    channel.prefetch(1);
    console.log(' [x] Awaiting RPC requests on queue:' + q);
    channel.consume(q, (msg) => {
        (function(msg){
            new Promise((resolve, reject) => {
                let services = cb();
                if (services[msg.properties.type] === undefined) {
                    channel.sendToQueue(msg.properties.replyTo,
                        new Buffer("Unknown service"),
                        {correlationId: msg.properties.correlationId});
                    channel.ack(msg);
                }
                else {
                    services[msg.properties.type](msg.content.toString(), resolve, args);
                }
            }).then((sendMsg) => {
                if (typeof sendMsg !== 'string') {
                    sendMsg = JSON.stringify(sendMsg);
                }

                channel.sendToQueue(msg.properties.replyTo,
                    new Buffer(sendMsg),
                    {correlationId: msg.properties.correlationId});
                channel.ack(msg);
            }).catch((msg) => {
                console.error(msg);
            });
        }(msg))
    });
};
const listen = (queue,key,cb) => {
    channel.assertQueue(queue, {durable:true},function(err, q) {
        console.log(' [*] Waiting for data on'+q.queue);
        channel.bindQueue(q.queue, exchange, key);
        //  channel.bindQueue(q.queue, exchangeFanout, key);
        //Fetch 5 messages in a time and wait for ack on those
        channel.prefetch(5);
        channel.consume(q.queue, (msg) => {
            cb(() => {channel.ack(msg);},() => {channel.nack(msg);},msg.content.toString());
        }, {noAck: false});
    });
}

// Set up services (event receivers) server-side
// Use triggers before and after service execution
const useEvents = (queue, services, beforeTrigger, afterTrigger, ...params) => {
    channel.assertQueue(queue, {durable: true});

    // Bind all routing keys
    Object.keys(services.EventTaskMapping).forEach(function(key)
    {
        channel.bindQueue(queue, exchange, key);
    });
    channel.prefetch(5);
    console.log(' [x] Awaiting events on queue:' + queue);
    channel.consume(queue, (msg) => {
        (function(msg){
            if (services.EventTaskMapping[msg.fields.routingKey] === undefined) {
                channel.sendToQueue(msg.properties.replyTo,
                    new Buffer("Unknown event"),
                    {correlationId: msg.properties.correlationId});
            }
            else {

                let task = services.EventTaskMapping[msg.fields.routingKey];
                let service = services.TaskServiceMapping[task];

                if (beforeTrigger)
                {
                    Promise.resolve(beforeTrigger.resolve(task, msg.content.toString(),...params))
                        .then((sendMsg) => {
                        })
                        .catch((err) => console.error(err));
                }

                Promise.resolve(service.resolve(msg.content.toString(), msg.fields.routingKey, ...params))
                    .then((sendMsg) => {
                        if (!sendMsg) {
                            throw new Error("Internal service must return some value");
                        }
                        if (typeof sendMsg !== 'string') {
                            sendMsg = JSON.stringify(sendMsg);
                        }
                        if (afterTrigger)
                        {
                            Promise.resolve(afterTrigger.resolve(task, msg.content.toString(), sendMsg, ...params))
                                .then((sendMsg) => {
                                })
                                .catch((err) => console.error(err));
                        }

                        channel.sendToQueue(msg.properties.replyTo,
                            new Buffer(sendMsg),
                            {correlationId: msg.properties.correlationId});
                    })
                    .catch((err) => {
                        console.log(err);

                        // Returns error message
                        let errors = { errors: [
                                { message: err.message,
                                    detail: err
                                }]};

                        if (afterTrigger)
                        {
                            Promise.resolve(afterTrigger.resolve(task, msg.content.toString(), JSON.stringify(errors), ...params))
                                .then((sendMsg) => {
                                })
                                .catch((err) => console.error(err));
                        }

                        channel.sendToQueue(msg.properties.replyTo,
                            new Buffer(JSON.stringify(errors)),
                            {correlationId: msg.properties.correlationId});
                    });
            }
        }(msg))
        channel.ack(msg);
    });
};
const listenFanout = (queue,key,cb) => {
    channel.assertQueue(queue, {durable:true},function(err, q) {
        console.log(' [*] Waiting for data on'+q.queue);

        channel.bindQueue(q.queue, exchangeFanout, key);
        //Fetch 5 messages in a time and wait for ack on those
        channel.prefetch(5);
        channel.consume(q.queue, function(msg) {
            cb(() => {channel.ack(msg)},msg.content.toString());
        }, {noAck: false});
    });
};

// Set up services (rpc receivers) server-side
// Use triggers before and after service execution
const useRPC = (queue,services, beforeTrigger, afterTrigger, ...params) => {
    const q = "RPC." + queue;
    channel.assertQueue(q, {durable: false});
    channel.prefetch(1);
    console.log(' [x] Awaiting RPC requests on queue:' + q);
    channel.consume(q, (msg) => {
        (function(msg){
            if (services[msg.properties.type] === undefined) {
                channel.sendToQueue(msg.properties.replyTo,
                    new Buffer("Unknown service"),
                    {correlationId: msg.properties.correlationId});
            }
            else {
                if (beforeTrigger)
                {
                    Promise.resolve(beforeTrigger.resolve(msg.properties.type, msg.content.toString(),...params))
                        .then((sendMsg) => {
                        })
                        .catch((err) => console.error(err));
                }

                Promise.resolve(services[msg.properties.type].resolve(msg.content.toString(),
                    msg.properties.type,
                    ...params))
                    .then((sendMsg) => {
                        if (!sendMsg) {
                            throw new Error("Internal service must return some value");
                        }
                        if (typeof sendMsg !== 'string') {
                            sendMsg = JSON.stringify(sendMsg);
                        }
                        if (afterTrigger)
                        {
                            Promise.resolve(afterTrigger.resolve(msg.properties.type, msg.content.toString(), sendMsg, ...params))
                                .then((sendMsg) => {
                                })
                                .catch((err) => console.error(err));
                        }

                        channel.sendToQueue(msg.properties.replyTo,
                            new Buffer(sendMsg),
                            {correlationId: msg.properties.correlationId});
                    })
                    .catch((err) => {
                        console.log(err);

                        // Returns error message
                        let errors = { errors: [
                                { message: err.message,
                                    detail: err
                                }]};

                        if (afterTrigger)
                        {
                            Promise.resolve(afterTrigger.resolve(msg.properties.type, msg.content.toString(), JSON.stringify(errors), ...params))
                                .then((sendMsg) => {
                                })
                                .catch((err) => console.error(err));
                        }

                        channel.sendToQueue(msg.properties.replyTo,
                            new Buffer(JSON.stringify(errors)),
                            {correlationId: msg.properties.correlationId});
                    });
            }
        }(msg))
        channel.ack(msg);
    });
};

module.exports = {
    connect:connect,
    publish:publish,
    publishEvents:publishEvents,
    listen:listen,
    RPCListen:RPCListen,
    RPC:RPC,
    RPCMany:RPCMany,
    fanout:fanout,
    listenFanout:listenFanout,
    disconnect: (cb) => {
        if(connection) {
            connection.close(() => {
                cb();
            })
        } else {cb();}},
    useRPC:useRPC,
    useEvents:useEvents
};<|endoftext|>


<commit_before>import babel from 'rollup-plugin-babel';
import commonjs from 'rollup-plugin-commonjs';
import compiler from '@ampproject/rollup-plugin-closure-compiler';
import nodeResolve from 'rollup-plugin-node-resolve';
import replace from 'rollup-plugin-replace';
import { terser } from 'rollup-plugin-terser';

import { name } from './package.json';

export default [
  {
    input: 'modules/index.js',
    output: {
      file: `build/${name}.development.js`,
      format: 'esm',
      sourcemap: true
    },
    external: ['@babel/runtime/helpers/esm/extends'],
    plugins: [
      babel({
        exclude: /node_modules/,
        runtimeHelpers: true,
        plugins: [['@babel/transform-runtime', { useESModules: true }]]
      }),
      replace({ 'process.env.NODE_ENV': JSON.stringify('development') })
    ]
  },
  {
    input: 'modules/index.js',
    output: {
      file: `build/${name}.production.js`,
      format: 'esm',
      sourcemap: true
    },
    external: ['@babel/runtime/helpers/esm/extends'],
    plugins: [
      babel({
        exclude: /node_modules/,
        runtimeHelpers: true,
        plugins: [['@babel/transform-runtime', { useESModules: true }]]
      }),
      replace({ 'process.env.NODE_ENV': JSON.stringify('production') }),
      compiler({
        compilation_level: 'ADVANCED_OPTIMIZATIONS'
      }),
      terser()
    ]
  },

  // UMD
  {
    input: 'modules/index.js',
    output: {
      file: `build/umd/${name}.development.js`,
      format: 'umd',
      sourcemap: true,
      name: 'HistoryLibrary'
    },
    plugins: [
      babel({
        exclude: /node_modules/,
        runtimeHelpers: true,
        plugins: [['@babel/transform-runtime', { useESModules: true }]]
      }),
      nodeResolve(),
      commonjs({ include: /node_modules/ }),
      replace({ 'process.env.NODE_ENV': JSON.stringify('development') })
    ]
  },
  {
    input: 'modules/index.js',
    output: {
      file: `build/umd/${name}.production.js`,
      format: 'umd',
      sourcemap: true,
      name: 'HistoryLibrary'
    },
    plugins: [
      babel({
        exclude: /node_modules/,
        runtimeHelpers: true,
        plugins: [['@babel/transform-runtime', { useESModules: true }]]
      }),
      nodeResolve(),
      commonjs({ include: /node_modules/ }),
      replace({ 'process.env.NODE_ENV': JSON.stringify('production') }),
      compiler({
        compilation_level: 'ADVANCED_OPTIMIZATIONS'
      }),
      terser()
    ]
  }
];
<commit_msg>Use simple optimizations instead of advanced<commit_after>import babel from 'rollup-plugin-babel';
import commonjs from 'rollup-plugin-commonjs';
import compiler from '@ampproject/rollup-plugin-closure-compiler';
import nodeResolve from 'rollup-plugin-node-resolve';
import replace from 'rollup-plugin-replace';
import { terser } from 'rollup-plugin-terser';

import { name } from './package.json';

export default [
  {
    input: 'modules/index.js',
    output: {
      file: `build/${name}.development.js`,
      format: 'esm',
      sourcemap: true
    },
    external: ['@babel/runtime/helpers/esm/extends'],
    plugins: [
      babel({
        exclude: /node_modules/,
        runtimeHelpers: true,
        plugins: [['@babel/transform-runtime', { useESModules: true }]]
      }),
      replace({ 'process.env.NODE_ENV': JSON.stringify('development') })
    ]
  },
  {
    input: 'modules/index.js',
    output: {
      file: `build/${name}.production.js`,
      format: 'esm',
      sourcemap: true
    },
    external: ['@babel/runtime/helpers/esm/extends'],
    plugins: [
      babel({
        exclude: /node_modules/,
        runtimeHelpers: true,
        plugins: [['@babel/transform-runtime', { useESModules: true }]]
      }),
      replace({ 'process.env.NODE_ENV': JSON.stringify('production') }),
      compiler({
        compilation_level: 'ADVANCED_OPTIMIZATIONS'
      }),
      terser()
    ]
  },

  // UMD
  {
    input: 'modules/index.js',
    output: {
      file: `build/umd/${name}.development.js`,
      format: 'umd',
      sourcemap: true,
      name: 'HistoryLibrary'
    },
    plugins: [
      babel({
        exclude: /node_modules/,
        runtimeHelpers: true,
        plugins: [['@babel/transform-runtime', { useESModules: true }]]
      }),
      nodeResolve(),
      commonjs({ include: /node_modules/ }),
      replace({ 'process.env.NODE_ENV': JSON.stringify('development') })
    ]
  },
  {
    input: 'modules/index.js',
    output: {
      file: `build/umd/${name}.production.js`,
      format: 'umd',
      sourcemap: true,
      name: 'HistoryLibrary'
    },
    plugins: [
      babel({
        exclude: /node_modules/,
        runtimeHelpers: true,
        plugins: [['@babel/transform-runtime', { useESModules: true }]]
      }),
      nodeResolve(),
      commonjs({ include: /node_modules/ }),
      replace({ 'process.env.NODE_ENV': JSON.stringify('production') }),
      compiler({
        compilation_level: 'SIMPLE_OPTIMIZATIONS'
      }),
      terser()
    ]
  }
];
<|endoftext|>


<commit_before>import React from 'react';
import ReactDOM from 'react-dom';
import { DragDropContext as dragDropContext } from 'react-dnd';
import HTML5Backend from 'react-dnd-html5-backend';

import DraggableCell from './cell/draggable-cell';
import CellCreator from './cell/cell-creator';
import { executeCell, focusNextCell, moveCell } from '../actions';

import Immutable from 'immutable';

class Notebook extends React.Component {
  static propTypes = {
    channels: React.PropTypes.any,
    displayOrder: React.PropTypes.instanceOf(Immutable.List),
    notebook: React.PropTypes.any,
    transforms: React.PropTypes.instanceOf(Immutable.Map),
    focusedCell: React.PropTypes.string,
  };

  static contextTypes = {
    dispatch: React.PropTypes.func,
  };

  static childContextTypes = {
    channels: React.PropTypes.object,
  };

  constructor() {
    super();
    this.createCellElement = this.createCellElement.bind(this);
    this.keyDown = this.keyDown.bind(this);
    this.moveCell = this.moveCell.bind(this);
  }

  getChildContext() {
    return {
      channels: this.props.channels,
    };
  }

  componentWillMount() {
    require('codemirror/mode/markdown/markdown');

    const lang = this.props.notebook.getIn(['metadata', 'kernelspec', 'language']);
    if (!lang) {
      return;
    }
    // HACK: This should give you the heeby-jeebies
    // Mostly because lang could be ../../../../whatever
    // This is the notebook though, so hands off
    // We'll want to check for this existing later
    // and any other validation
    require(`codemirror/mode/${lang}/${lang}`);
    // Assume markdown should be required
  }

  componentDidMount() {
    document.addEventListener('keydown', this.keyDown);
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.focusedCell !== this.props.focusedCell) {
      this.resolveScrollPosition(nextProps.focusedCell);
    }
  }

  componentWillUnmount() {
    document.removeEventListener('keydown', this.keyDown);
  }

  resolveScrollPosition(id) {
    const viewportHeight = window.innerHeight;
    const viewportOffset = document.body.scrollTop;

    const focusedCell = ReactDOM.findDOMNode(this.refs[id]);

    if (focusedCell) {
      const cellTop = focusedCell.offsetTop;
      const cellHeight = focusedCell.offsetHeight;

      const belowFold = (cellTop + cellHeight) > (viewportOffset + viewportHeight);
      const aboveFold = cellTop < viewportOffset;

      if (aboveFold) {
        document.body.scrollTop = cellTop;
      }

      if (belowFold) {
        if (cellHeight > viewportHeight) {
          document.body.scrollTop = cellTop;
        } else {
          const offset = viewportHeight - cellHeight;
          document.body.scrollTop = cellTop - offset;
        }
      }
    }
  }

  keyDown(e) {
    if (e.keyCode !== 13) {
      return;
    }

    const shiftXORctrl = (e.shiftKey || e.ctrlKey) && !(e.shiftKey && e.ctrlKey);
    if (!shiftXORctrl) {
      return;
    }

    if (!this.props.focusedCell) {
      return;
    }

    e.preventDefault();

    const cellMap = this.props.notebook.get('cellMap');
    const id = this.props.focusedCell;
    const cell = cellMap.get(id);

    if (e.shiftKey) {
      this.context.dispatch(focusNextCell(this.props.focusedCell));
    }

    this.context.dispatch(
      executeCell(this.props.channels, id, cell.get('source'))
    );
  }

  moveCell(sourceId, destinationId, above) {
    this.context.dispatch(moveCell(sourceId, destinationId, above));
  }

  createCellElement(id) {
    const cellMap = this.props.notebook.get('cellMap');

    return (
      <div
        key={`cell-container-${id}`}
        ref="container"
      >
        <DraggableCell cell={cellMap.get(id)}
          language={this.props.notebook.getIn(['metadata', 'language_info', 'name'])}
          id={id}
          key={id}
          ref={id}
          displayOrder={this.props.displayOrder}
          transforms={this.props.transforms}
          moveCell={this.moveCell}
          focusedCell={this.props.focusedCell}
        />
        <CellCreator key={`creator-${id}`} id={id} above={false} />

);
  }

  render() {
    if (!this.props.notebook) {
      return (

      );
    }
    const cellOrder = this.props.notebook.get('cellOrder');
    return (

        <CellCreator id={cellOrder.get(0, null)} above />
      {
        cellOrder.map(this.createCellElement)
      }

    );
  }
}

export default dragDropContext(HTML5Backend)(Notebook);
<commit_msg>conditional check for code cell type<commit_after>import React from 'react';
import ReactDOM from 'react-dom';
import { DragDropContext as dragDropContext } from 'react-dnd';
import HTML5Backend from 'react-dnd-html5-backend';

import DraggableCell from './cell/draggable-cell';
import CellCreator from './cell/cell-creator';
import { executeCell, focusNextCell, moveCell } from '../actions';

import Immutable from 'immutable';

class Notebook extends React.Component {
  static propTypes = {
    channels: React.PropTypes.any,
    displayOrder: React.PropTypes.instanceOf(Immutable.List),
    notebook: React.PropTypes.any,
    transforms: React.PropTypes.instanceOf(Immutable.Map),
    focusedCell: React.PropTypes.string,
  };

  static contextTypes = {
    dispatch: React.PropTypes.func,
  };

  static childContextTypes = {
    channels: React.PropTypes.object,
  };

  constructor() {
    super();
    this.createCellElement = this.createCellElement.bind(this);
    this.keyDown = this.keyDown.bind(this);
    this.moveCell = this.moveCell.bind(this);
  }

  getChildContext() {
    return {
      channels: this.props.channels,
    };
  }

  componentWillMount() {
    require('codemirror/mode/markdown/markdown');

    const lang = this.props.notebook.getIn(['metadata', 'kernelspec', 'language']);
    if (!lang) {
      return;
    }
    // HACK: This should give you the heeby-jeebies
    // Mostly because lang could be ../../../../whatever
    // This is the notebook though, so hands off
    // We'll want to check for this existing later
    // and any other validation
    require(`codemirror/mode/${lang}/${lang}`);
    // Assume markdown should be required
  }

  componentDidMount() {
    document.addEventListener('keydown', this.keyDown);
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.focusedCell !== this.props.focusedCell) {
      this.resolveScrollPosition(nextProps.focusedCell);
    }
  }

  componentWillUnmount() {
    document.removeEventListener('keydown', this.keyDown);
  }

  resolveScrollPosition(id) {
    const viewportHeight = window.innerHeight;
    const viewportOffset = document.body.scrollTop;

    const focusedCell = ReactDOM.findDOMNode(this.refs[id]);

    if (focusedCell) {
      const cellTop = focusedCell.offsetTop;
      const cellHeight = focusedCell.offsetHeight;

      const belowFold = (cellTop + cellHeight) > (viewportOffset + viewportHeight);
      const aboveFold = cellTop < viewportOffset;

      if (aboveFold) {
        document.body.scrollTop = cellTop;
      }

      if (belowFold) {
        if (cellHeight > viewportHeight) {
          document.body.scrollTop = cellTop;
        } else {
          const offset = viewportHeight - cellHeight;
          document.body.scrollTop = cellTop - offset;
        }
      }
    }
  }

  keyDown(e) {
    if (e.keyCode !== 13) {
      return;
    }

    const shiftXORctrl = (e.shiftKey || e.ctrlKey) && !(e.shiftKey && e.ctrlKey);
    if (!shiftXORctrl) {
      return;
    }

    if (!this.props.focusedCell) {
      return;
    }

    e.preventDefault();

    const cellMap = this.props.notebook.get('cellMap');
    const id = this.props.focusedCell;
    const cell = cellMap.get(id);

    if (e.shiftKey) {
      this.context.dispatch(focusNextCell(this.props.focusedCell));
    }

    if (cell.get('cell_type') === 'code') {
      this.context.dispatch(
        executeCell(this.props.channels, id, cell.get('source'))
      );
    }
  }

  moveCell(sourceId, destinationId, above) {
    this.context.dispatch(moveCell(sourceId, destinationId, above));
  }

  createCellElement(id) {
    const cellMap = this.props.notebook.get('cellMap');

    return (
      <div
        key={`cell-container-${id}`}
        ref="container"
      >
        <DraggableCell cell={cellMap.get(id)}
          language={this.props.notebook.getIn(['metadata', 'language_info', 'name'])}
          id={id}
          key={id}
          ref={id}
          displayOrder={this.props.displayOrder}
          transforms={this.props.transforms}
          moveCell={this.moveCell}
          focusedCell={this.props.focusedCell}
        />
        <CellCreator key={`creator-${id}`} id={id} above={false} />

);
  }

  render() {
    if (!this.props.notebook) {
      return (

      );
    }
    const cellOrder = this.props.notebook.get('cellOrder');
    return (

        <CellCreator id={cellOrder.get(0, null)} above />
      {
        cellOrder.map(this.createCellElement)
      }

    );
  }
}

export default dragDropContext(HTML5Backend)(Notebook);
<|endoftext|>


<commit_before>const path = require('path');
const CSSSplitWebpackPlugin = require('css-split-webpack-plugin').default;

const isDev = process.env.NODE_ENV === 'development';
const usePreact = process.env.REACT_ENV === 'preact';

module.exports = {
  port: 8001,
  source: {
    components: './components',
    docs: './docs',
    changelog: [
      'CHANGELOG.zh-CN.md',
      'CHANGELOG.en-US.md',
    ],
  },
  theme: './site/theme',
  htmlTemplate: './site/theme/static/template.html',
  themeConfig: {
    categoryOrder: {
      设计原则: 2,
      Principles: 2,
    },
    typeOrder: {
      General: 0,
      Layout: 1,
      Navigation: 2,
      'Data Entry': 3,
      'Data Display': 4,
      Feedback: 5,
      Localization: 6,
      Other: 7,
    },
    docVersions: {
      '0.9.x': 'http://09x.ant.design',
      '0.10.x': 'http://010x.ant.design',
      '0.11.x': 'http://011x.ant.design',
      '0.12.x': 'http://012x.ant.design',
      '1.x': 'http://1x.ant.design',
    },
  },
  filePathMapper(filePath) {
    if (filePath === '/index.html') {
      return ['/index.html', '/index-cn.html'];
    }
    if (filePath.endsWith('/index.html')) {
      return [filePath, filePath.replace(/\/index\.html$/, '-cn/index.html')];
    }
    if (filePath !== '/404.html' && filePath !== '/index-cn.html') {
      return [filePath, filePath.replace(/\.html$/, '-cn.html')];
    }
    return filePath;
  },
  doraConfig: {
    verbose: true,
    plugins: ['dora-plugin-upload'],
  },
  webpackConfig(config) {
    config.resolve.alias = {
      'antd/lib': path.join(process.cwd(), 'components'),
      antd: path.join(process.cwd(), 'index'),
      site: path.join(process.cwd(), 'site'),
      'react-router': 'react-router/umd/ReactRouter',
    };

    config.externals = {
      'react-router-dom': 'ReactRouterDOM',
    };

    if (usePreact) {
      config.resolve.alias = {
        ...config.resolve.alias,
        react: 'preact-compat',
        'react-dom': 'preact-compat',
        'create-react-class': 'preact-compat/lib/create-react-class',
        'react-router': 'react-router',
      };
    } else {
      config.externals = {
        ...config.externals,
        react: 'React',
        'react-dom': 'ReactDOM',
      };
    }

    config.babel.plugins.push([
      require.resolve('babel-plugin-transform-runtime'),
      {
        polyfill: false,
        regenerator: true,
      },
    ]);

    config.plugins.push(new CSSSplitWebpackPlugin({ size: 4000 }));

    return config;
  },

  htmlTemplateExtraData: {
    isDev,
    usePreact,
  },
};
<commit_msg>site: update config syntax<commit_after>const path = require('path');
const CSSSplitWebpackPlugin = require('css-split-webpack-plugin').default;

const isDev = process.env.NODE_ENV === 'development';
const usePreact = process.env.REACT_ENV === 'preact';

module.exports = {
  port: 8001,
  source: {
    components: './components',
    docs: './docs',
    changelog: [
      'CHANGELOG.zh-CN.md',
      'CHANGELOG.en-US.md',
    ],
  },
  theme: './site/theme',
  htmlTemplate: './site/theme/static/template.html',
  themeConfig: {
    categoryOrder: {
      设计原则: 2,
      Principles: 2,
    },
    typeOrder: {
      General: 0,
      Layout: 1,
      Navigation: 2,
      'Data Entry': 3,
      'Data Display': 4,
      Feedback: 5,
      Localization: 6,
      Other: 7,
    },
    docVersions: {
      '0.9.x': 'http://09x.ant.design',
      '0.10.x': 'http://010x.ant.design',
      '0.11.x': 'http://011x.ant.design',
      '0.12.x': 'http://012x.ant.design',
      '1.x': 'http://1x.ant.design',
    },
  },
  filePathMapper(filePath) {
    if (filePath === '/index.html') {
      return ['/index.html', '/index-cn.html'];
    }
    if (filePath.endsWith('/index.html')) {
      return [filePath, filePath.replace(/\/index\.html$/, '-cn/index.html')];
    }
    if (filePath !== '/404.html' && filePath !== '/index-cn.html') {
      return [filePath, filePath.replace(/\.html$/, '-cn.html')];
    }
    return filePath;
  },
  doraConfig: {
    verbose: true,
    plugins: ['dora-plugin-upload'],
  },
  webpackConfig(config) {
    config.resolve.alias = {
      'antd/lib': path.join(process.cwd(), 'components'),
      antd: path.join(process.cwd(), 'index'),
      site: path.join(process.cwd(), 'site'),
      'react-router': 'react-router/umd/ReactRouter',
    };

    config.externals = {
      'react-router-dom': 'ReactRouterDOM',
    };

    if (usePreact) {
      config.resolve.alias = Object.assign({}, config.resolve.alias, {
        react: 'preact-compat',
        'react-dom': 'preact-compat',
        'create-react-class': 'preact-compat/lib/create-react-class',
        'react-router': 'react-router',
      });
    } else {
      config.externals = Object.assign({}, config.externals, {
        react: 'React',
        'react-dom': 'ReactDOM',
      });
    }

    config.babel.plugins.push([
      require.resolve('babel-plugin-transform-runtime'),
      {
        polyfill: false,
        regenerator: true,
      },
    ]);

    config.plugins.push(new CSSSplitWebpackPlugin({ size: 4000 }));

    return config;
  },

  htmlTemplateExtraData: {
    isDev,
    usePreact,
  },
};
<|endoftext|>


<commit_before>import babel from 'rollup-plugin-babel';
import { terser } from 'rollup-plugin-terser';
import commonjs from 'rollup-plugin-commonjs';
import resolve from 'rollup-plugin-node-resolve';
import pkg from './package.json';

const NAME = 'Photoswiper';
const COPYRIGHT_YEAR = `2016-${parseInt((new Date()).getFullYear(), 10)}`;

const banner = formatStr => `
/***
 * ${NAME} v${pkg.version}${(formatStr) ? `
 * ${formatStr}` : ''}
 * Copyright ${COPYRIGHT_YEAR} ${pkg.author.name}
 * Licensed under ${pkg.license}
 ***/`;

const terserOpts = {
	output: {
		comments(node, { value, type }) {
			if (type === 'comment2') {
				return /copyright/i.test(value);
			}
			return false;
		},
	},
};

const prod = process.env.NODE_ENV === 'production';

export default [
	// Node.js build
	{
		input: 'src/photoswiper.js',
		external: [
			'tabtrap',
			'lodash.merge',
			'photoswipe',
			'photoswipe/dist/photoswipe-ui-default'
		],
		plugins: [
			babel({
				// override targets to transpile for node 8
				presets: [['airbnb', {
					targets: { node: 8 },
				}]],
			}),
			(prod) ? terser(terserOpts) : null,
		],
		output: {
			file: pkg.main,
			format: 'cjs',
			banner: banner('Built for Node.js'),
		},
	},

	// ES module build
	{
		input: 'src/photoswiper.js',
		plugins: [
			resolve(),
    		commonjs(),
			babel({
				// https://caniuse.com/#feat=es6-module
				presets: [['airbnb', {
					targets: {
						android: 67,
						chromeandroid: 70,
						firefoxandroid: 63,
						ios: 11,
						chrome: 61,
						edge: 16,
						firefox: 60,
						safari: 11,
					},
				}]],
			}),
			(prod) ? terser(terserOpts) : null,
		],
		output: {
			file: pkg.module,
			format: 'esm',
			banner: banner('Built for ES modules'),
		},
	},

	// UMD build
	{
		input: 'src/photoswiper.js',
		plugins: [
			resolve(),
    		commonjs(),
			babel({ presets: ['airbnb'] }),
			(prod) ? terser(terserOpts) : null,
		],
		output: {
			file: pkg.browser,
			name: NAME,
			format: 'umd',
			banner: banner('Built for the browser'),
		},
	},
];
<commit_msg>style: fix linting errors in rollup config<commit_after>import babel from 'rollup-plugin-babel';
import { terser } from 'rollup-plugin-terser';
import commonjs from 'rollup-plugin-commonjs';
import resolve from 'rollup-plugin-node-resolve';
import pkg from './package.json';

const NAME = 'Photoswiper';
const COPYRIGHT_YEAR = `2016-${parseInt((new Date()).getFullYear(), 10)}`;

const banner = formatStr => `
/***
 * ${NAME} v${pkg.version}${(formatStr) ? `
 * ${formatStr}` : ''}
 * Copyright ${COPYRIGHT_YEAR} ${pkg.author.name}
 * Licensed under ${pkg.license}
 ***/`;

const terserOpts = {
	output: {
		comments(node, { value, type }) {
			if (type === 'comment2') {
				return /copyright/i.test(value);
			}
			return false;
		},
	},
};

const prod = process.env.NODE_ENV === 'production';

export default [
	// Node.js build
	{
		input: 'src/photoswiper.js',
		external: [
			'tabtrap',
			'lodash.merge',
			'photoswipe',
			'photoswipe/dist/photoswipe-ui-default',
		],
		plugins: [
			babel({
				// override targets to transpile for node 8
				presets: [['airbnb', {
					targets: { node: 8 },
				}]],
			}),
			(prod) ? terser(terserOpts) : null,
		],
		output: {
			file: pkg.main,
			format: 'cjs',
			banner: banner('Built for Node.js'),
		},
	},

	// ES module build
	{
		input: 'src/photoswiper.js',
		plugins: [
			resolve(),
			commonjs(),
			babel({
				// https://caniuse.com/#feat=es6-module
				presets: [['airbnb', {
					targets: {
						android: 67,
						chromeandroid: 70,
						firefoxandroid: 63,
						ios: 11,
						chrome: 61,
						edge: 16,
						firefox: 60,
						safari: 11,
					},
				}]],
			}),
			(prod) ? terser(terserOpts) : null,
		],
		output: {
			file: pkg.module,
			format: 'esm',
			banner: banner('Built for ES modules'),
		},
	},

	// UMD build
	{
		input: 'src/photoswiper.js',
		plugins: [
			resolve(),
			commonjs(),
			babel({ presets: ['airbnb'] }),
			(prod) ? terser(terserOpts) : null,
		],
		output: {
			file: pkg.browser,
			name: NAME,
			format: 'umd',
			banner: banner('Built for the browser'),
		},
	},
];
<|endoftext|>


<commit_before>function print(board){
    document.write('
');

    _.forEach(board, function(row, key){
        document.write("
");
        _.forEach(row, function(square, k){
            document.write("" + square + "	")

        });
        document.write("
");
    });

    document.write('
');
}

var board = {};
    board.a = {
        'one': '',
        'two': '',
        'three': '',
        'four': '',
        'five': '',
        'six': '',
        'seven': '',
        'eight': ''
    };
    board.b = {
        'one': '',
        'two': '',
        'three': '',
        'four': '',
        'five': '',
        'six': '',
        'seven': '',
        'eight': ''
    };
    board.c = {
        'one': '',
        'two': '',
        'three': '',
        'four': '',
        'five': '',
        'six': '',
        'seven': '',
        'eight': ''
    };
    board.d = {
        'one': '',
        'two': '',
        'three': '',
        'four': '',
        'five': '',
        'six': '',
        'seven': '',
        'eight': ''
    };
    board.e = {
        'one': '',
        'two': '',
        'three': '',
        'four': '',
        'five': '',
        'six': '',
        'seven': '',
        'eight': ''
    };
    board.f = {
        'one': '',
        'two': '',
        'three': '',
        'four': '',
        'five': '',
        'six': '',
        'seven': '',
        'eight': ''
    };
    board.g = {
        'one': '',
        'two': '',
        'three': '',
        'four': '',
        'five': '',
        'six': '',
        'seven': '',
        'eight': ''
    };
    board.h = {
        'one': '',
        'two': '',
        'three': '',
        'four': '',
        'five': '',
        'six': '',
        'seven': '',
        'eight': ''
    };

function move(board, fromX, fromY, toX, toY){
  board.c.three = board.a.one;
  board.a.one = '';
}

print(board);

    document.write('
');
    document.write('');
    document.write('');
    document.write('');
    document.write('');
    document.write('
');<commit_msg>@mfees @carolinapowers trying to make the pieces move with a function, riding the struggle bus<commit_after>function print(board){
    document.write('
');

    _.forEach(board, function(row, key){
        document.write("
");
        _.forEach(row, function(square, k){
            document.write("" + square + "	")

        });
        document.write("
");
    });

    document.write('
');
}

var board = {};
    board.a = {
        'one': '',
        'two': '',
        'three': '',
        'four': '',
        'five': '',
        'six': '',
        'seven': '',
        'eight': ''
    };
    board.b = {
        'one': '',
        'two': '',
        'three': '',
        'four': '',
        'five': '',
        'six': '',
        'seven': '',
        'eight': ''
    };
    board.c = {
        'one': '',
        'two': '',
        'three': '',
        'four': '',
        'five': '',
        'six': '',
        'seven': '',
        'eight': ''
    };
    board.d = {
        'one': '',
        'two': '',
        'three': '',
        'four': '',
        'five': '',
        'six': '',
        'seven': '',
        'eight': ''
    };
    board.e = {
        'one': '',
        'two': '',
        'three': '',
        'four': '',
        'five': '',
        'six': '',
        'seven': '',
        'eight': ''
    };
    board.f = {
        'one': '',
        'two': '',
        'three': '',
        'four': '',
        'five': '',
        'six': '',
        'seven': '',
        'eight': ''
    };
    board.g = {
        'one': '',
        'two': '',
        'three': '',
        'four': '',
        'five': '',
        'six': '',
        'seven': '',
        'eight': ''
    };
    board.h = {
        'one': '',
        'two': '',
        'three': '',
        'four': '',
        'five': '',
        'six': '',
        'seven': '',
        'eight': ''
    };

print(board);

function move(board){
    board.c.three = board.a.one;
    board.a.one = '';
    print(board);
}
    console.log(move());

    document.write('
');
    document.write('');
    document.write('');
    document.write('');
    document.write('');
    document.write('
');<|endoftext|>


<commit_before>Array.prototype.distSq = function (b) {
  return this.reduce((sum,cur,i,a) => sum + (a[i]-b[i])*(a[i]-b[i]), 0)
}

Array.prototype.dist = function (b) { return Math.sqrt(this.distSq(b)) }

Array.prototype.magSq = function (b) {
  return this.reduce((sum,cur,i,a) => sum + (cur*cur), 0)
}

Array.prototype.mag = function (b) { return Math.sqrt(this.magSq(b)) }

Array.prototype.add = function (b) { return this.map((cir,i,a) => a[i] + b[i]) }
Array.prototype.sub = function (b) { return this.map((cur,i,a) => a[i] - b[i]) }
Array.prototype.mul = function (b) { return this.map((cur,i,a) => a[i] * b) }
Array.prototype.div = function (b) { return this.map((ccur,i,a) => a[i] / b) }

// Σaₐbₐ
Array.prototype.dot = function (b) {
  return this.reduce((sum,cur,i,a) => sum + a[i]*b[i], 0)
}

Array.prototype.cross = function (b) {
  return [
    this[1]*b[2] - this[2]*b[1],
    this[2]*b[0] - this[0]*b[2],
    this[0]*b[1] - this[1]*b[0]
  ]
}

Array.prototype.x = function(newVal) {
  if(newVal) this[0] = newVal
  return this[0]
}

Array.prototype.y = function(newVal) {
  if(newVal) this[1] = newVal
  return this[1]
}

Array.prototype.z = function(newVal) {
  if(newVal) this[2] = newVal
  return this[2]
}

Math.clamp = function (val, min, max) {
  return Math.max(min, Math.min(max, val))
}

Object.getOwnPropertyNames(Math).forEach(function (fn) {
  Array.prototype[fn] = function () {
    var args = Array.from(arguments)

    return this.map((cur,i,a) => Math[fn].apply(0, [cur].concat(args)))
  }
})<commit_msg>Removed ES6 arrow functions<commit_after>Array.prototype.distSq = function (b) {
  return this.reduce(function(sum,cur,i,a) {
    return sum + (a[i]-b[i])*(a[i]-b[i])
  }, 0)
}

Array.prototype.dist = function (b) {
  return Math.sqrt(this.distSq(b))
}

Array.prototype.magSq = function (b) {
  return this.reduce(function(sum,cur,i,a) {
    return sum + (cur*cur)
  }, 0)
}

Array.prototype.mag = function (b) { return Math.sqrt(this.magSq(b)) }
Array.prototype.add = function (b) { return this.map(function(cir,i,a) { return a[i] + b[i] }) }
Array.prototype.sub = function (b) { return this.map(function(cur,i,a) { return a[i] - b[i] }) }
Array.prototype.mul = function (b) { return this.map(function(cur,i,a) { return a[i] * b }) }
Array.prototype.div = function (b) { return this.map(function(cur,i,a) { return a[i] / b }) }

// Σaₐbₐ
Array.prototype.dot = function (b) {
  return this.reduce(function(sum,cur,i,a) { return sum + a[i]*b[i] }, 0)
}

Array.prototype.cross = function (b) {
  return [
    this[1]*b[2] - this[2]*b[1],
    this[2]*b[0] - this[0]*b[2],
    this[0]*b[1] - this[1]*b[0]
  ]
}

Array.prototype.x = function(newVal) {
  if(newVal) this[0] = newVal
  return this[0]
}

Array.prototype.y = function(newVal) {
  if(newVal) this[1] = newVal
  return this[1]
}

Array.prototype.z = function(newVal) {
  if(newVal) this[2] = newVal
  return this[2]
}

Math.clamp = function (val, min, max) {
  return Math.max(min, Math.min(max, val))
}

Object.getOwnPropertyNames(Math).forEach(function (fn) {
  Array.prototype[fn] = function () {
    var args = Array.from(arguments)

    return this.map(function(cur,i,a) { return Math[fn].apply(0, [cur].concat(args)) })
  }
})<|endoftext|>


<commit_before>// batteries
// Copyright 2010 - 2011 Sami Samhuri <sami@samhuri.net>

var MathExt =
{ avg: avg
, sum: sum
};

exports.extendNative = function() {
  Math.avg = avg;
  Math.sum = sum;
};

function sum() {
  var nums = Array.isArray(arguments[0]) ? arguments[0] : arguments
    , i = nums.length
    , sum = 0
    ;
  while (i--) sum += arguments[i];
  return sum;
}

function avg() {
  var nums = Array.isArray(arguments[0]) ? arguments[0] : arguments;
  return sum.call(this, nums) / nums.length;
}
<commit_msg>export functions in math ext (whoops)<commit_after>// batteries
// Copyright 2010 - 2011 Sami Samhuri <sami@samhuri.net>

var MathExt =
{ avg: avg
, sum: sum
};

var batteries = require('./');

batteries.object.extend(module.exports, MathExt);

exports.extendNative = function() {
  batteries.object.extend(Math, MathExt);
};

function sum() {
  var nums = Array.isArray(arguments[0]) ? arguments[0] : arguments
    , i = nums.length
    , sum = 0
    ;
  while (i--) sum += arguments[i];
  return sum;
}

function avg() {
  var nums = Array.isArray(arguments[0]) ? arguments[0] : arguments;
  return sum.call(this, nums) / nums.length;
}
<|endoftext|>


<commit_before>var value = 123456;

describe('Wrapper', function(){
	it('can create', function() {
		var wrapper = Wrapper.create();

		Should(wrapper.get('value')).be.exactly(undefined);
    });

    it('can not set value', function() {
		var wrapper = Wrapper.create();

		expect(function(){
			wrapper.set('value', value);
		}).toThrow(new Error("Serialize is not implemented"));
    });

    it('can should copy', function() {
		var wrapper = Wrapper.create();

		var wrapper2 = wrapper.copy();

		Should(wrapper2 instanceof Wrapper).be.exactly(true);
    });
});

describe('Number Wrapper', function(){
	it('can create', function() {
		var wrapper = NumberWrapper.create();

		Should(wrapper.get('value')).be.exactly(undefined);
		Should(wrapper.get('isDefined')).be.exactly(false);
		Should(wrapper.get('isNull')).be.exactly(false);
    });

    it('can set value', function() {
		var wrapper = NumberWrapper.create();

		wrapper.set('value', value);

		Should(wrapper.get('value')).be.exactly(value);
		Should(wrapper.get('isDefined')).be.exactly(true);
		Should(wrapper.get('isNull')).be.exactly(false);
    });

    it('can create with value', function() {
		var wrapper = NumberWrapper.create({
			value: value
		});

		Should(wrapper.get('value')).be.exactly(value);
    });

     it('can check dirty', function() {
		var wrapper = NumberWrapper.create({});

		Should(wrapper.get('isDirty')).be.exactly(false);
		wrapper.set('value', 999);
		Should(wrapper.get('isDirty')).be.exactly(true);

		wrapper = NumberWrapper.create({
			value: value
		});

		Should(wrapper.get('isDirty')).be.exactly(true);
    });

    it('can not set for readOnly', function() {
		var wrapper = NumberWrapper.create({
			readOnly: true,
		});

		expect(function(){
			wrapper.set('value', 9999);
		}).toThrow(new Error("Variable is read only"));
    });

    it('can should copy', function() {
		var wrapper = NumberWrapper.create({
			value: value
		});

		var wrapper2 = wrapper.copy();

		Should(wrapper2 instanceof NumberWrapper).be.exactly(true);
		Should(wrapper2.get('value')).be.exactly(value);
    });

    it('can create with value equal null', function() {
		var wrapper = NumberWrapper.create({
			value: null
		});

		Should(wrapper.get('value')).be.exactly(null);
		Should(wrapper.get('isDefined')).be.exactly(true);
		Should(wrapper.get('isNull')).be.exactly(true);
    });

    it('can create with casted value to number equal -123', function() {
		var wrapper = NumberWrapper.create({
			value: "-123"
		});

		Should(wrapper.get('value')).be.exactly(-123);
		Should(wrapper.get('isDefined')).be.exactly(true);
		Should(wrapper.get('isNull')).be.exactly(false);
    });
});

describe('Boolean Wrapper', function(){
	it('can create', function() {
		var wrapper = BooleanWrapper.create();

		Should(wrapper.get('value')).be.exactly(undefined);
		Should(wrapper.get('isDefined')).be.exactly(false);
		Should(wrapper.get('isNull')).be.exactly(false);
    });

    it('can set value true', function() {
		var wrapper = BooleanWrapper.create();

		wrapper.set('value', true);

		Should(wrapper.get('value')).be.exactly(true);
		Should(wrapper.get('isDefined')).be.exactly(true);
		Should(wrapper.get('isNull')).be.exactly(false);
    });

    it('can create with value false', function() {
		var wrapper = BooleanWrapper.create({
			value: false
		});

		Should(wrapper.get('value')).be.exactly(false);
		Should(wrapper.get('isDefined')).be.exactly(true);
		Should(wrapper.get('isNull')).be.exactly(false);
    });

    it('can should copy', function() {
		var wrapper = BooleanWrapper.create({
			value: true
		});

		var wrapper2 = wrapper.copy();

		Should(wrapper2 instanceof BooleanWrapper).be.exactly(true);
		Should(wrapper2.get('value')).be.exactly(true);
    });

    it('can create with casted value equal "true"', function() {
		var wrapper = BooleanWrapper.create({
			value: "true"
		});

		Should(wrapper.get('value')).be.exactly(true);
		Should(wrapper.get('isDefined')).be.exactly(true);
		Should(wrapper.get('isNull')).be.exactly(false);
    });

    it('can create with casted value equal "yes"', function() {
		var wrapper = BooleanWrapper.create({
			value: "yes"
		});

		Should(wrapper.get('value')).be.exactly(true);
		Should(wrapper.get('isDefined')).be.exactly(true);
		Should(wrapper.get('isNull')).be.exactly(false);
    });

    it('can create with casted value equal "1"', function() {
		var wrapper = BooleanWrapper.create({
			value: "1"
		});

		Should(wrapper.get('value')).be.exactly(true);
		Should(wrapper.get('isDefined')).be.exactly(true);
		Should(wrapper.get('isNull')).be.exactly(false);
    });
});

describe('Array Wrapper', function(){
	it('can create', function() {
		var wrapper = ArrayWrapper.create();

		Should(wrapper.get('value')).be.instanceof(Array).and.have.lengthOf(0);
		Should(wrapper.get('isDefined')).be.exactly(true);
		Should(wrapper.get('isNull')).be.exactly(false);
    });

    it('can set value', function() {
		var wrapper = ArrayWrapper.create({
			type: StringWrapper
		});

		wrapper.set('value', ["ahoj", "peter"]);

		Should(wrapper.get('value')).be.instanceof(Array).and.have.lengthOf(2);
		Should(wrapper.get('isDefined')).be.exactly(true);
		Should(wrapper.get('isNull')).be.exactly(false);

		Should(wrapper.objectAt(0)).be.exactly("ahoj");
		Should(wrapper.objectAt(1)).be.exactly("peter");

		wrapper.forEach(function(item, index){
			Should(item).be.exactly(index===0 ? "ahoj" : "peter");
		});

		wrapper.pushObject("smith");
		Should(wrapper.get('value')).be.instanceof(Array).and.have.lengthOf(3);

		wrapper.removeAt(1);
		Should(wrapper.get('value')).be.instanceof(Array).and.have.lengthOf(2);
		wrapper.forEach(function(item, index){
			Should(item).be.exactly(index===0 ? "ahoj" : "smith");
		});
    });
});

var TestModel = Model.extend({});
TestModel.reopenClass({
	type: 'test'
});

describe('Test Model', function(){
	it('instanceof', function() {
		var testModel = TestModel.create({});

		Should(TestModel.isModel).be.exactly(true);
		Should(Model.isModel).be.exactly(true);
		Should(ModelBase.isModel).not.be.exactly(true);

		Should(testModel instanceof TestModel).be.exactly(true);
		Should(testModel instanceof Model).be.exactly(true);
		Should(testModel instanceof ModelBase).be.exactly(true);
    });
});

describe('Object Wrapper', function(){
	it('can create', function() {
		var obj = ComputedObject.build({
			name: DataLight.attribute(String, {defaultValue: 'Zlatko Fedor'})
		});

		var wrapper = ObjectWrapper.create({
			obj: obj
		});

		Should(wrapper.get('isDefined')).be.exactly(true);
		Should(wrapper.get('isNull')).be.exactly(false);
    });
});

/*
//MUST BE LAST
describe('Model Wrapper', function(){
	it('can create', function() {
		var wrapper = ModelWrapper.create();

		Should(wrapper.get('isDefined')).be.exactly(false);
		Should(wrapper.get('isNull')).be.exactly(false);
    });

    it('can set value', function() {
		var wrapper = ModelWrapper.create({});

		wrapper.set('value', 123456);

		Should(wrapper.get('value')).be.exactly(123456);
		Should(wrapper.get('isDefined')).be.exactly(true);
		Should(wrapper.get('isNull')).be.exactly(false);

		expect(function(){
			wrapper.get('computed');
		}).toThrow(new Error("Model is not defined or has no implemented method find"));
    });

    it('can set with real model', function() {
		var wrapper = ModelWrapper.create({
			model: TestModel
		});

		wrapper.set('value', 123456);

		Should(wrapper.get('model').type).be.exactly('test');

		Should(wrapper.get('value')).be.exactly(123456);
		Should(wrapper.get('isDefined')).be.exactly(true);
		Should(wrapper.get('isNull')).be.exactly(false);

		wrapper.get('computed');
    });
});*/

var User = null;

describe('Model', function(){
	it('can extend with few simple attributes', function() {
		User = Model.extend({
			name: DataLight.attribute(String, { defaultValue: 'Zlatko Fedor' }),
			age: DataLight.attribute(Number),
			canEdit: DataLight.attribute(Boolean, { defaultValue: false }),
			created: DataLight.attribute(Date),
		});

		Should(User.isModel).be.exactly(true);
    });

    it('can create empty instance', function() {
		var user = User.create({});

		Should(user instanceof User).be.exactly(true);
		Should(user instanceof Model).be.exactly(true);
		Should(user instanceof ModelBase).be.exactly(true);

		Should(user.get('isNew')).be.exactly(true);
		Should(user.get('isDirty')).be.exactly(false);

		Should(user.get('name')).be.exactly('Zlatko Fedor');
		Should(user.get('age')).be.exactly(undefined);
		Should(user.get('canEdit')).be.exactly(false);
		Should(user.get('created')).be.exactly(undefined);
    });

    it('can create empty instance', function() {
		var user = User.create({
			name: 'Zlatik',
			age: 18,
			canEdit: true,
			created: Date.now()
		});

		Should(user.get('isNew')).be.exactly(true);
		Should(user.get('isDirty')).be.exactly(true);

		Should(user.get('name')).be.exactly('Zlatik');
		Should(user.get('age')).be.exactly(18);
		Should(user.get('canEdit')).be.exactly(true);
    });

    it('can get json', function() {
		var user = User.create({
			name: 'Zlatik',
			age: 18,
			canEdit: true,
			created: Date.now()
		});

		var json = user.toJSON();

		Should(json).have.property('age', 18);
		Should(json).have.property('name', 'Zlatik');
		Should(json).have.property('canEdit', true);
		Should(json).have.property('created');
    });
});

describe('Model with subobject', function(){
	it('can extend with few simple attributes', function() {
		User = Model.extend({
			name: DataLight.attribute(String, { defaultValue: 'Zlatko Fedor' }),
			age: DataLight.attribute(Number),
			canEdit: DataLight.attribute(Boolean, { defaultValue: false }),
			created: DataLight.attribute(Date),
			address: DataLight.attribute({
				state: DataLight.attribute(String, { defaultValue: 'Slovakia' }),
				city: DataLight.attribute(String)
			}),
		});

		Should(User.isModel).be.exactly(true);
    });

    it('can create empty instance', function() {
		var user = User.create({});

		Should(user instanceof User).be.exactly(true);
		Should(user instanceof Model).be.exactly(true);
		Should(user instanceof ModelBase).be.exactly(true);

		Should(user.get('isNew')).be.exactly(true);
		Should(user.get('isDirty')).be.exactly(false);

		Should(user.get('name')).be.exactly('Zlatko Fedor');
		Should(user.get('age')).be.exactly(undefined);
		Should(user.get('canEdit')).be.exactly(false);
		Should(user.get('created')).be.exactly(undefined);

		Should(user.get('address.state')).be.exactly('Slovakia');
		Should(user.get('address.city')).be.exactly(undefined);
    });

    it('can create instance with values', function() {
		var user = User.create({
			address: {
				city: 'Bratislava'
			}
		});

		Should(user instanceof User).be.exactly(true);
		Should(user instanceof Model).be.exactly(true);
		Should(user instanceof ModelBase).be.exactly(true);

		Should(user.get('isNew')).be.exactly(true);
		Should(user.get('isDirty')).be.exactly(true);

		Should(user.get('name')).be.exactly('Zlatko Fedor');
		Should(user.get('age')).be.exactly(undefined);
		Should(user.get('canEdit')).be.exactly(false);
		Should(user.get('created')).be.exactly(undefined);

		Should(user.get('address.state')).be.exactly('Slovakia');
		Should(user.get('address.city')).be.exactly('Bratislava');

		user.set('address.state', 'Italia');
		Should(user.get('address.state')).be.exactly('Italia');
    });
});

var Article = null;

describe('Model with array', function(){
	it('can extend with few simple attributes', function() {
		Article = Model.extend({
			title: DataLight.attribute(String),
			tags: DataLight.attribute([String])
		});

		Should(Article.isModel).be.exactly(true);
    });

    it('can create empty instance', function() {
		var article = Article.create({});

		Should(article instanceof Article).be.exactly(true);
		Should(article instanceof Model).be.exactly(true);
		Should(article instanceof ModelBase).be.exactly(true);

		Should(article.get('isNew')).be.exactly(true);
		Should(article.get('isDirty')).be.exactly(false);

		Should(article.get('title')).be.exactly(undefined);
		Should(article.get('tags')).be.instanceof(Array).and.have.lengthOf(0);
    });

    it('can create instance with values', function() {
		var article = Article.create({
			title: 'Article about cats in house',
			tags: ['house', 'car', 'cat']
		});

		Should(article instanceof Article).be.exactly(true);
		Should(article instanceof Model).be.exactly(true);
		Should(article instanceof ModelBase).be.exactly(true);

		Should(article.get('isNew')).be.exactly(true);
		Should(article.get('isDirty')).be.exactly(true);

		Should(article.get('title')).be.exactly('Article about cats in house');
		Should(article.get('tags')).be.instanceof(Array).and.have.lengthOf(3);
		Should(article.get('tags')).have.property('0', 'house');
		Should(article.get('tags')).have.property('1', 'car');
		Should(article.get('tags')).have.property('2', 'cat');

		article.get('attributes.tags').pushObject('dog');

		Should(article.get('tags')).be.instanceof(Array).and.have.lengthOf(4);
		Should(article.get('tags')).have.property('3', 'dog');

    });

});<commit_msg>better test for adding items to array<commit_after>var value = 123456;

describe('Wrapper', function(){
	it('can create', function() {
		var wrapper = Wrapper.create();

		Should(wrapper.get('value')).be.exactly(undefined);
    });

    it('can not set value', function() {
		var wrapper = Wrapper.create();

		expect(function(){
			wrapper.set('value', value);
		}).toThrow(new Error("Serialize is not implemented"));
    });

    it('can should copy', function() {
		var wrapper = Wrapper.create();

		var wrapper2 = wrapper.copy();

		Should(wrapper2 instanceof Wrapper).be.exactly(true);
    });
});

describe('Number Wrapper', function(){
	it('can create', function() {
		var wrapper = NumberWrapper.create();

		Should(wrapper.get('value')).be.exactly(undefined);
		Should(wrapper.get('isDefined')).be.exactly(false);
		Should(wrapper.get('isNull')).be.exactly(false);
    });

    it('can set value', function() {
		var wrapper = NumberWrapper.create();

		wrapper.set('value', value);

		Should(wrapper.get('value')).be.exactly(value);
		Should(wrapper.get('isDefined')).be.exactly(true);
		Should(wrapper.get('isNull')).be.exactly(false);
    });

    it('can create with value', function() {
		var wrapper = NumberWrapper.create({
			value: value
		});

		Should(wrapper.get('value')).be.exactly(value);
    });

     it('can check dirty', function() {
		var wrapper = NumberWrapper.create({});

		Should(wrapper.get('isDirty')).be.exactly(false);
		wrapper.set('value', 999);
		Should(wrapper.get('isDirty')).be.exactly(true);

		wrapper = NumberWrapper.create({
			value: value
		});

		Should(wrapper.get('isDirty')).be.exactly(true);
    });

    it('can not set for readOnly', function() {
		var wrapper = NumberWrapper.create({
			readOnly: true,
		});

		expect(function(){
			wrapper.set('value', 9999);
		}).toThrow(new Error("Variable is read only"));
    });

    it('can should copy', function() {
		var wrapper = NumberWrapper.create({
			value: value
		});

		var wrapper2 = wrapper.copy();

		Should(wrapper2 instanceof NumberWrapper).be.exactly(true);
		Should(wrapper2.get('value')).be.exactly(value);
    });

    it('can create with value equal null', function() {
		var wrapper = NumberWrapper.create({
			value: null
		});

		Should(wrapper.get('value')).be.exactly(null);
		Should(wrapper.get('isDefined')).be.exactly(true);
		Should(wrapper.get('isNull')).be.exactly(true);
    });

    it('can create with casted value to number equal -123', function() {
		var wrapper = NumberWrapper.create({
			value: "-123"
		});

		Should(wrapper.get('value')).be.exactly(-123);
		Should(wrapper.get('isDefined')).be.exactly(true);
		Should(wrapper.get('isNull')).be.exactly(false);
    });
});

describe('Boolean Wrapper', function(){
	it('can create', function() {
		var wrapper = BooleanWrapper.create();

		Should(wrapper.get('value')).be.exactly(undefined);
		Should(wrapper.get('isDefined')).be.exactly(false);
		Should(wrapper.get('isNull')).be.exactly(false);
    });

    it('can set value true', function() {
		var wrapper = BooleanWrapper.create();

		wrapper.set('value', true);

		Should(wrapper.get('value')).be.exactly(true);
		Should(wrapper.get('isDefined')).be.exactly(true);
		Should(wrapper.get('isNull')).be.exactly(false);
    });

    it('can create with value false', function() {
		var wrapper = BooleanWrapper.create({
			value: false
		});

		Should(wrapper.get('value')).be.exactly(false);
		Should(wrapper.get('isDefined')).be.exactly(true);
		Should(wrapper.get('isNull')).be.exactly(false);
    });

    it('can should copy', function() {
		var wrapper = BooleanWrapper.create({
			value: true
		});

		var wrapper2 = wrapper.copy();

		Should(wrapper2 instanceof BooleanWrapper).be.exactly(true);
		Should(wrapper2.get('value')).be.exactly(true);
    });

    it('can create with casted value equal "true"', function() {
		var wrapper = BooleanWrapper.create({
			value: "true"
		});

		Should(wrapper.get('value')).be.exactly(true);
		Should(wrapper.get('isDefined')).be.exactly(true);
		Should(wrapper.get('isNull')).be.exactly(false);
    });

    it('can create with casted value equal "yes"', function() {
		var wrapper = BooleanWrapper.create({
			value: "yes"
		});

		Should(wrapper.get('value')).be.exactly(true);
		Should(wrapper.get('isDefined')).be.exactly(true);
		Should(wrapper.get('isNull')).be.exactly(false);
    });

    it('can create with casted value equal "1"', function() {
		var wrapper = BooleanWrapper.create({
			value: "1"
		});

		Should(wrapper.get('value')).be.exactly(true);
		Should(wrapper.get('isDefined')).be.exactly(true);
		Should(wrapper.get('isNull')).be.exactly(false);
    });
});

describe('Array Wrapper', function(){
	it('can create', function() {
		var wrapper = ArrayWrapper.create();

		Should(wrapper.get('value')).be.instanceof(Array).and.have.lengthOf(0);
		Should(wrapper.get('isDefined')).be.exactly(true);
		Should(wrapper.get('isNull')).be.exactly(false);
    });

    it('can set value', function() {
		var wrapper = ArrayWrapper.create({
			type: StringWrapper
		});

		wrapper.set('value', ["ahoj", "peter"]);

		Should(wrapper.get('value')).be.instanceof(Array).and.have.lengthOf(2);
		Should(wrapper.get('isDefined')).be.exactly(true);
		Should(wrapper.get('isNull')).be.exactly(false);

		Should(wrapper.objectAt(0)).be.exactly("ahoj");
		Should(wrapper.objectAt(1)).be.exactly("peter");

		wrapper.forEach(function(item, index){
			Should(item).be.exactly(index===0 ? "ahoj" : "peter");
		});

		wrapper.pushObject("smith");
		Should(wrapper.get('value')).be.instanceof(Array).and.have.lengthOf(3);

		wrapper.removeAt(1);
		Should(wrapper.get('value')).be.instanceof(Array).and.have.lengthOf(2);
		wrapper.forEach(function(item, index){
			Should(item).be.exactly(index===0 ? "ahoj" : "smith");
		});
    });
});

var TestModel = Model.extend({});
TestModel.reopenClass({
	type: 'test'
});

describe('Test Model', function(){
	it('instanceof', function() {
		var testModel = TestModel.create({});

		Should(TestModel.isModel).be.exactly(true);
		Should(Model.isModel).be.exactly(true);
		Should(ModelBase.isModel).not.be.exactly(true);

		Should(testModel instanceof TestModel).be.exactly(true);
		Should(testModel instanceof Model).be.exactly(true);
		Should(testModel instanceof ModelBase).be.exactly(true);
    });
});

describe('Object Wrapper', function(){
	it('can create', function() {
		var obj = ComputedObject.build({
			name: DataLight.attribute(String, {defaultValue: 'Zlatko Fedor'})
		});

		var wrapper = ObjectWrapper.create({
			obj: obj
		});

		Should(wrapper.get('isDefined')).be.exactly(true);
		Should(wrapper.get('isNull')).be.exactly(false);
    });
});

/*
//MUST BE LAST
describe('Model Wrapper', function(){
	it('can create', function() {
		var wrapper = ModelWrapper.create();

		Should(wrapper.get('isDefined')).be.exactly(false);
		Should(wrapper.get('isNull')).be.exactly(false);
    });

    it('can set value', function() {
		var wrapper = ModelWrapper.create({});

		wrapper.set('value', 123456);

		Should(wrapper.get('value')).be.exactly(123456);
		Should(wrapper.get('isDefined')).be.exactly(true);
		Should(wrapper.get('isNull')).be.exactly(false);

		expect(function(){
			wrapper.get('computed');
		}).toThrow(new Error("Model is not defined or has no implemented method find"));
    });

    it('can set with real model', function() {
		var wrapper = ModelWrapper.create({
			model: TestModel
		});

		wrapper.set('value', 123456);

		Should(wrapper.get('model').type).be.exactly('test');

		Should(wrapper.get('value')).be.exactly(123456);
		Should(wrapper.get('isDefined')).be.exactly(true);
		Should(wrapper.get('isNull')).be.exactly(false);

		wrapper.get('computed');
    });
});*/

var User = null;

describe('Model', function(){
	it('can extend with few simple attributes', function() {
		User = Model.extend({
			name: DataLight.attribute(String, { defaultValue: 'Zlatko Fedor' }),
			age: DataLight.attribute(Number),
			canEdit: DataLight.attribute(Boolean, { defaultValue: false }),
			created: DataLight.attribute(Date),
		});

		Should(User.isModel).be.exactly(true);
    });

    it('can create empty instance', function() {
		var user = User.create({});

		Should(user instanceof User).be.exactly(true);
		Should(user instanceof Model).be.exactly(true);
		Should(user instanceof ModelBase).be.exactly(true);

		Should(user.get('isNew')).be.exactly(true);
		Should(user.get('isDirty')).be.exactly(false);

		Should(user.get('name')).be.exactly('Zlatko Fedor');
		Should(user.get('age')).be.exactly(undefined);
		Should(user.get('canEdit')).be.exactly(false);
		Should(user.get('created')).be.exactly(undefined);
    });

    it('can create empty instance', function() {
		var user = User.create({
			name: 'Zlatik',
			age: 18,
			canEdit: true,
			created: Date.now()
		});

		Should(user.get('isNew')).be.exactly(true);
		Should(user.get('isDirty')).be.exactly(true);

		Should(user.get('name')).be.exactly('Zlatik');
		Should(user.get('age')).be.exactly(18);
		Should(user.get('canEdit')).be.exactly(true);
    });

    it('can get json', function() {
		var user = User.create({
			name: 'Zlatik',
			age: 18,
			canEdit: true,
			created: Date.now()
		});

		var json = user.toJSON();

		Should(json).have.property('age', 18);
		Should(json).have.property('name', 'Zlatik');
		Should(json).have.property('canEdit', true);
		Should(json).have.property('created');
    });
});

describe('Model with subobject', function(){
	it('can extend with few simple attributes', function() {
		User = Model.extend({
			name: DataLight.attribute(String, { defaultValue: 'Zlatko Fedor' }),
			age: DataLight.attribute(Number),
			canEdit: DataLight.attribute(Boolean, { defaultValue: false }),
			created: DataLight.attribute(Date),
			address: DataLight.attribute({
				state: DataLight.attribute(String, { defaultValue: 'Slovakia' }),
				city: DataLight.attribute(String)
			}),
		});

		Should(User.isModel).be.exactly(true);
    });

    it('can create empty instance', function() {
		var user = User.create({});

		Should(user instanceof User).be.exactly(true);
		Should(user instanceof Model).be.exactly(true);
		Should(user instanceof ModelBase).be.exactly(true);

		Should(user.get('isNew')).be.exactly(true);
		Should(user.get('isDirty')).be.exactly(false);

		Should(user.get('name')).be.exactly('Zlatko Fedor');
		Should(user.get('age')).be.exactly(undefined);
		Should(user.get('canEdit')).be.exactly(false);
		Should(user.get('created')).be.exactly(undefined);

		Should(user.get('address.state')).be.exactly('Slovakia');
		Should(user.get('address.city')).be.exactly(undefined);
    });

    it('can create instance with values', function() {
		var user = User.create({
			address: {
				city: 'Bratislava'
			}
		});

		Should(user instanceof User).be.exactly(true);
		Should(user instanceof Model).be.exactly(true);
		Should(user instanceof ModelBase).be.exactly(true);

		Should(user.get('isNew')).be.exactly(true);
		Should(user.get('isDirty')).be.exactly(true);

		Should(user.get('name')).be.exactly('Zlatko Fedor');
		Should(user.get('age')).be.exactly(undefined);
		Should(user.get('canEdit')).be.exactly(false);
		Should(user.get('created')).be.exactly(undefined);

		Should(user.get('address.state')).be.exactly('Slovakia');
		Should(user.get('address.city')).be.exactly('Bratislava');

		user.set('address.state', 'Italia');
		Should(user.get('address.state')).be.exactly('Italia');
    });
});

var Article = null;

describe('Model with array', function(){
	it('can extend with few simple attributes', function() {
		Article = Model.extend({
			title: DataLight.attribute(String),
			tags: DataLight.attribute([String])
		});

		Should(Article.isModel).be.exactly(true);
    });

    it('can create empty instance', function() {
		var article = Article.create({});

		Should(article instanceof Article).be.exactly(true);
		Should(article instanceof Model).be.exactly(true);
		Should(article instanceof ModelBase).be.exactly(true);

		Should(article.get('isNew')).be.exactly(true);
		Should(article.get('isDirty')).be.exactly(false);

		Should(article.get('title')).be.exactly(undefined);
		Should(article.get('tags')).be.instanceof(Array).and.have.lengthOf(0);
    });

    it('can create instance with values', function() {
		var article = Article.create({
			title: 'Article about cats in house',
			tags: ['house', 'car', 'cat']
		});

		Should(article instanceof Article).be.exactly(true);
		Should(article instanceof Model).be.exactly(true);
		Should(article instanceof ModelBase).be.exactly(true);

		Should(article.get('isNew')).be.exactly(true);
		Should(article.get('isDirty')).be.exactly(true);

		Should(article.get('title')).be.exactly('Article about cats in house');
		Should(article.get('tags')).be.instanceof(Array).and.have.lengthOf(3);
		Should(article.get('tags')).have.property('0', 'house');
		Should(article.get('tags')).have.property('1', 'car');
		Should(article.get('tags')).have.property('2', 'cat');
    });

    it('can add and remove value', function() {
		var article = Article.create({
			title: 'Article about cats in house',
			tags: ['house', 'car', 'cat']
		});

		article.get('attributes.tags').pushObject('dog');

		Should(article.get('tags')).be.instanceof(Array).and.have.lengthOf(4);
		Should(article.get('tags')).have.property('3', 'dog');

		article.get('attributes.tags').removeObject('dog');
		Should(article.get('tags')).be.instanceof(Array).and.have.lengthOf(3);
    });
});<|endoftext|>


<commit_before>import commonjs from "rollup-plugin-commonjs";
import nodeResolve from "rollup-plugin-node-resolve";

export default {
    input: "./lib/sinon.js",
    output: {
        file: "pkg/bundle-esm.js",
        format: "esm"
    },
    plugins: [
        nodeResolve({
            jsnext: true,
            main: true
        }),

        commonjs({
            // non-CommonJS modules will be ignored, but you can also
            // specifically include/exclude files
            //include: "node_modules/**", // Default: undefined
            //exclude: ["node_modules/foo/**", "node_modules/bar/**"], // Default: undefined
            // these values can also be regular expressions
            // include: /node_modules/

            // search for files other than .js files (must already
            // be transpiled by a previous plugin!)
            //extensions: [".js", ".coffee"], // Default: [ '.js' ]

            // if true then uses of `global` won't be dealt with by this plugin
            ignoreGlobal: false, // Default: false

            // if false then skip sourceMap generation for CommonJS modules
            sourceMap: false // Default: true

            // explicitly specify unresolvable named exports
            // (see below for more details)
            //namedExports: {
            //"node_modules/diff/lib/index.js": ["default"]
            //} // Default: undefined

            // sometimes you have to leave require statements
            // unconverted. Pass an array containing the IDs
            // or a `id => boolean` function. Only use this
            // option if you know what you're doing!
            //ignore: ["conditional-runtime-dependency"]
        })
    ]
};
<commit_msg>Add sourcemapping<commit_after>import commonjs from "rollup-plugin-commonjs";
import nodeResolve from "rollup-plugin-node-resolve";

export default {
    input: "./lib/sinon.js",
    output: {
        file: "pkg/bundle-esm.js",
        format: "esm"
    },
    plugins: [
        nodeResolve({
            jsnext: true,
            main: true
        }),

        commonjs({
            // non-CommonJS modules will be ignored, but you can also
            // specifically include/exclude files
            //include: "node_modules/**", // Default: undefined
            //exclude: ["node_modules/foo/**", "node_modules/bar/**"], // Default: undefined
            // these values can also be regular expressions
            // include: /node_modules/

            // search for files other than .js files (must already
            // be transpiled by a previous plugin!)
            //extensions: [".js", ".coffee"], // Default: [ '.js' ]

            // if true then uses of `global` won't be dealt with by this plugin
            ignoreGlobal: false, // Default: false

            // if false then skip sourceMap generation for CommonJS modules
            sourceMap: true // Default: true

            // explicitly specify unresolvable named exports
            // (see below for more details)
            //namedExports: {
            //"node_modules/diff/lib/index.js": ["default"]
            //} // Default: undefined

            // sometimes you have to leave require statements
            // unconverted. Pass an array containing the IDs
            // or a `id => boolean` function. Only use this
            // option if you know what you're doing!
            //ignore: ["conditional-runtime-dependency"]
        })
    ]
};
<|endoftext|>