<commit_before>var Flow = require('./flow');
var utils = require('./utils');
var isPublicPath = /^\/[^/]/;
var styles = {};
var markups = engine.markup = {};

// global module instance cache
var instances = engine.instances = {};

/**
 * Create a new module instance.
 *
 * @public
 * @param {object} The CommonJS module.
 * @param {object} The composition config.
 * @param {function} Callback handler.
 */
module.exports = function factory (module, config, role, callback, loaderInstance) {

    // check instance cache
    if (instances[config.name]) {
        return callback(null, instances[config.name]);
    }

    // create new flow emitter
    var instance = Flow();
    var countDown = 1;
    var readyHandler = function (err) {

        // TODO handle error

        if (--countDown === 0) {

            // don't init dependency instances
            if (loaderInstance) {
                return callback(null, instance);
            }

            initInstancesInLoadOrder(instance, callback, loaderInstance);
        }
    };

    // extend module instance with module methods
    if (module) {
        for (var prop in module) {
            instance[prop] = module[prop];
        }
    }

    // save module instance in cache
    instances[config.name] = instance;

    // extend instance
    instance._config = config.config || {};
    instance._name = config.name;
    instance._roles = config.roles || {};
    instance._access = {};
    instance._load = config.load;

    if (config.flow) {
        instance._flow = config.flow;
    }

    // collect dependency instance names in loader dependencies
    if (loaderInstance) {
        loaderInstance._load.push(config.name);
        loaderInstance._load.concat(config.load || []);
    }

    // load styles
    config.styles && loadStyles(config.styles);

    // load markup
    if (config.markup && config.markup.length) {
        ++countDown;
        loadSnippets(config.markup, readyHandler);
    }

    // only client, on the server the module can just use require any file
    if (config.load) {
        countDown += config.load.length;

        for (var i = 0, l = config.load.length; i < l; ++i) {
            engine.load(config.load[i], role, readyHandler, loaderInstance || instance);
        }
    }

    readyHandler();
};

/**
 * Setup event flow, emit ready events and after all module instances are ready, emit a route event.
 *
 * @public
 * @param {err} The err string.
 * @param {array} The loaded module instances.
 */
function initInstancesInLoadOrder (instance, callback) {

    // init instance
    setupFlowAndInit(instance);

    // init dependencies
    var dependencies = instance._load;
    if (dependencies) {
        // initialize module instances
        for (var i = 0, l = dependencies.length, moduleInstance, flow; i < l; ++i) {
            setupFlowAndInit(engine.instances[dependencies[i]]);
        }
    }

    callback(null, instance);
}

function setupFlowAndInit (instance) {

    // setup event flow
    var flows = instance._flow;
    if (flows) {

        for (var i = 0, l = flows.length, flow; i < l; ++i) {
            flow = flows[i];
            if (flow.on) {

                // update event access
                instance._access[flow.on] = true;

                // append flow handler
                instance.mind(flow.on, flow);
            }
        }
    }

    // call the factory method if it exists
    if (instance.init) {
        instance.init();
    }
}

/**
 * Load html snippets.
 *
 * @public
 * @param {array} The array containing html snippet file urls.
 */
function loadSnippets (urls, callback) {

    var count = urls.length;
    var stream = engine.flow('M');

    // TODO cache snipptes (instance + path)

    // receive html snipptes
    stream.data(function (err, html) {

        // ignore errors
        if (err || !html) {
            // check if all snippets are loaded
            if (--count === 0) {
                stream.end();
                callback();
            }
            return;
        }

        // save html snippet in cache
        markups[html[0]] = html[1];

        // check if all snippets are loaded
        if (--count === 0) {
            stream.end();
            callback();
        }
    });

    // get html snippets
    for (var i in urls) {
        if (!markups[urls[i]]) {
            stream.write(null, urls[i]);

        } else if (--count === 0) {
            stream.end();
            callback();
        }
    }
}

/**
 * Load css files.
 *
 * @public
 * @param {array} The array containing css file urls.
 */
function loadStyles (urls) {

    for (var i = 0, link; i < urls.length; ++i) {
        if (!styles[urls[i]]) {
            styles[urls[i]] = 1;

            link = global.document.createElement('link');

            // append public file prefix
            if (isPublicPath.test(urls[i])) {
                urls[i] = '/!' + urls[i];

            // append module file prefix
            } else if (urls[i].indexOf('://') < 0 && urls[i].indexOf('//') !== 0) {
                urls[i] = '/@/@/' + urls[i];
            }

            link.setAttribute('rel', 'stylesheet');
            link.setAttribute('href', urls[i]);
            global.document.head.appendChild(link);
        }
    }
}
<commit_msg>append log method to instances<commit_after>var Flow = require('./flow');
var utils = require('./utils');
var logs = engine.production ? function () {} : require('./logs');
var isPublicPath = /^\/[^/]/;
var styles = {};
var markups = engine.markup = {};

// global module instance cache
var instances = engine.instances = {};

/**
 * Create a new module instance.
 *
 * @public
 * @param {object} The CommonJS module.
 * @param {object} The composition config.
 * @param {function} Callback handler.
 */
module.exports = function factory (module, config, role, callback, loaderInstance) {

    // check instance cache
    if (instances[config.name]) {
        return callback(null, instances[config.name]);
    }

    // create new flow emitter
    var instance = Flow();
    var countDown = 1;
    var readyHandler = function (err) {

        // TODO handle error

        if (--countDown === 0) {

            // don't init dependency instances
            if (loaderInstance) {
                return callback(null, instance);
            }

            initInstancesInLoadOrder(instance, callback, loaderInstance);
        }
    };

    // extend module instance with module methods
    if (module) {
        for (var prop in module) {
            instance[prop] = module[prop];
        }
    }

    // extend instance
    instance._module = config.module;
    instance._config = config.config || {};
    instance._name = config.name;
    instance._roles = config.roles || {};
    instance._access = {};
    instance._load = config.load;

    if (config.flow) {
        instance._flow = config.flow;
    }

    // collect dependency instance names in loader dependencies
    if (loaderInstance) {
        loaderInstance._load.push(config.name);
        loaderInstance._load.concat(config.load || []);
    }

    // extend engine with logging methods
    instance.log = logs || function () {};

    // save module instance in cache
    instances[config.name] = instance;

    // load styles
    config.styles && loadStyles(config.styles);

    // load markup
    if (config.markup && config.markup.length) {
        ++countDown;
        loadSnippets(config.markup, readyHandler);
    }

    // only client, on the server the module can just use require any file
    if (config.load) {
        countDown += config.load.length;

        for (var i = 0, l = config.load.length; i < l; ++i) {
            engine.load(config.load[i], role, readyHandler, loaderInstance || instance);
        }
    }

    readyHandler();
};

/**
 * Setup event flow, emit ready events and after all module instances are ready, emit a route event.
 *
 * @public
 * @param {err} The err string.
 * @param {array} The loaded module instances.
 */
function initInstancesInLoadOrder (instance, callback) {

    // init instance
    setupFlowAndInit(instance);

    // init dependencies
    var dependencies = instance._load;
    if (dependencies) {
        // initialize module instances
        for (var i = 0, l = dependencies.length, moduleInstance, flow; i < l; ++i) {
            setupFlowAndInit(engine.instances[dependencies[i]]);
        }
    }

    callback(null, instance);
}

function setupFlowAndInit (instance) {

    // setup event flow
    var flows = instance._flow;
    if (flows) {

        for (var i = 0, l = flows.length, flow; i < l; ++i) {
            flow = flows[i];
            if (flow.on) {

                // update event access
                instance._access[flow.on] = true;

                // append flow handler
                instance.mind(flow.on, flow);
            }
        }
    }

    // call the factory method if it exists
    if (instance.init) {
        instance.init();
    }
}

/**
 * Load html snippets.
 *
 * @public
 * @param {array} The array containing html snippet file urls.
 */
function loadSnippets (urls, callback) {

    var count = urls.length;
    var stream = engine.flow('M');

    // TODO cache snipptes (instance + path)

    // receive html snipptes
    stream.data(function (err, html) {

        // ignore errors
        if (err || !html) {
            // check if all snippets are loaded
            if (--count === 0) {
                stream.end();
                callback();
            }
            return;
        }

        // save html snippet in cache
        markups[html[0]] = html[1];

        // check if all snippets are loaded
        if (--count === 0) {
            stream.end();
            callback();
        }
    });

    // get html snippets
    for (var i in urls) {
        if (!markups[urls[i]]) {
            stream.write(null, urls[i]);

        } else if (--count === 0) {
            stream.end();
            callback();
        }
    }
}

/**
 * Load css files.
 *
 * @public
 * @param {array} The array containing css file urls.
 */
function loadStyles (urls) {

    for (var i = 0, link; i < urls.length; ++i) {
        if (!styles[urls[i]]) {
            styles[urls[i]] = 1;

            link = global.document.createElement('link');

            // append public file prefix
            if (isPublicPath.test(urls[i])) {
                urls[i] = '/!' + urls[i];

            // append module file prefix
            } else if (urls[i].indexOf('://') < 0 && urls[i].indexOf('//') !== 0) {
                urls[i] = '/@/@/' + urls[i];
            }

            link.setAttribute('rel', 'stylesheet');
            link.setAttribute('href', urls[i]);
            global.document.head.appendChild(link);
        }
    }
}
<|endoftext|>


<commit_before>var Flow = require('./flow');
var utils = require('./utils');
var isPublicPath = /^\/[^/]/;
var styles = {};
var markups = {};

// global module instance cache
var instances = engine.instances = {};

/**
 * Create a new module instance.
 *
 * @public
 * @param {object} The CommonJS module.
 * @param {object} The composition config.
 * @param {function} Callback handler.
 */
module.exports = function factory (module, config, role, callback) {

    // check instance cache
    if (instances[config.name]) {
        return callback(null, instances[config.name]);
    }

    // create new flow emitter
    var instance = Flow();
    var countDown = 1;
    var readyHandler = function (err) {

        // TODO handle error

        if (--countDown === 0) {
            initInstancesInLoadOrder(instance, callback);
        }
    };

    // extend module instance with module methods
    if (module) {
        for (var prop in module) {
            instance[prop] = module[prop];
        }
    }

    // save module instance in cache
    instances[config.name] = instance;

    // extend instance
    instance._config = config.config || {};
    instance._name = config.name;
    instance._roles = config.roles || {};
    instance._access = {};

    if (config.flow) {
        instance._flow = config.flow;
    }

    // load styles
    config.styles && loadStyles(config.styles);

    // load markup
    if (config.markup) {
        ++countDown;
        loadSnippets(config.markup, readyHandler);
    }

    // only client, on the server the module can just use require any file
    if (config.load) {
        countDown += config.load.length;
        for (var i = 0, l = config.load.length; i < l; ++i) {
            engine.load(config.load[i], role, readyHandler);
        }
    }

    readyHandler();
};

/**
 * Setup event flow, emit ready events and after all module instances are ready, emit a route event.
 *
 * @public
 * @param {err} The err string.
 * @param {array} The loaded module instances.
 */
function initInstancesInLoadOrder (instance, callback) {

    // init instance
    setupFlowAndInit(instance);

    // init dependencies
    var dependencies = instance._config.load;
    if (dependencies) {

        // initialize module instances
        for (var i = 0, l = dependencies.length, moduleInstance, flow; i < l; ++i) {
            setupFlowAndInit(engine.instances[dependencies[i]]);
        }
    }

    callback(null, instance);
}

function setupFlowAndInit (instance) {

    // setup event flow
    var flows = instance._flow;
    if (flows) {

        for (var i = 0, l = flows.length, flow; i < l; ++i) {
            flow = flows[i];
            if (flow.on) {

                // update event access
                instance._access[flow.on] = true;

                // append flow handler
                instance.mind(flow.on, flow);
            }
        }
    }

    // call the factory method if it exists
    if (instance.init) {
        instance.init();
    }
}

/**
 * Load html snippets.
 *
 * @public
 * @param {array} The array containing html snippet file urls.
 */
function loadSnippets (urls, callback) {

    var count = urls.length;
    var stream = engine.flow('M');

    // TODO cache snipptes (instance + path)

    // receive html snipptes
    stream.data(function (err, html) {

        // ignore errors
        if (err || !html) {
            // check if all snippets are loaded
            if (--count === 0) {
                stream.end();
                callback();
            }
            return;
        }

        // save html snippet in cache
        markups[html[0]] = html[1];

        // check if all snippets are loaded
        if (--count === 0) {
            stream.end();
            callback();
        }
    });

    // get html snippets
    for (var i in urls) {
        if (!markups[urls[i]]) {
            stream.write(null, urls[i]);

        } else if (--count === 0) {
            stream.end();
            callback();
        }
    }
}

/**
 * Load css files.
 *
 * @public
 * @param {array} The array containing css file urls.
 */
function loadStyles (urls) {

    for (var i = 0, link; i < urls.length; ++i) {
        if (!styles[urls[i]]) {
            styles[urls[i]] = 1;

            link = global.document.createElement('link');

            // append public file prefix
            if (isPublicPath.test(urls[i])) {
                urls[i] = '/!' + urls[i];

            // append module file prefix
            } else if (urls[i].indexOf('://') < 0 && urls[i].indexOf('//') !== 0) {
                urls[i] = '/@/@/' + urls[i];
            }

            link.setAttribute('rel', 'stylesheet');
            link.setAttribute('href', urls[i]);
            global.document.head.appendChild(link);
        }
    }
}
<commit_msg>make markup snippets available in the engine global<commit_after>var Flow = require('./flow');
var utils = require('./utils');
var isPublicPath = /^\/[^/]/;
var styles = {};
var markups = engine.markup = {};

// global module instance cache
var instances = engine.instances = {};

/**
 * Create a new module instance.
 *
 * @public
 * @param {object} The CommonJS module.
 * @param {object} The composition config.
 * @param {function} Callback handler.
 */
module.exports = function factory (module, config, role, callback) {

    // check instance cache
    if (instances[config.name]) {
        return callback(null, instances[config.name]);
    }

    // create new flow emitter
    var instance = Flow();
    var countDown = 1;
    var readyHandler = function (err) {

        // TODO handle error

        if (--countDown === 0) {
            initInstancesInLoadOrder(instance, callback);
        }
    };

    // extend module instance with module methods
    if (module) {
        for (var prop in module) {
            instance[prop] = module[prop];
        }
    }

    // save module instance in cache
    instances[config.name] = instance;

    // extend instance
    instance._config = config.config || {};
    instance._name = config.name;
    instance._roles = config.roles || {};
    instance._access = {};

    if (config.flow) {
        instance._flow = config.flow;
    }

    // load styles
    config.styles && loadStyles(config.styles);

    // load markup
    if (config.markup) {
        ++countDown;
        loadSnippets(config.markup, readyHandler);
    }

    // only client, on the server the module can just use require any file
    if (config.load) {
        countDown += config.load.length;
        for (var i = 0, l = config.load.length; i < l; ++i) {
            engine.load(config.load[i], role, readyHandler);
        }
    }

    readyHandler();
};

/**
 * Setup event flow, emit ready events and after all module instances are ready, emit a route event.
 *
 * @public
 * @param {err} The err string.
 * @param {array} The loaded module instances.
 */
function initInstancesInLoadOrder (instance, callback) {

    // init instance
    setupFlowAndInit(instance);

    // init dependencies
    var dependencies = instance._config.load;
    if (dependencies) {

        // initialize module instances
        for (var i = 0, l = dependencies.length, moduleInstance, flow; i < l; ++i) {
            setupFlowAndInit(engine.instances[dependencies[i]]);
        }
    }

    callback(null, instance);
}

function setupFlowAndInit (instance) {

    // setup event flow
    var flows = instance._flow;
    if (flows) {

        for (var i = 0, l = flows.length, flow; i < l; ++i) {
            flow = flows[i];
            if (flow.on) {

                // update event access
                instance._access[flow.on] = true;

                // append flow handler
                instance.mind(flow.on, flow);
            }
        }
    }

    // call the factory method if it exists
    if (instance.init) {
        instance.init();
    }
}

/**
 * Load html snippets.
 *
 * @public
 * @param {array} The array containing html snippet file urls.
 */
function loadSnippets (urls, callback) {

    var count = urls.length;
    var stream = engine.flow('M');

    // TODO cache snipptes (instance + path)

    // receive html snipptes
    stream.data(function (err, html) {

        // ignore errors
        if (err || !html) {
            // check if all snippets are loaded
            if (--count === 0) {
                stream.end();
                callback();
            }
            return;
        }

        // save html snippet in cache
        markups[html[0]] = html[1];

        // check if all snippets are loaded
        if (--count === 0) {
            stream.end();
            callback();
        }
    });

    // get html snippets
    for (var i in urls) {
        if (!markups[urls[i]]) {
            stream.write(null, urls[i]);

        } else if (--count === 0) {
            stream.end();
            callback();
        }
    }
}

/**
 * Load css files.
 *
 * @public
 * @param {array} The array containing css file urls.
 */
function loadStyles (urls) {

    for (var i = 0, link; i < urls.length; ++i) {
        if (!styles[urls[i]]) {
            styles[urls[i]] = 1;

            link = global.document.createElement('link');

            // append public file prefix
            if (isPublicPath.test(urls[i])) {
                urls[i] = '/!' + urls[i];

            // append module file prefix
            } else if (urls[i].indexOf('://') < 0 && urls[i].indexOf('//') !== 0) {
                urls[i] = '/@/@/' + urls[i];
            }

            link.setAttribute('rel', 'stylesheet');
            link.setAttribute('href', urls[i]);
            global.document.head.appendChild(link);
        }
    }
}
<|endoftext|>


<commit_before>const constants = {
    DEFAULT_MODE_WIDTH: 250,
    COMPACT_MODE_WIDTH: 50,
    MODE_CHANGE_DURATION_MS: 200,
    MIN_WIDTH: 500,
    MIN_HEIGHT: 300
};

export default Marionette.View.extend({
    initialize(options) {
        this.firstPanel = options.firstPanel;
        this.secondPanel = options.secondPanel;
    },

    className: 'split-panel-resizer_container',

    template: Handlebars.compile('

'),

    onRender() {
        if (this.options.orientation === 'horizontal') {
            const originalPanel1Height = this.firstPanel.el.getBoundingClientRect().height;

            this.$el.css('left', '');
            this.$el.css('top', `${originalPanel1Height + this.firstPanel.el.offsetTop}px`);
            this.originalParentHeight = this.firstPanel.parentEl().offsetHeight + this.firstPanel.parentEl().getBoundingClientRect().top;
            this.minimumTop = this.firstPanel.el.offsetTop + constants.MIN_HEIGHT;
            this.el.className = 'split-panel-resizer_container split-panel-resizer_horizontal';

            Core.services.UIService.draggable({
                el: this.el,
                axis: 'y',
                drag: (event, ui) => this.__onResizerDragHorizontal(ui)
            });
        } else {
            const originalPanel1Width = this.firstPanel.el.getBoundingClientRect().width;

            this.$el.css('top', '');
            this.$el.css('left', `${originalPanel1Width + this.firstPanel.el.offsetLeft}px`);
            this.originalParentWidth = this.firstPanel.parentEl().offsetWidth;
            this.minimumLeft = this.firstPanel.el.offsetLeft + constants.MIN_WIDTH;
            this.el.className = 'split-panel-resizer_container split-panel-resizer_vertical';

            Core.services.UIService.draggable({
                el: this.el,
                axis: 'x',
                drag: (event, ui) => this.__onResizerDragVertical(ui)
            });
        }
    },

    toggleOrientation(type) {
        this.options.orientation = type;
        this.render();
    },

    doManualResize() {
        this.render();
    },

    __onResizerDragVertical(ui) {
        const totalWidth = this.originalParentWidth;
        let width = ui.position.left;

        if (width < constants.MIN_WIDTH) {
            width = constants.MIN_WIDTH;
            ui.position.left = this.minimumLeft;
        }

        const maxWidth = totalWidth - constants.MIN_WIDTH;

        if (width > maxWidth) {
            width = maxWidth;
            ui.position.left = this.firstPanel.el.offsetLeft + maxWidth;
        }

        this.firstPanel.$el.css('flex', `0 0 ${width}px`);
    },

    __onResizerDragHorizontal(ui) {
        let top = ui.position.top;

        if (top < constants.MIN_HEIGHT) {
            top = constants.MIN_HEIGHT;
            ui.position.top = this.minimumTop;
        }

        const maxHeight = this.originalParentHeight - constants.MIN_HEIGHT;

        if (top > maxHeight) {
            top = maxHeight;
            ui.position.top = maxHeight;
        }

        this.firstPanel.$el.css('flex', `0 0 ${top}px`);
    }
});
<commit_msg>Fix split panel resizer<commit_after>const constants = {
    DEFAULT_MODE_WIDTH: 250,
    COMPACT_MODE_WIDTH: 50,
    MODE_CHANGE_DURATION_MS: 200,
    MIN_WIDTH: 500,
    MIN_HEIGHT: 300
};

export default Marionette.View.extend({
    initialize(options) {
        this.firstPanel = options.firstPanel;
        this.secondPanel = options.secondPanel;
    },

    className: 'split-panel-resizer_container',

    template: Handlebars.compile('

'),

    onRender() {
        if (this.options.orientation === 'horizontal') {
            const originalPanel1Height = this.firstPanel.el.getBoundingClientRect().height;

            this.$el.css('left', '');
            this.$el.css('top', `${originalPanel1Height + this.firstPanel.el.offsetTop}px`);
            this.originalParentHeight = this.firstPanel.parentEl().offsetHeight + this.firstPanel.parentEl().getBoundingClientRect().top;
            this.minimumTop = this.firstPanel.el.offsetTop + constants.MIN_HEIGHT;
            this.el.className = 'split-panel-resizer_container split-panel-resizer_horizontal';

            Core.services.UIService.draggable({
                el: this.el,
                axis: 'y',
                drag: (event, ui) => this.__onResizerDragHorizontal(ui)
            });
        } else {
            const originalPanel1Width = this.firstPanel.el.getBoundingClientRect().width;

            this.leftOffset = this.firstPanel.el.offsetLeft;
            this.$el.css('top', '');
            this.$el.css('left', `${originalPanel1Width + this.firstPanel.el.offsetLeft}px`);
            this.originalParentWidth = this.firstPanel.parentEl().offsetWidth;
            this.minimumLeft = this.firstPanel.el.offsetLeft + constants.MIN_WIDTH;
            this.el.className = 'split-panel-resizer_container split-panel-resizer_vertical';

            Core.services.UIService.draggable({
                el: this.el,
                axis: 'x',
                drag: (event, ui) => this.__onResizerDragVertical(ui)
            });
        }
    },

    toggleOrientation(type) {
        this.options.orientation = type;
        this.render();
    },

    doManualResize() {
        this.render();
    },

    __onResizerDragVertical(ui) {
        const totalWidth = this.originalParentWidth;
        let width = ui.position.left - this.leftOffset;

        if (width < constants.MIN_WIDTH) {
            width = constants.MIN_WIDTH;
            ui.position.left = this.minimumLeft;
        }

        const maxWidth = totalWidth - constants.MIN_WIDTH;

        if (width > maxWidth) {
            width = maxWidth;
            ui.position.left = this.firstPanel.el.offsetLeft + maxWidth;
        }

        this.firstPanel.$el.css('flex', `0 0 ${width}px`);
    },

    __onResizerDragHorizontal(ui) {
        let top = ui.position.top;

        if (top < constants.MIN_HEIGHT) {
            top = constants.MIN_HEIGHT;
            ui.position.top = this.minimumTop;
        }

        const maxHeight = this.originalParentHeight - constants.MIN_HEIGHT;

        if (top > maxHeight) {
            top = maxHeight;
            ui.position.top = maxHeight;
        }

        this.firstPanel.$el.css('flex', `0 0 ${top}px`);
    }
});
<|endoftext|>


<commit_before>(function (global, body) {

/**
 * Wrapper function for CommonJS modules.
 *
 * @public
 * @param {string} The complete file path.
 * @param {function} The wrapper function, which returns the module object
 */
var engine = global.E = function Engine (path, module) {

    // create CommonJS module directly if path is not loaded from a dependency list.
    if (!moduleCache[path]) {
        moduleCache[path] = module;
        createCommonJSModule(path);

    // emit path as event to create CommonJS modules in order,
    // after all resources are loaded.
    } else {
        var checkLoaded = moduleCache[path];
        moduleCache[path] = module;

        // call all load handlers
        for (var i = 0, l = checkLoaded.length; i < l; ++i) {
            checkLoaded[i]();
        }
    }
};

// module cache
var moduleCache = {};

// constants
var isPublicPath = /^\/[^/]/;
var isWorker = /^\(W|S\)/;
var checkFp = /\.@[a-z0-9]{7}\.(?:js|css|html)$/i;

/**
 * Load module scripts depedencies.
 *
 * @public
 * @param {array} The file paths.
 * @param {function} The callback handler.
 */
function load (scripts, callback) {

    // get the number of scripts
    var length = scripts.length;

    // ensure callback
    callback = callback || function () {};

    // create CommonJS module, when all scrips are loaded
    function moduleLoaded () {
        if (--length === 0) {
            evaluateScriptsInOrder(scripts, callback);
        }
    }

    // loop through scripts
    for (var i = length - 1, url, cleanPath, worker; i >= 0; --i) {

        url = scripts[i];

        // get worker info
        worker = false;
        if (isWorker.test(url)) {
            worker = url.substr(1,1);
            url = url.substr(3);
        }

        cleanPath = url;

        if (checkFp.test(url)) {

            // split path
            cleanPath = url.split('.');

            // remove fingerprint from read path
            cleanPath.splice(cleanPath.length - 2, 1);

            // create path without fingerprint
            cleanPath = cleanPath.join('.');
        }

        // append public file prefix
        if (isPublicPath.test(cleanPath)) {
            url = '/!' + url + (worker ? '' : '?w=1');

        // append module file prefix
        } else if (url.indexOf('://') < 0 && url.indexOf('//') !== 0) {
            url = '/@/@/' + url + (worker ? '' : '?w=1');

        // handle external files, that must be wrapped
        } else if (url[0] === '#') {
            url = '/@/@/!/' + url.substr(1) + (worker ? '' : '?w=1');
            cleanPath = cleanPath.substr(1);
        }

        // overwrite script path with path without fingerprints
        scripts[i] = cleanPath;

        // emit source event for already loaded scripts
        if (moduleCache[cleanPath] && moduleCache[cleanPath][0] !== moduleLoaded) {
            moduleLoaded();

        // load module scripts
        } else if (!moduleCache[cleanPath]) {

            // load a shared or dedicated worker
            if (worker) {
                moduleCache[cleanPath] = worker === 'S' ? new SharedWorker(url) : new Worker(url);
                moduleLoaded();
                continue;
            }

            // create script cache entry
            moduleCache[cleanPath] = [moduleLoaded];

            // crate script dom elemeent
            var node = body.createElement('script');

            // set url and append dom script elm to the document head
            node.src = url;
            body.head.appendChild(node);

        // push load handler method
        } else {
            moduleCache[cleanPath].push(moduleLoaded);
        }
    }
}

/**
 * Initialize CommonJS modules in order of the dependencies.
 *
 * @private
 * @param {object} .
 */
function evaluateScriptsInOrder (scripts, callback) {

    // init modules in order (desc)
    for (var i = (scripts.length - 1), l = 0; i >= l; --i) {

        // evaluate module script
        if (typeof moduleCache[scripts[i]] === 'function' && !moduleCache[scripts[i]]._eval) {
            createCommonJSModule(scripts[i]);
        }
    }

    // return module export
    callback(moduleCache[scripts[0]].exports);
}

/**
 * Evaluate/create CommonJS module.
 *
 * @public
 * @param {string} The script path.
 */
function createCommonJSModule(script) {

    var module = {
        id: script,
        exports: {}
    };

    var path = module.id.split('/');
    module.file = path.pop();
    module.base = path.join('/');

    // execute CommonJS module
    moduleCache[script] = moduleCache[script].call(module.exports, require(module), module, module.exports, global, engine);
    moduleCache[script]._eval = true;
}

function getNearestModulePath (module, name) {

    var path = '';

    // separate module name and path
    if (name.indexOf('/') > 0) {
        path = name.split('/');
        name = path.shift();
        path = path.join('/');
    }

    // TODO find a way to require a module without version
    /*var version = '0.1.0';
    var main = '';
    var versionMap = {
        view: {
            v: '0.1.0',
            m: 'main/file.js',
            s: {
                moduleName: {
                  v: '0.1.0',
                  m: 'trucken/client.js'
            }
        ]
    };

    for (var moduleId in versionMap) {

    }*/

    return  name + '@' + version + '/' + (path || main || 'index.js');
}

/**
 * The CommonJS require function.
 *
 * @private
 * @param {object} The module object.
 */
function require (module) {
    return function (name, callback) {

        // load a module resources and create a CommonJS module
        if (name instanceof Array) {
            return load(name, callback);
        }

        // handle different path types
        switch (name.indexOf('./')) {

            // external module
            case -1:

                // get the path from the module version relative to the base
                //name  = getNearestModulePath(module, name);
                break;

            // relative forward
            case 0:
                // ...create path with module base
                name = module.base + '/' + name.substr(2);
                break;

            // relative backward
            case 1:
                // ...create path with module base
                name = name.split('../');
                var stepsBack = name.length;
                var basePath = module.base.split('/');

                // return if module path is exceeded
                if (basePath.length < stepsBack) {
                    return;
                }

                // create new path
                name = basePath.slice(0, (stepsBack - 1) * -1).join('/') + '/' + name.pop();
        }

        name += name.slice(-3) !== '.js' ? '.js' : '';

        if (moduleCache[name]) {
            return moduleCache[name].exports || moduleCache[name];
        }
    };
}

})(this, document);
<commit_msg>check if script is evaluated<commit_after>(function (global, body) {

/**
 * Wrapper function for CommonJS modules.
 *
 * @public
 * @param {string} The complete file path.
 * @param {function} The wrapper function, which returns the module object
 */
var engine = global.E = function Engine (path, module) {

    // create CommonJS module directly if path is not loaded from a dependency list.
    if (!moduleCache[path]) {
        moduleCache[path] = module;
        createCommonJSModule(path);

    // emit path as event to create CommonJS modules in order,
    // after all resources are loaded.
    } else {
        var checkLoaded = moduleCache[path];
        moduleCache[path] = module;

        // call all load handlers
        for (var i = 0, l = checkLoaded.length; i < l; ++i) {
            checkLoaded[i]();
        }
    }
};

// module cache
var moduleCache = {};

// constants
var isPublicPath = /^\/[^/]/;
var isWorker = /^\(W|S\)/;
var checkFp = /\.@[a-z0-9]{7}\.(?:js|css|html)$/i;

/**
 * Load module scripts depedencies.
 *
 * @public
 * @param {array} The file paths.
 * @param {function} The callback handler.
 */
function load (scripts, callback) {

    // get the number of scripts
    var length = scripts.length;

    // ensure callback
    callback = callback || function () {};

    // create CommonJS module, when all scrips are loaded
    function moduleLoaded () {
        if (--length === 0) {
            evaluateScriptsInOrder(scripts, callback);
        }
    }

    // loop through scripts
    for (var i = length - 1, url, cleanPath, worker; i >= 0; --i) {

        url = scripts[i];

        // get worker info
        worker = false;
        if (isWorker.test(url)) {
            worker = url.substr(1,1);
            url = url.substr(3);
        }

        cleanPath = url;

        if (checkFp.test(url)) {

            // split path
            cleanPath = url.split('.');

            // remove fingerprint from read path
            cleanPath.splice(cleanPath.length - 2, 1);

            // create path without fingerprint
            cleanPath = cleanPath.join('.');
        }

        // append public file prefix
        if (isPublicPath.test(cleanPath)) {
            url = '/!' + url + (worker ? '' : '?w=1');

        // append module file prefix
        } else if (url.indexOf('://') < 0 && url.indexOf('//') !== 0) {
            url = '/@/@/' + url + (worker ? '' : '?w=1');

        // handle external files, that must be wrapped
        } else if (url[0] === '#') {
            url = '/@/@/!/' + url.substr(1) + (worker ? '' : '?w=1');
            cleanPath = cleanPath.substr(1);
        }

        // overwrite script path with path without fingerprints
        scripts[i] = cleanPath;

        // emit source event for already loaded scripts
        if (moduleCache[cleanPath] && moduleCache[cleanPath]._eval) {
            moduleLoaded();

        // load module scripts
        } else if (!moduleCache[cleanPath]) {

            // load a shared or dedicated worker
            if (worker) {
                moduleCache[cleanPath] = worker === 'S' ? new SharedWorker(url) : new Worker(url);
                moduleLoaded();
                continue;
            }

            // create script cache entry
            moduleCache[cleanPath] = [moduleLoaded];

            // crate script dom elemeent
            var node = body.createElement('script');

            // set url and append dom script elm to the document head
            node.src = url;
            body.head.appendChild(node);

        // push load handler method
        } else {
            moduleCache[cleanPath].push(moduleLoaded);
        }
    }
}

/**
 * Initialize CommonJS modules in order of the dependencies.
 *
 * @private
 * @param {object} .
 */
function evaluateScriptsInOrder (scripts, callback) {

    // init modules in order (desc)
    for (var i = (scripts.length - 1), l = 0; i >= l; --i) {

        // evaluate module script
        if (typeof moduleCache[scripts[i]] === 'function' && !moduleCache[scripts[i]]._eval) {
            createCommonJSModule(scripts[i]);
        }
    }

    // return module export
    callback(moduleCache[scripts[0]].exports);
}

/**
 * Evaluate/create CommonJS module.
 *
 * @public
 * @param {string} The script path.
 */
function createCommonJSModule(script) {

    var module = {
        id: script,
        exports: {}
    };

    var path = module.id.split('/');
    module.file = path.pop();
    module.base = path.join('/');

    // execute CommonJS module
    moduleCache[script] = moduleCache[script].call(module.exports, require(module), module, module.exports, global, engine);
    moduleCache[script]._eval = true;
}

function getNearestModulePath (module, name) {

    var path = '';

    // separate module name and path
    if (name.indexOf('/') > 0) {
        path = name.split('/');
        name = path.shift();
        path = path.join('/');
    }

    // TODO find a way to require a module without version
    /*var version = '0.1.0';
    var main = '';
    var versionMap = {
        view: {
            v: '0.1.0',
            m: 'main/file.js',
            s: {
                moduleName: {
                  v: '0.1.0',
                  m: 'trucken/client.js'
            }
        ]
    };

    for (var moduleId in versionMap) {

    }*/

    return  name + '@' + version + '/' + (path || main || 'index.js');
}

/**
 * The CommonJS require function.
 *
 * @private
 * @param {object} The module object.
 */
function require (module) {
    return function (name, callback) {

        // load a module resources and create a CommonJS module
        if (name instanceof Array) {
            return load(name, callback);
        }

        // handle different path types
        switch (name.indexOf('./')) {

            // external module
            case -1:

                // get the path from the module version relative to the base
                //name  = getNearestModulePath(module, name);
                break;

            // relative forward
            case 0:
                // ...create path with module base
                name = module.base + '/' + name.substr(2);
                break;

            // relative backward
            case 1:
                // ...create path with module base
                name = name.split('../');
                var stepsBack = name.length;
                var basePath = module.base.split('/');

                // return if module path is exceeded
                if (basePath.length < stepsBack) {
                    return;
                }

                // create new path
                name = basePath.slice(0, (stepsBack - 1) * -1).join('/') + '/' + name.pop();
        }

        name += name.slice(-3) !== '.js' ? '.js' : '';

        if (moduleCache[name]) {
            return moduleCache[name].exports || moduleCache[name];
        }
    };
}

})(this, document);
<|endoftext|>


<commit_before>
const RemoveAllHighlightsCommand = require('./commands/remove-all-highlights');
const UnhighlightCommand = require('./commands/unhighlight');
const ColourRegistry = require('./colour-registry');
const ConfigStore = require('./config-store');
const Debouncer = require('./debouncer');
const DecorationOperatorFactory = require('./decoration-operator-factory');
const DecorationRefresher = require('./decoration-refresher');
const DecorationRegistry = require('./decoration-registry');
const HighlightCommand = require('./commands/highlight');
const HighlightPatternPicker = require('./highlight-pattern-picker');
const HighlightUsingRegexCommand = require('./commands/highlight-using-regex');
const ToggleHighlightCommand = require('./commands/toggle-highlight');
const ToggleCaseSensitivityCommand = require('./commands/toggle-case-sensitivity');
const PatternFactory = require('./pattern-factory');
const RegexReader = require('./regex-reader');
const SelectedTextFinder = require('./selected-text-finder');
const TextDecorator = require('./text-decorator');
const TextLocator = require('./text-locator');
const generateUuid = require('uuid/v4');

class CommandFactory {

    constructor({vscode, logger}) {
        this._vscode = vscode;
        this._logger = logger;
    }

    createToggleHighlightCommand() {
        return new ToggleHighlightCommand({
            decorationOperatorFactory: this._getDecorationOperatorFactory(),
            selectedTextFinder: this._getSelectedTextFinder(),
            logger: this._logger,
            vsWindow: this._vscode.window,
            patternFactory: this._getPatternFactory()
        });
    }

    createHighlightCommand() {
        return new HighlightCommand({
            decorationOperatorFactory: this._getDecorationOperatorFactory(),
            selectedTextFinder: this._getSelectedTextFinder(),
            logger: this._logger,
            vsWindow: this._vscode.window,
            patternFactory: this._getPatternFactory()
        });
    }

    createHighlightUsingRegex() {
        return new HighlightUsingRegexCommand({
            decorationOperatorFactory: this._getDecorationOperatorFactory(),
            logger: this._logger,
            regexReader: new RegexReader({
                patternFactory: this._getPatternFactory(),
                vsWindow: this._vscode.window
            }),
            vsWindow: this._vscode.window
        });
    }

    createUnhighlightCommand() {
        const highlightPatternPicker = new HighlightPatternPicker({
            decorationRegistry: this._getDecorationRegistry(),
            vsWindow: this._vscode.window
        });
        return new UnhighlightCommand({
            decorationOperatorFactory: this._getDecorationOperatorFactory(),
            logger: this._logger,
            vsWindow: this._vscode.window,
            highlightPatternPicker
        });
    }

    createRemoveAllHighlightsCommand() {
        return new RemoveAllHighlightsCommand({
            decorationOperatorFactory: this._getDecorationOperatorFactory(),
            logger: this._logger,
            vsWindow: this._vscode.window
        });
    }

    createToggleCaseSensitivityCommand() {
        const highlightPatternPicker = new HighlightPatternPicker({
            decorationRegistry: this._getDecorationRegistry(),
            vsWindow: this._vscode.window
        });
        return new ToggleCaseSensitivityCommand({
            decorationOperatorFactory: this._getDecorationOperatorFactory(),
            logger: this._logger,
            vsWindow: this._vscode.window,
            highlightPatternPicker
        });
    }

    createDecorationRefresher() {
        return new DecorationRefresher({
            debouncer: new Debouncer({configStore: this._getConfigStore()}),
            decorationOperatorFactory: this._getDecorationOperatorFactory(),
            logger: this._logger,
            vsWindow: this._vscode.window
        });
    }

    _getSelectedTextFinder() {
        this._selectedTextFinder = this._selectedTextFinder || new SelectedTextFinder();
        return this._selectedTextFinder;
    }

    _getDecorationOperatorFactory() {
        this._decorationOperatorFactory = this._decorationOperatorFactory || this._createDecorationOperatorFactory();
        return this._decorationOperatorFactory;
    }

    _getConfigStore() {
        this._configStore = this._configStore || new ConfigStore({workspace: this._vscode.workspace});
        return this._configStore;
    }

    _getDecorationRegistry() {
        this._decorationRegistry = this._decorationRegistry || this._createDecorationRegistry();
        return this._decorationRegistry;
    }

    _createDecorationOperatorFactory() {
        const textLocator = new TextLocator({Range: this._vscode.Range});
        return new DecorationOperatorFactory({
            textDecorator: new TextDecorator({textLocator}),
            decorationRegistry: this._getDecorationRegistry()
        });
    }

    _createDecorationRegistry() {
        const colourRegistry = new ColourRegistry({configStore: this._getConfigStore()});
        return new DecorationRegistry({
            colourRegistry,
            generateUuid,
            window: this._vscode.window
        });
    }

    _getPatternFactory() {
        this._patternFactory = this._patternFactory || new PatternFactory();
    }
}

module.exports = CommandFactory;
<commit_msg>Fix the problem that patternFactory was not returned<commit_after>
const RemoveAllHighlightsCommand = require('./commands/remove-all-highlights');
const UnhighlightCommand = require('./commands/unhighlight');
const ColourRegistry = require('./colour-registry');
const ConfigStore = require('./config-store');
const Debouncer = require('./debouncer');
const DecorationOperatorFactory = require('./decoration-operator-factory');
const DecorationRefresher = require('./decoration-refresher');
const DecorationRegistry = require('./decoration-registry');
const HighlightCommand = require('./commands/highlight');
const HighlightPatternPicker = require('./highlight-pattern-picker');
const HighlightUsingRegexCommand = require('./commands/highlight-using-regex');
const ToggleHighlightCommand = require('./commands/toggle-highlight');
const ToggleCaseSensitivityCommand = require('./commands/toggle-case-sensitivity');
const PatternFactory = require('./pattern-factory');
const RegexReader = require('./regex-reader');
const SelectedTextFinder = require('./selected-text-finder');
const TextDecorator = require('./text-decorator');
const TextLocator = require('./text-locator');
const generateUuid = require('uuid/v4');

class CommandFactory {

    constructor({vscode, logger}) {
        this._vscode = vscode;
        this._logger = logger;
    }

    createToggleHighlightCommand() {
        return new ToggleHighlightCommand({
            decorationOperatorFactory: this._getDecorationOperatorFactory(),
            selectedTextFinder: this._getSelectedTextFinder(),
            logger: this._logger,
            vsWindow: this._vscode.window,
            patternFactory: this._getPatternFactory()
        });
    }

    createHighlightCommand() {
        return new HighlightCommand({
            decorationOperatorFactory: this._getDecorationOperatorFactory(),
            selectedTextFinder: this._getSelectedTextFinder(),
            logger: this._logger,
            vsWindow: this._vscode.window,
            patternFactory: this._getPatternFactory()
        });
    }

    createHighlightUsingRegex() {
        return new HighlightUsingRegexCommand({
            decorationOperatorFactory: this._getDecorationOperatorFactory(),
            logger: this._logger,
            regexReader: new RegexReader({
                patternFactory: this._getPatternFactory(),
                vsWindow: this._vscode.window
            }),
            vsWindow: this._vscode.window
        });
    }

    createUnhighlightCommand() {
        const highlightPatternPicker = new HighlightPatternPicker({
            decorationRegistry: this._getDecorationRegistry(),
            vsWindow: this._vscode.window
        });
        return new UnhighlightCommand({
            decorationOperatorFactory: this._getDecorationOperatorFactory(),
            logger: this._logger,
            vsWindow: this._vscode.window,
            highlightPatternPicker
        });
    }

    createRemoveAllHighlightsCommand() {
        return new RemoveAllHighlightsCommand({
            decorationOperatorFactory: this._getDecorationOperatorFactory(),
            logger: this._logger,
            vsWindow: this._vscode.window
        });
    }

    createToggleCaseSensitivityCommand() {
        const highlightPatternPicker = new HighlightPatternPicker({
            decorationRegistry: this._getDecorationRegistry(),
            vsWindow: this._vscode.window
        });
        return new ToggleCaseSensitivityCommand({
            decorationOperatorFactory: this._getDecorationOperatorFactory(),
            logger: this._logger,
            vsWindow: this._vscode.window,
            highlightPatternPicker
        });
    }

    createDecorationRefresher() {
        return new DecorationRefresher({
            debouncer: new Debouncer({configStore: this._getConfigStore()}),
            decorationOperatorFactory: this._getDecorationOperatorFactory(),
            logger: this._logger,
            vsWindow: this._vscode.window
        });
    }

    _getSelectedTextFinder() {
        this._selectedTextFinder = this._selectedTextFinder || new SelectedTextFinder();
        return this._selectedTextFinder;
    }

    _getDecorationOperatorFactory() {
        this._decorationOperatorFactory = this._decorationOperatorFactory || this._createDecorationOperatorFactory();
        return this._decorationOperatorFactory;
    }

    _getConfigStore() {
        this._configStore = this._configStore || new ConfigStore({workspace: this._vscode.workspace});
        return this._configStore;
    }

    _getDecorationRegistry() {
        this._decorationRegistry = this._decorationRegistry || this._createDecorationRegistry();
        return this._decorationRegistry;
    }

    _createDecorationOperatorFactory() {
        const textLocator = new TextLocator({Range: this._vscode.Range});
        return new DecorationOperatorFactory({
            textDecorator: new TextDecorator({textLocator}),
            decorationRegistry: this._getDecorationRegistry()
        });
    }

    _createDecorationRegistry() {
        const colourRegistry = new ColourRegistry({configStore: this._getConfigStore()});
        return new DecorationRegistry({
            colourRegistry,
            generateUuid,
            window: this._vscode.window
        });
    }

    _getPatternFactory() {
        this._patternFactory = this._patternFactory || new PatternFactory();
        return this._patternFactory;
    }
}

module.exports = CommandFactory;
<|endoftext|>


<commit_before>/**
 * Module dependencies.
 */
var os = require('os');
var lodashGet = require('lodash.get');
var flatten = require('flat');

/**
 * Main function that converts json to csv
 *
 * @param {Object} params Function parameters containing data, fields,
 * delimiter (default is ','), hasCSVColumnTitle (default is true)
 * and default value (default is '')
 * @param {Function} callback(err, csv) - Callback function
 *   if error, returning error in call back.
 *   if csv is created successfully, returning csv output to callback.
 */
module.exports = function (params, callback) {
  if (!callback || typeof callback !== 'function') {
    throw new Error('Callback is required');
  }

  checkParams(params, function (err) {
    if (err) {
      return callback(err);
    }

    var titles = createColumnTitles(params);
    var csv = createColumnContent(params, titles);

    callback(null, csv);
  });
};

/**
 * Check passing params
 *
 * @param {Object} params Function parameters containing data, fields,
 * delimiter, default value, mark quotes and hasCSVColumnTitle
 * @param {Function} callback Callback function returning error when invalid field is found
 */
function checkParams(params, callback) {
  params.data = params.data || [];

  // if data is an Object, not in array [{}], then just create 1 item array.
  // So from now all data in array of object format.
  if (!Array.isArray(params.data)) {
    params.data = [params.data];
  }

  if (params.flatten) {
    params.data = params.data.map(flatten);
  }

  // Set params.fields default to first data element's keys
  if (!params.fields && (params.data.length === 0 || typeof params.data[0] !== 'object')) {
    return callback(new Error('params should include "fields" and/or non-empty "data" array of objects'));
  }
  params.fields = params.fields || Object.keys(params.data[0]);

  //#check fieldNames
  if (params.fieldNames && params.fieldNames.length !== params.fields.length) {
    return callback(new Error('fieldNames and fields should be of the same length, if fieldNames is provided.'));
  }

  // Get fieldNames from fields
  params.fieldNames = params.fields.map(function (field, i) {
    if (params.fieldNames && typeof field === 'string') {
      return params.fieldNames[i];
    }
    return (typeof field === 'string') ? field : (field.label || field.value);
  });

  //#check delimiter
  params.del = params.del || ',';

  //#check end of line character
  params.eol = params.eol || '';

  //#check quotation mark
  params.quotes = typeof params.quotes === 'string' ? params.quotes : '"';

  //#check double quotes
  params.doubleQuotes = typeof params.doubleQuotes === 'string' ? params.doubleQuotes : Array(3).join(params.quotes);

  //#check default value
  params.defaultValue = params.defaultValue;

  //#check hasCSVColumnTitle, if it is not explicitly set to false then true.
  params.hasCSVColumnTitle = params.hasCSVColumnTitle !== false;

  callback(null);
}

/**
 * Create the title row with all the provided fields as column headings
 *
 * @param {Object} params Function parameters containing data, fields and delimiter
 * @returns {String} titles as a string
 */
function createColumnTitles(params) {
  var str = '';

  //if CSV has column title, then create it
  if (params.hasCSVColumnTitle) {
    params.fieldNames.forEach(function (element) {
      if (str !== '') {
        str += params.del;
      }
      str += JSON.stringify(element).replace(/\"/g, params.quotes);
    });
  }

  return str;
}

/**
 * Replace the quotation marks of the field element if needed (can be a not string-like item)
 *
 * @param {string} stringifiedElement The field element after JSON.stringify()
 * @param {string} quotes The params.quotes value. At this point we know that is not equal to double (")
 */
function replaceQuotationMarks(stringifiedElement, quotes) {
  var lastCharIndex = stringifiedElement.length - 1;

  //check if it's an string-like element
  if (stringifiedElement[0] === '"' && stringifiedElement[lastCharIndex] === '"') {
    //split the stringified field element because Strings are immutable
    var splitElement = stringifiedElement.split('');

    //replace the quotation marks
    splitElement[0] = quotes;
    splitElement[lastCharIndex] = quotes;

    //join again
    stringifiedElement = splitElement.join('');
  }

  return stringifiedElement;
}

/**
 * Create the content column by column and row by row below the title
 *
 * @param {Object} params Function parameters containing data, fields and delimiter
 * @param {String} str Title row as a string
 * @returns {String} csv string
 */
function createColumnContent(params, str) {
  params.data.forEach(function (dataElement) {
    //if null or empty object do nothing
    if (dataElement && Object.getOwnPropertyNames(dataElement).length > 0) {
      var line = '';
      var eol = params.newLine || os.EOL || '\n';

      params.fields.forEach(function (fieldElement) {
        var val;

        if (fieldElement && (typeof fieldElement === 'string' || typeof fieldElement.value === 'string')) {
          var path = (typeof fieldElement === 'string') ? fieldElement : fieldElement.value;
          var defaultValue = fieldElement.default || params.defaultValue;
          val = lodashGet(dataElement, path, defaultValue);
          if (val === null && defaultValue !== undefined){
            val = defaultValue;
          }
        } else if (fieldElement && typeof fieldElement.value === 'function') {
          val = fieldElement.value(dataElement) || fieldElement.default;
        }

        if (val !== undefined) {
          var stringifiedElement = JSON.stringify(val);

          if (typeof val === 'object') stringifiedElement = JSON.stringify(stringifiedElement);

          if (params.quotes !== '"') {
            stringifiedElement = replaceQuotationMarks(stringifiedElement, params.quotes);
          }

          //JSON.stringify('\\') results in a string with two backslash
          //characters in it. I.e. '\\\\'.
          stringifiedElement = stringifiedElement.replace(/\\\\/g, '\\');

         if (params.excelStrings) {
           stringifiedElement = '"="' + stringifiedElement + '""';
         }

          line += stringifiedElement;
        }

        line += params.del;
      });

      //remove last delimeter
      line = line.substring(0, line.length - 1);
      //Replace single quotes with double quotes. Single quotes are preceeded by
      //a backslash. Be careful not to remove backslash content from the string.
      line = line.split('\\\\').map(function (portion) {
        return portion.replace(/\\"/g, params.doubleQuotes);
      }).join('\\\\');
      //Remove the final excess backslashes from the stringified value.
      line = line.replace(/\\\\/g, '\\');
      //If header exists, add it, otherwise, print only content
      if (str !== '') {
        str += eol + line + params.eol;
      } else {
        str = line + params.eol;
      }
    }
  });

  return str;
}
<commit_msg>now only runs values of type string through excel formatter<commit_after>/**
 * Module dependencies.
 */
var os = require('os');
var lodashGet = require('lodash.get');
var flatten = require('flat');

/**
 * Main function that converts json to csv
 *
 * @param {Object} params Function parameters containing data, fields,
 * delimiter (default is ','), hasCSVColumnTitle (default is true)
 * and default value (default is '')
 * @param {Function} callback(err, csv) - Callback function
 *   if error, returning error in call back.
 *   if csv is created successfully, returning csv output to callback.
 */
module.exports = function (params, callback) {
  if (!callback || typeof callback !== 'function') {
    throw new Error('Callback is required');
  }

  checkParams(params, function (err) {
    if (err) {
      return callback(err);
    }

    var titles = createColumnTitles(params);
    var csv = createColumnContent(params, titles);

    callback(null, csv);
  });
};

/**
 * Check passing params
 *
 * @param {Object} params Function parameters containing data, fields,
 * delimiter, default value, mark quotes and hasCSVColumnTitle
 * @param {Function} callback Callback function returning error when invalid field is found
 */
function checkParams(params, callback) {
  params.data = params.data || [];

  // if data is an Object, not in array [{}], then just create 1 item array.
  // So from now all data in array of object format.
  if (!Array.isArray(params.data)) {
    params.data = [params.data];
  }

  if (params.flatten) {
    params.data = params.data.map(flatten);
  }

  // Set params.fields default to first data element's keys
  if (!params.fields && (params.data.length === 0 || typeof params.data[0] !== 'object')) {
    return callback(new Error('params should include "fields" and/or non-empty "data" array of objects'));
  }
  params.fields = params.fields || Object.keys(params.data[0]);

  //#check fieldNames
  if (params.fieldNames && params.fieldNames.length !== params.fields.length) {
    return callback(new Error('fieldNames and fields should be of the same length, if fieldNames is provided.'));
  }

  // Get fieldNames from fields
  params.fieldNames = params.fields.map(function (field, i) {
    if (params.fieldNames && typeof field === 'string') {
      return params.fieldNames[i];
    }
    return (typeof field === 'string') ? field : (field.label || field.value);
  });

  //#check delimiter
  params.del = params.del || ',';

  //#check end of line character
  params.eol = params.eol || '';

  //#check quotation mark
  params.quotes = typeof params.quotes === 'string' ? params.quotes : '"';

  //#check double quotes
  params.doubleQuotes = typeof params.doubleQuotes === 'string' ? params.doubleQuotes : Array(3).join(params.quotes);

  //#check default value
  params.defaultValue = params.defaultValue;

  //#check hasCSVColumnTitle, if it is not explicitly set to false then true.
  params.hasCSVColumnTitle = params.hasCSVColumnTitle !== false;

  callback(null);
}

/**
 * Create the title row with all the provided fields as column headings
 *
 * @param {Object} params Function parameters containing data, fields and delimiter
 * @returns {String} titles as a string
 */
function createColumnTitles(params) {
  var str = '';

  //if CSV has column title, then create it
  if (params.hasCSVColumnTitle) {
    params.fieldNames.forEach(function (element) {
      if (str !== '') {
        str += params.del;
      }
      str += JSON.stringify(element).replace(/\"/g, params.quotes);
    });
  }

  return str;
}

/**
 * Replace the quotation marks of the field element if needed (can be a not string-like item)
 *
 * @param {string} stringifiedElement The field element after JSON.stringify()
 * @param {string} quotes The params.quotes value. At this point we know that is not equal to double (")
 */
function replaceQuotationMarks(stringifiedElement, quotes) {
  var lastCharIndex = stringifiedElement.length - 1;

  //check if it's an string-like element
  if (stringifiedElement[0] === '"' && stringifiedElement[lastCharIndex] === '"') {
    //split the stringified field element because Strings are immutable
    var splitElement = stringifiedElement.split('');

    //replace the quotation marks
    splitElement[0] = quotes;
    splitElement[lastCharIndex] = quotes;

    //join again
    stringifiedElement = splitElement.join('');
  }

  return stringifiedElement;
}

/**
 * Create the content column by column and row by row below the title
 *
 * @param {Object} params Function parameters containing data, fields and delimiter
 * @param {String} str Title row as a string
 * @returns {String} csv string
 */
function createColumnContent(params, str) {
  params.data.forEach(function (dataElement) {
    //if null or empty object do nothing
    if (dataElement && Object.getOwnPropertyNames(dataElement).length > 0) {
      var line = '';
      var eol = params.newLine || os.EOL || '\n';

      params.fields.forEach(function (fieldElement) {
        var val;

        if (fieldElement && (typeof fieldElement === 'string' || typeof fieldElement.value === 'string')) {
          var path = (typeof fieldElement === 'string') ? fieldElement : fieldElement.value;
          var defaultValue = fieldElement.default || params.defaultValue;
          val = lodashGet(dataElement, path, defaultValue);
          if (val === null && defaultValue !== undefined){
            val = defaultValue;
          }
        } else if (fieldElement && typeof fieldElement.value === 'function') {
          val = fieldElement.value(dataElement) || fieldElement.default;
        }

        if (val !== undefined) {
          var stringifiedElement = JSON.stringify(val);

          if (typeof val === 'object') stringifiedElement = JSON.stringify(stringifiedElement);

          if (params.quotes !== '"') {
            stringifiedElement = replaceQuotationMarks(stringifiedElement, params.quotes);
          }

          //JSON.stringify('\\') results in a string with two backslash
          //characters in it. I.e. '\\\\'.
          stringifiedElement = stringifiedElement.replace(/\\\\/g, '\\');

          if (params.excelStrings && typeof val === 'string') {
            stringifiedElement = '"="' + stringifiedElement + '""';
          }

          line += stringifiedElement;
        }

        line += params.del;
      });

      //remove last delimeter
      line = line.substring(0, line.length - 1);
      //Replace single quotes with double quotes. Single quotes are preceeded by
      //a backslash. Be careful not to remove backslash content from the string.
      line = line.split('\\\\').map(function (portion) {
        return portion.replace(/\\"/g, params.doubleQuotes);
      }).join('\\\\');
      //Remove the final excess backslashes from the stringified value.
      line = line.replace(/\\\\/g, '\\');
      //If header exists, add it, otherwise, print only content
      if (str !== '') {
        str += eol + line + params.eol;
      } else {
        str = line + params.eol;
      }
    }
  });

  return str;
}
<|endoftext|>


<commit_before>// Generated by IcedCoffeeScript 1.7.1-a
(function() {
  var Base, BufferInStream, Command, E, TrackSubSubCommand, User, add_option_dict, dict_union, env, iced, log, make_esc, master_ring, __iced_k, __iced_k_noop,
    __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  iced = require('iced-coffee-script').iced;
  __iced_k = __iced_k_noop = function() {};

  Base = require('./base').Base;

  log = require('../log');

  add_option_dict = require('./argparse').add_option_dict;

  E = require('../err').E;

  TrackSubSubCommand = require('../tracksubsub').TrackSubSubCommand;

  BufferInStream = require('iced-spawn').BufferInStream;

  master_ring = require('../keyring').master_ring;

  make_esc = require('iced-error').make_esc;

  dict_union = require('../util').dict_union;

  User = require('../user').User;

  env = require('../env').env;

  exports.Command = Command = (function(_super) {
    __extends(Command, _super);

    function Command() {
      return Command.__super__.constructor.apply(this, arguments);
    }

    Command.prototype.OPTS = dict_union(TrackSubSubCommand.OPTS, {
      s: {
        alias: "sign",
        action: "storeTrue",
        help: "sign in addition to encrypting"
      },
      m: {
        alias: "message",
        help: "provide the message on the command line"
      },
      b: {
        alias: 'binary',
        action: "storeTrue",
        help: "output in binary (rather than ASCII/armored)"
      },
      o: {
        alias: 'output',
        help: 'the output file to write the encryption to'
      }
    });

    Command.prototype.add_subcommand_parser = function(scp) {
      var name, opts, sub;
      opts = {
        aliases: ["enc"],
        help: "verify a user's authenticity and optionally track him"
      };
      name = "encrypt";
      sub = scp.addParser(name, opts);
      add_option_dict(sub, this.OPTS);
      sub.addArgument(["them"], {
        nargs: 1,
        help: "the username of the receiver"
      });
      sub.addArgument(["file"], {
        nargs: '?',
        help: "the file to be encrypted"
      });
      return opts.aliases.concat([name]);
    };

    Command.prototype.do_encrypt = function(cb) {
      var args, err, gargs, o, out, sign_key, ti, tp, ___iced_passed_deferral, __iced_deferrals, __iced_k;
      __iced_k = __iced_k_noop;
      ___iced_passed_deferral = iced.findDeferral(arguments);
      tp = this.them.fingerprint(true);
      ti = this.them.key_id_64();
      args = ["--encrypt", "-r", tp, "--trust-mode", "always"];
      if (this.argv.sign) {
        sign_key = this.is_self ? this.them : this.tssc.me;
        args.push("--sign", "-u", sign_key.fingerprint(true));
      }
      gargs = {
        args: args
      };
      gargs.quiet = true;
      if ((o = this.argv.output)) {
        args.push("--output", o, "--yes");
      }
      if (!this.argv.binary) {
        args.push("-a");
      }
      if (this.argv.message) {
        gargs.stdin = new BufferInStream(this.argv.message);
      } else if (this.argv.file != null) {
        args.push(this.argv.file);
      } else {
        gargs.stdin = process.stdin;
      }
      (function(_this) {
        return (function(__iced_k) {
          __iced_deferrals = new iced.Deferrals(__iced_k, {
            parent: ___iced_passed_deferral,
            filename: "/Users/max/src/keybase/node-client/src/command/encrypt.iced",
            funcname: "Command.do_encrypt"
          });
          master_ring().gpg(gargs, __iced_deferrals.defer({
            assign_fn: (function() {
              return function() {
                err = arguments[0];
                return out = arguments[1];
              };
            })(),
            lineno: 71
          }));
          __iced_deferrals._fulfill();
        });
      })(this)((function(_this) {
        return function() {
          if (_this.argv.output == null) {
            log.console.log(out.toString(_this.argv.binary ? 'utf8' : 'binary'));
          }
          return cb(err);
        };
      })(this));
    };

    Command.prototype.run = function(cb) {
      var batch, esc, them_un, ___iced_passed_deferral, __iced_deferrals, __iced_k;
      __iced_k = __iced_k_noop;
      ___iced_passed_deferral = iced.findDeferral(arguments);
      esc = make_esc(cb, "Command::run");
      batch = !this.argv.message && (this.argv.file == null);
      them_un = this.argv.them[0];
      (function(_this) {
        return (function(__iced_k) {
          if (them_un === env().get_username()) {
            _this.is_self = true;
            (function(__iced_k) {
              __iced_deferrals = new iced.Deferrals(__iced_k, {
                parent: ___iced_passed_deferral,
                filename: "/Users/max/src/keybase/node-client/src/command/encrypt.iced",
                funcname: "Command.run"
              });
              User.load_me({
                secret: true
              }, esc(__iced_deferrals.defer({
                assign_fn: (function(__slot_1) {
                  return function() {
                    return __slot_1.them = arguments[0];
                  };
                })(_this),
                lineno: 84
              })));
              __iced_deferrals._fulfill();
            })(__iced_k);
          } else {
            _this.is_self = false;
            _this.tssc = new TrackSubSubCommand({
              args: {
                them: them_un
              },
              opts: _this.argv,
              batch: batch
            });
            (function(__iced_k) {
              __iced_deferrals = new iced.Deferrals(__iced_k, {
                parent: ___iced_passed_deferral,
                filename: "/Users/max/src/keybase/node-client/src/command/encrypt.iced",
                funcname: "Command.run"
              });
              _this.tssc.run(esc(__iced_deferrals.defer({
                lineno: 88
              })));
              __iced_deferrals._fulfill();
            })(function() {
              return __iced_k(_this.them = _this.tssc.them);
            });
          }
        });
      })(this)((function(_this) {
        return function() {
          (function(__iced_k) {
            __iced_deferrals = new iced.Deferrals(__iced_k, {
              parent: ___iced_passed_deferral,
              filename: "/Users/max/src/keybase/node-client/src/command/encrypt.iced",
              funcname: "Command.run"
            });
            _this.do_encrypt(esc(__iced_deferrals.defer({
              lineno: 90
            })));
            __iced_deferrals._fulfill();
          })(function() {
            return cb(null);
          });
        };
      })(this));
    };

    return Command;

  })(Base);

}).call(this);
<commit_msg>recompile with correct documentation<commit_after>// Generated by IcedCoffeeScript 1.7.1-a
(function() {
  var Base, BufferInStream, Command, E, TrackSubSubCommand, User, add_option_dict, dict_union, env, iced, log, make_esc, master_ring, __iced_k, __iced_k_noop,
    __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  iced = require('iced-coffee-script').iced;
  __iced_k = __iced_k_noop = function() {};

  Base = require('./base').Base;

  log = require('../log');

  add_option_dict = require('./argparse').add_option_dict;

  E = require('../err').E;

  TrackSubSubCommand = require('../tracksubsub').TrackSubSubCommand;

  BufferInStream = require('iced-spawn').BufferInStream;

  master_ring = require('../keyring').master_ring;

  make_esc = require('iced-error').make_esc;

  dict_union = require('../util').dict_union;

  User = require('../user').User;

  env = require('../env').env;

  exports.Command = Command = (function(_super) {
    __extends(Command, _super);

    function Command() {
      return Command.__super__.constructor.apply(this, arguments);
    }

    Command.prototype.OPTS = dict_union(TrackSubSubCommand.OPTS, {
      s: {
        alias: "sign",
        action: "storeTrue",
        help: "sign in addition to encrypting"
      },
      m: {
        alias: "message",
        help: "provide the message on the command line"
      },
      b: {
        alias: 'binary',
        action: "storeTrue",
        help: "output in binary (rather than ASCII/armored)"
      },
      o: {
        alias: 'output',
        help: 'the output file to write the encryption to'
      }
    });

    Command.prototype.add_subcommand_parser = function(scp) {
      var name, opts, sub;
      opts = {
        aliases: ["enc"],
        help: "encrypt a message and output to stdout or a file"
      };
      name = "encrypt";
      sub = scp.addParser(name, opts);
      add_option_dict(sub, this.OPTS);
      sub.addArgument(["them"], {
        nargs: 1,
        help: "the username of the receiver"
      });
      sub.addArgument(["file"], {
        nargs: '?',
        help: "the file to be encrypted"
      });
      return opts.aliases.concat([name]);
    };

    Command.prototype.do_encrypt = function(cb) {
      var args, err, gargs, o, out, sign_key, ti, tp, ___iced_passed_deferral, __iced_deferrals, __iced_k;
      __iced_k = __iced_k_noop;
      ___iced_passed_deferral = iced.findDeferral(arguments);
      tp = this.them.fingerprint(true);
      ti = this.them.key_id_64();
      args = ["--encrypt", "-r", tp, "--trust-mode", "always"];
      if (this.argv.sign) {
        sign_key = this.is_self ? this.them : this.tssc.me;
        args.push("--sign", "-u", sign_key.fingerprint(true));
      }
      gargs = {
        args: args
      };
      gargs.quiet = true;
      if ((o = this.argv.output)) {
        args.push("--output", o, "--yes");
      }
      if (!this.argv.binary) {
        args.push("-a");
      }
      if (this.argv.message) {
        gargs.stdin = new BufferInStream(this.argv.message);
      } else if (this.argv.file != null) {
        args.push(this.argv.file);
      } else {
        gargs.stdin = process.stdin;
      }
      (function(_this) {
        return (function(__iced_k) {
          __iced_deferrals = new iced.Deferrals(__iced_k, {
            parent: ___iced_passed_deferral,
            filename: "/Users/max/src/keybase/node-client/src/command/encrypt.iced",
            funcname: "Command.do_encrypt"
          });
          master_ring().gpg(gargs, __iced_deferrals.defer({
            assign_fn: (function() {
              return function() {
                err = arguments[0];
                return out = arguments[1];
              };
            })(),
            lineno: 71
          }));
          __iced_deferrals._fulfill();
        });
      })(this)((function(_this) {
        return function() {
          if (_this.argv.output == null) {
            log.console.log(out.toString(_this.argv.binary ? 'utf8' : 'binary'));
          }
          return cb(err);
        };
      })(this));
    };

    Command.prototype.run = function(cb) {
      var batch, esc, them_un, ___iced_passed_deferral, __iced_deferrals, __iced_k;
      __iced_k = __iced_k_noop;
      ___iced_passed_deferral = iced.findDeferral(arguments);
      esc = make_esc(cb, "Command::run");
      batch = !this.argv.message && (this.argv.file == null);
      them_un = this.argv.them[0];
      (function(_this) {
        return (function(__iced_k) {
          if (them_un === env().get_username()) {
            _this.is_self = true;
            (function(__iced_k) {
              __iced_deferrals = new iced.Deferrals(__iced_k, {
                parent: ___iced_passed_deferral,
                filename: "/Users/max/src/keybase/node-client/src/command/encrypt.iced",
                funcname: "Command.run"
              });
              User.load_me({
                secret: true
              }, esc(__iced_deferrals.defer({
                assign_fn: (function(__slot_1) {
                  return function() {
                    return __slot_1.them = arguments[0];
                  };
                })(_this),
                lineno: 84
              })));
              __iced_deferrals._fulfill();
            })(__iced_k);
          } else {
            _this.is_self = false;
            _this.tssc = new TrackSubSubCommand({
              args: {
                them: them_un
              },
              opts: _this.argv,
              batch: batch
            });
            (function(__iced_k) {
              __iced_deferrals = new iced.Deferrals(__iced_k, {
                parent: ___iced_passed_deferral,
                filename: "/Users/max/src/keybase/node-client/src/command/encrypt.iced",
                funcname: "Command.run"
              });
              _this.tssc.run(esc(__iced_deferrals.defer({
                lineno: 88
              })));
              __iced_deferrals._fulfill();
            })(function() {
              return __iced_k(_this.them = _this.tssc.them);
            });
          }
        });
      })(this)((function(_this) {
        return function() {
          (function(__iced_k) {
            __iced_deferrals = new iced.Deferrals(__iced_k, {
              parent: ___iced_passed_deferral,
              filename: "/Users/max/src/keybase/node-client/src/command/encrypt.iced",
              funcname: "Command.run"
            });
            _this.do_encrypt(esc(__iced_deferrals.defer({
              lineno: 90
            })));
            __iced_deferrals._fulfill();
          })(function() {
            return cb(null);
          });
        };
      })(this));
    };

    return Command;

  })(Base);

}).call(this);
<|endoftext|>


<commit_before>var fs = require('fs');

var h = require('../helper');
var config = require('../config');
var log = require('../log');
var Plugin = require('../plugin');
var session = require('../session');

var cmd = {
  command: 'plugin [name]',
  aliases: ['extension', 'ext'],
  desc:    'show plugins',
  builder: {
    install: {
      alias:    'i',
      type:     'boolean',
      describe: 'Install plugin',
      default:  false
    },
    enable: {
      alias:    'e',
      type:     'boolean',
      describe: 'Enable plugin',
      default:  false
    },
    disable: {
      alias:    'd',
      type:     'boolean',
      describe: 'Disable plugin',
      default:  false
    },
    delete: {
      alias:    'D',
      type:     'boolean',
      describe: 'Delete plugin',
      default:  false
    },
    config: {
      alias:    'c',
      type:     'boolean',
      describe: 'Show config',
      default:  false
    }
  }
};

cmd.handler = function(argv) {
  session.argv = argv;

  var name = argv.name;
  if (argv.install) {
    Plugin.install(name, function(e, plugin) {
      if (e) return log.error(e);
      plugin.help();
    });
    return;
  }

  var plugins = Plugin.plugins;
  if (name) {
    plugins = plugins.filter(function(p) {
      return p.name === name;
    });
  }
  if (plugins.length === 0) return log.error('Plugin not found!');

  var plugin = plugins[0];
  var oldname = h.getPluginFile(plugin.file);
  var newname;

  if (argv.enable) {
    if (plugin.file[0] !== '.') return;
    newname = h.getPluginFile(plugin.file.substr(1));

    fs.rename(oldname, newname, function(e) {
      if (e) log.error(e.message);
    });
  } else if (argv.disable) {
    if (plugin.file[0] === '.') return;
    newname = h.getPluginFile('.' + plugin.file);

    fs.rename(oldname, newname, function(e) {
      if (e) log.error(e.message);
    });
  } else if (argv.delete) {
    fs.unlink(oldname, function(e) {
      if (e) log.error(e.message);
    });
  } else if (argv.config) {
    log.info(JSON.stringify(config.plugins[name] || {}, null, 2));
  } else {
    plugins.forEach(function(p) {
      log.printf('%s %-18s %-15s %s', h.prettyText('', p.enabled), p.name, p.ver, p.desc);
    });
  }
};

module.exports = cmd;
<commit_msg>Refactor `plugin` a bit.<commit_after>var fs = require('fs');

var h = require('../helper');
var config = require('../config');
var log = require('../log');
var Plugin = require('../plugin');
var session = require('../session');

var cmd = {
  command: 'plugin [name]',
  aliases: ['extension', 'ext'],
  desc:    'show plugins',
  builder: {
    install: {
      alias:    'i',
      type:     'boolean',
      describe: 'Install plugin',
      default:  false
    },
    enable: {
      alias:    'e',
      type:     'boolean',
      describe: 'Enable plugin',
      default:  false
    },
    disable: {
      alias:    'd',
      type:     'boolean',
      describe: 'Disable plugin',
      default:  false
    },
    delete: {
      alias:    'D',
      type:     'boolean',
      describe: 'Delete plugin',
      default:  false
    },
    config: {
      alias:    'c',
      type:     'boolean',
      describe: 'Show config',
      default:  false
    }
  }
};

cmd.handler = function(argv) {
  session.argv = argv;

  var name = argv.name;
  if (argv.install) {
    Plugin.install(name, function(e, plugin) {
      if (e) return log.error(e);
      plugin.help();
    });
    return;
  }

  var plugins = Plugin.plugins;
  if (name) {
    plugins = plugins.filter(function(p) {
      return p.name === name;
    });
  }
  if (plugins.length === 0) return log.error('Plugin not found!');

  var plugin = plugins[0];
  var fullpath = h.getPluginFile(plugin.file);
  var newname;

  if (argv.enable) {
    if (plugin.enabled) return;
    newname = h.getPluginFile(plugin.file.substr(1));

    fs.rename(fullpath, newname, function(e) {
      if (e) log.error(e.message);
    });
  } else if (argv.disable) {
    if (!plugin.enabled) return;
    newname = h.getPluginFile('.' + plugin.file);

    fs.rename(fullpath, newname, function(e) {
      if (e) log.error(e.message);
    });
  } else if (argv.delete) {
    fs.unlink(fullpath, function(e) {
      if (e) log.error(e.message);
    });
  } else if (argv.config) {
    log.info(JSON.stringify(config.plugins[name] || {}, null, 2));
  } else {
    plugins.forEach(function(p) {
      log.printf('%s %-18s %-15s %s', h.prettyText('', p.enabled), p.name, p.ver, p.desc);
    });
  }
};

module.exports = cmd;
<|endoftext|>


<commit_before>/**
 * KeyPair
 * =======
 *
 * A keyPair is a collection of a private key and a public key.
 * let keyPair = new KeyPair().fromRandom()
 * let keyPair = new KeyPair().fromPrivKey(privKey)
 * let privKey = keyPair.privKey
 * let pubKey = keyPair.pubKey
 */
'use strict'
let dependencies = {
  PrivKey: require('./priv-key'),
  PubKey: require('./pub-key'),
  Struct: require('./struct'),
  Bw: require('./bw'),
  asink: require('asink')
}

let inject = function (deps) {
  let PrivKey = deps.PrivKey
  let PubKey = deps.PubKey
  let Struct = deps.Struct
  let Bw = deps.Bw
  let asink = deps.asink

  class KeyPair extends Struct {
    constructor (privKey, pubKey) {
      super({privKey, pubKey})
    }

    fromJson (json) {
      this.fromObject({
        privKey: new PrivKey().fromJson(json.privKey),
        pubKey: new PubKey().fromJson(json.pubKey)
      })
      return this
    }

    toJson () {
      let json = {
        privKey: this.privKey.toJson(),
        pubKey: this.pubKey.toJson()
      }
      return json
    }

    fromBr (br) {
      let buflen1 = br.readUInt8()
      if (buflen1 > 0) {
        this.privKey = new PrivKey().fromFastBuffer(br.read(buflen1))
      }
      let buflen2 = br.readUInt8()
      if (buflen2 > 0) {
        this.pubKey = new PubKey().fromFastBuffer(br.read(buflen2))
      }
      return this
    }

    toBw (bw) {
      if (!bw) {
        bw = new Bw()
      }
      if (this.privKey) {
        let privKeybuf = this.privKey.toFastBuffer()
        bw.writeUInt8(privKeybuf.length)
        bw.write(privKeybuf)
      } else {
        bw.writeUInt8(0)
      }
      if (this.pubKey) {
        let pubKeybuf = this.pubKey.toFastBuffer()
        bw.writeUInt8(pubKeybuf.length)
        bw.write(pubKeybuf)
      } else {
        bw.writeUInt8(0)
      }
      return bw
    }

    fromString (str) {
      return this.fromJson(JSON.parse(str))
    }

    toString () {
      return JSON.stringify(this.toJson())
    }

    toPublic () {
      let keyPair = new KeyPair().fromObject(this)
      keyPair.privKey = undefined
      return keyPair
    }

    fromPrivKey (privKey) {
      this.privKey = privKey
      this.pubKey = new PubKey().fromPrivKey(privKey)
      return this
    }

    static fromPrivKey (privKey) {
      return new this().fromPrivKey(privKey)
    }

    asyncFromPrivKey (privKey) {
      return asink(function * () {
        this.privKey = privKey
        this.pubKey = yield new PubKey().asyncFromPrivKey(privKey)
        return this
      }, this)
    }

    static asyncFromPrivKey (privKey) {
      return new this().asyncFromPrivKey(privKey)
    }

    fromRandom () {
      this.privKey = new PrivKey().fromRandom()
      this.pubKey = new PubKey().fromPrivKey(this.privKey)
      return this
    }

    static fromRandom () {
      return new this().fromRandom()
    }

    asyncFromRandom () {
      return asink(function * () {
        this.privKey = new PrivKey().fromRandom()
        return this.asyncFromPrivKey(this.privKey)
      }, this)
    }

    static asyncFromRandom () {
      return new this().asyncFromRandom()
    }
  }

  return KeyPair
}

inject = require('injecter')(inject, dependencies)
let KeyPair = inject()
KeyPair.Mainnet = inject({
  PrivKey: require('./priv-key').Mainnet
})
KeyPair.Testnet = inject({
  PrivKey: require('./priv-key').Testnet
})
module.exports = KeyPair
<commit_msg>toJson and fromJson now work in conjunction with toPublic<commit_after>/**
 * KeyPair
 * =======
 *
 * A keyPair is a collection of a private key and a public key.
 * let keyPair = new KeyPair().fromRandom()
 * let keyPair = new KeyPair().fromPrivKey(privKey)
 * let privKey = keyPair.privKey
 * let pubKey = keyPair.pubKey
 */
'use strict'
let dependencies = {
  PrivKey: require('./priv-key'),
  PubKey: require('./pub-key'),
  Struct: require('./struct'),
  Bw: require('./bw'),
  asink: require('asink')
}

let inject = function (deps) {
  let PrivKey = deps.PrivKey
  let PubKey = deps.PubKey
  let Struct = deps.Struct
  let Bw = deps.Bw
  let asink = deps.asink

  class KeyPair extends Struct {
    constructor (privKey, pubKey) {
      super({privKey, pubKey})
    }

    fromJson (json) {
      if (json.privKey) {
        this.privKey = PrivKey.fromJson(json.privKey)
      }
      if (json.pubKey) {
        this.pubKey = PubKey.fromJson(json.pubKey)
      }
      return this
    }

    toJson () {
      let json = {}
      if (this.privKey && this.privKey !== undefined) {
        json.privKey = this.privKey.toJson()
      }
      if (this.pubKey && this.pubKey !== undefined) {
        json.pubKey = this.pubKey.toJson()
      }
      return json
    }

    fromBr (br) {
      let buflen1 = br.readUInt8()
      if (buflen1 > 0) {
        this.privKey = new PrivKey().fromFastBuffer(br.read(buflen1))
      }
      let buflen2 = br.readUInt8()
      if (buflen2 > 0) {
        this.pubKey = new PubKey().fromFastBuffer(br.read(buflen2))
      }
      return this
    }

    toBw (bw) {
      if (!bw) {
        bw = new Bw()
      }
      if (this.privKey) {
        let privKeybuf = this.privKey.toFastBuffer()
        bw.writeUInt8(privKeybuf.length)
        bw.write(privKeybuf)
      } else {
        bw.writeUInt8(0)
      }
      if (this.pubKey) {
        let pubKeybuf = this.pubKey.toFastBuffer()
        bw.writeUInt8(pubKeybuf.length)
        bw.write(pubKeybuf)
      } else {
        bw.writeUInt8(0)
      }
      return bw
    }

    fromString (str) {
      return this.fromJson(JSON.parse(str))
    }

    toString () {
      return JSON.stringify(this.toJson())
    }

    toPublic () {
      let keyPair = new KeyPair().fromObject(this)
      keyPair.privKey = undefined
      return keyPair
    }

    fromPrivKey (privKey) {
      this.privKey = privKey
      this.pubKey = new PubKey().fromPrivKey(privKey)
      return this
    }

    static fromPrivKey (privKey) {
      return new this().fromPrivKey(privKey)
    }

    asyncFromPrivKey (privKey) {
      return asink(function * () {
        this.privKey = privKey
        this.pubKey = yield new PubKey().asyncFromPrivKey(privKey)
        return this
      }, this)
    }

    static asyncFromPrivKey (privKey) {
      return new this().asyncFromPrivKey(privKey)
    }

    fromRandom () {
      this.privKey = new PrivKey().fromRandom()
      this.pubKey = new PubKey().fromPrivKey(this.privKey)
      return this
    }

    static fromRandom () {
      return new this().fromRandom()
    }

    asyncFromRandom () {
      return asink(function * () {
        this.privKey = new PrivKey().fromRandom()
        return this.asyncFromPrivKey(this.privKey)
      }, this)
    }

    static asyncFromRandom () {
      return new this().asyncFromRandom()
    }
  }

  return KeyPair
}

inject = require('injecter')(inject, dependencies)
let KeyPair = inject()
KeyPair.Mainnet = inject({
  PrivKey: require('./priv-key').Mainnet
})
KeyPair.Testnet = inject({
  PrivKey: require('./priv-key').Testnet
})
module.exports = KeyPair
<|endoftext|>


<commit_before>var fs             = require('fs')
  , util           = require('util')
  , path           = require('path')
  , rework         = require('rework')
  , ejs            = require('ejs')
  , colors         = require('colors')
  , express        = require('express')
  , sass_functions = require('./sass_functions');

/**
 * JSON parses the manifest.json file if it exists
 */
function parseManifest(manifest_path){
  if (!fs.existsSync(manifest_path)) return console.error(manifest_path + " does not exist");
  var manifest = fs.readFileSync(manifest_path, 'utf8');
  return JSON.parse(manifest);
}

/**
 * Loades all hdsb files in `templates_path` and concatenates them into
 * one string
 *
 * @param templates_path String path to the template directory
 */
function compileTemplates(templates_path) {
  var files = fs.readdirSync(templates_path);
  var templates = {};
  files.forEach(function(file){
    var name = file.split('.')[0];
    var template = fs.readFileSync(path.join(templates_path, file), 'utf8');
    templates[name] = template;
  });

  return templates;
}

/**
 * Creates the app.js file
 *
 * @param app_path String path to the directory containing the Zendesk app
 * @returns appjs String return app.js
 */
function readified_js(app_path, id){
  if (!app_path) return;

  if (!fs.existsSync(app_path)) return console.error(app_path + " does not exist");

  var manifest = parseManifest(path.join(app_path, 'manifest.json'))
    , name = manifest.name || 'Local App'
    , location = manifest.location
    , translations = JSON.parse(fs.readFileSync(path.join(app_path, 'translations', 'en.json'), 'utf8'))
    , framework_version = manifest.frameworkVersion
    , asset_url_prefix = 'http://localhost:4567/'
    // hardcoding for the moment
    , app_id = id || 0
    , app_class_name = util.format("app-%d", app_id)
    , default_styles = fs.readFileSync(path.join(__dirname, 'assets', 'default_styles.css'), 'utf8')
    , css_file = path.join(app_path, 'app.css');

  // TODO: prompt user for settings
  var settings = {'title': name};

  if (manifest.parameters){
    manifest.parameters.forEach(function(param){
      if (param.default) settings[param.name] = param.default;
    });
  }

  if (fs.existsSync(css_file))
    default_styles += fs.readFileSync(css_file);

  var css = rework(default_styles)
    .use(rework.function({
      "app-asset-url": function(asset){
        return sass_functions.app_asset_url(asset_url_prefix, asset);
      }
    }))
    .use(rework.prefixSelectors(util.format(".%s", app_class_name)))
    .toString();
  var templates = compileTemplates(path.join(app_path, 'templates'));
  templates.layout = util.format('<style>\n%s</style>\n%s', css, templates.layout);

  var src_templ = fs.readFileSync(path.join(__dirname, 'assets', 'src.ejs'), 'utf8')
    , appjs = ejs.render(src_templ, {
      name: name,
      source: fs.readFileSync(path.join(app_path, 'app.js'), 'utf8'),
      location: location,
      asset_url_prefix: asset_url_prefix,
      app_class_name: app_class_name,
      author: manifest.author,
      translations: translations,
      framework_version: framework_version,
      templates: templates,
      settings: settings,
      app_id: app_id
    });

    return appjs;

};

module.exports.readified_js = readified_js;

module.exports.command = function(env){
  var app_path = env.path || '.';

  process.title = 'zapt';

  var app = express();
  app.use(express.compress());

  app.get('/app.js', function(req, res){
    console.log((new Date()).toString().grey + ' - GET '.green + req.originalUrl);
    res.set('Content-Type', 'text/javascript');
    res.send(readified_js(app_path));
  });

  app.get('*', function(req, res){
    console.log((new Date()).toString().grey + ' - GET '.green + req.originalUrl);
    if (req.path && req.path.match(/png/) ){
      var p = path.join(app_path, 'assets', req.path);
      if (fs.existsSync(p)){
        return fs.createReadStream(p).pipe(res);
      }
      res.send(404);
    }
  });

  app.listen(4567,  function(){
    console.log('listening');
  });

}
<commit_msg>utf8 please<commit_after>var fs             = require('fs')
  , util           = require('util')
  , path           = require('path')
  , rework         = require('rework')
  , ejs            = require('ejs')
  , colors         = require('colors')
  , express        = require('express')
  , sass_functions = require('./sass_functions');

/**
 * JSON parses the manifest.json file if it exists
 */
function parseManifest(manifest_path){
  if (!fs.existsSync(manifest_path)) return console.error(manifest_path + " does not exist");
  var manifest = fs.readFileSync(manifest_path, 'utf8');
  return JSON.parse(manifest);
}

/**
 * Loades all hdsb files in `templates_path` and concatenates them into
 * one string
 *
 * @param templates_path String path to the template directory
 */
function compileTemplates(templates_path) {
  var files = fs.readdirSync(templates_path);
  var templates = {};
  files.forEach(function(file){
    var name = file.split('.')[0];
    var template = fs.readFileSync(path.join(templates_path, file), 'utf8');
    templates[name] = template;
  });

  return templates;
}

/**
 * Creates the app.js file
 *
 * @param app_path String path to the directory containing the Zendesk app
 * @returns appjs String return app.js
 */
function readified_js(app_path, id){
  if (!app_path) return;

  if (!fs.existsSync(app_path)) return console.error(app_path + " does not exist");

  var manifest = parseManifest(path.join(app_path, 'manifest.json'))
    , name = manifest.name || 'Local App'
    , location = manifest.location
    , translations = JSON.parse(fs.readFileSync(path.join(app_path, 'translations', 'en.json'), 'utf8'))
    , framework_version = manifest.frameworkVersion
    , asset_url_prefix = 'http://localhost:4567/'
    // hardcoding for the moment
    , app_id = id || 0
    , app_class_name = util.format("app-%d", app_id)
    , default_styles = fs.readFileSync(path.join(__dirname, 'assets', 'default_styles.css'), 'utf8')
    , css_file = path.join(app_path, 'app.css');

  // TODO: prompt user for settings
  var settings = {'title': name};

  if (manifest.parameters){
    manifest.parameters.forEach(function(param){
      if (param.default) settings[param.name] = param.default;
    });
  }

  if (fs.existsSync(css_file))
    default_styles += fs.readFileSync(css_file);

  var css = rework(default_styles)
    .use(rework.function({
      "app-asset-url": function(asset){
        return sass_functions.app_asset_url(asset_url_prefix, asset);
      }
    }))
    .use(rework.prefixSelectors(util.format(".%s", app_class_name)))
    .toString();
  var templates = compileTemplates(path.join(app_path, 'templates'));
  templates.layout = util.format('<style>\n%s</style>\n%s', css, templates.layout);

  var src_templ = fs.readFileSync(path.join(__dirname, 'assets', 'src.ejs'), 'utf8')
    , appjs = ejs.render(src_templ, {
      name: name,
      source: fs.readFileSync(path.join(app_path, 'app.js'), 'utf8'),
      location: location,
      asset_url_prefix: asset_url_prefix,
      app_class_name: app_class_name,
      author: manifest.author,
      translations: translations,
      framework_version: framework_version,
      templates: templates,
      settings: settings,
      app_id: app_id
    });

    return appjs;

};

module.exports.readified_js = readified_js;

module.exports.command = function(env){
  var app_path = env.path || '.';

  process.title = 'zapt';

  var app = express();
  app.use(express.compress());

  app.get('/app.js', function(req, res){
    console.log((new Date()).toString().grey + ' - GET '.green + req.originalUrl);
    res.set('Content-Type', 'text/javascript; charset=utf8');
    res.send(readified_js(app_path));
  });

  app.get('*', function(req, res){
    console.log((new Date()).toString().grey + ' - GET '.green + req.originalUrl);
    if (req.path && req.path.match(/png/) ){
      var p = path.join(app_path, 'assets', req.path);
      if (fs.existsSync(p)){
        return fs.createReadStream(p).pipe(res);
      }
      res.send(404);
    }
  });

  app.listen(4567,  function(){
    console.log('listening');
  });

}
<|endoftext|>