<commit_before>'use strict';

// First, check for JSON support
// If there is no JSON, we no-op the core features of Raven
// since JSON is required to encode the payload
var _Raven = window.Raven,
    hasJSON = !!(window.JSON && window.JSON.stringify),
    globalServer,
    globalUser,
    globalKey,
    globalProject,
    globalOptions = {
        logger: 'javascript',
        ignoreUrls: []
    };

var TK = TraceKit.noConflict();

// Disable Tracekit's remote fetching by default
TK.remoteFetching = false;

/*
 * The core Raven singleton
 *
 * @this {Raven}
 */
var Raven = {
    VERSION: '@VERSION',

    /*
     * Allow multiple versions of Raven to be installed.
     * Strip Raven from the global context and returns the instance.
     *
     * @return {Raven}
     */
    noConflict: function() {
        window.Raven = _Raven;
        return Raven;
    },

    /*
     * Configure Raven with a DSN and extra options
     *
     * @param {string} dsn The public Sentry DSN
     * @param {object} options Optional set of of global options [optional]
     * @return {Raven}
     */
    config: function(dsn, options) {
        var uri = parseUri(dsn),
            lastSlash = uri.path.lastIndexOf('/'),
            path = uri.path.substr(1, lastSlash);

        if (options && options.ignoreErrors && window.console && console.warn) {
            console.warn('DeprecationWarning: `ignoreErrors` is going to be removed soon.');
        }

        // merge in options
        if (options) {
            each(options, function(key, value){
                globalOptions[key] = value;
            });
        }

        globalKey = uri.user;
        globalProject = ~~uri.path.substr(lastSlash + 1);

        // assemble the endpoint from the uri pieces
        globalServer = '//' + uri.host +
                      (uri.port ? ':' + uri.port : '') +
                      '/' + path + 'api/' + globalProject + '/store/';

        if (uri.protocol) {
            globalServer = uri.protocol + ':' + globalServer;
        }

        if (globalOptions.fetchContext) {
            TK.remoteFetching = true;
        }

        // return for chaining
        return Raven;
    },

    /*
     * Installs a global window.onerror error handler
     * to capture and report uncaught exceptions.
     * At this point, install() is required to be called due
     * to the way TraceKit is set up.
     *
     * @return {Raven}
     */
    install: function() {
        if (!isSetup()) return;

        TK.report.subscribe(handleStackInfo);

        return Raven;
    },

    /*
     * Wrap code within a context so Raven can capture errors
     * reliably across domains that is executed immediately.
     *
     * @param {object} options A specific set of options for this context [optional]
     * @param {function} func The callback to be immediately executed within the context
     * @param {array} args An array of arguments to be called with the callback [optional]
     */
    context: function(options, func, args) {
        if (isFunction(options)) {
            args = func || [];
            func = options;
            options = undefined;
        }

        Raven.wrap(options, func).apply(this, args);
    },

    /*
     * Wrap code within a context and returns back a new function to be executed
     *
     * @param {object} options A specific set of options for this context [optional]
     * @param {function} func The function to be wrapped in a new context
     * @return {function} The newly wrapped functions with a context
     */
    wrap: function(options, func) {
        // options is optional
        if (isFunction(options)) {
            func = options;
            options = undefined;
        }

        return function() {
            try {
                func.apply(this, arguments);
            } catch(e) {
                Raven.captureException(e, options);
                throw e;
            }
        };
    },

    /*
     * Uninstalls the global error handler.
     *
     * @return {Raven}
     */
    uninstall: function() {
        TK.report.unsubscribe(handleStackInfo);

        return Raven;
    },

    /*
     * Manually capture an exception and send it over to Sentry
     *
     * @param {error} ex An exception to be logged
     * @param {object} options A specific set of options for this error [optional]
     * @return {Raven}
     */
    captureException: function(ex, options) {
        // If a string is passed through, recall as a message
        if (typeof ex === 'string') {
            return Raven.captureMessage(ex, options);
        }

        // TraceKit.report will re-raise any exception passed to it,
        // which means you have to wrap it in try/catch. Instead, we
        // can wrap it here and only re-raise if TraceKit.report
        // raises an exception different from the one we asked to
        // report on.
        try {
            TK.report(ex, options);
        } catch(ex1) {
            if(ex !== ex1) {
                throw ex1;
            }
        }

        return Raven;
    },

    /*
     * Manually send a message to Sentry
     *
     * @param {string} msg A plain message to be captured in Sentry
     * @param {object} options A specific set of options for this message [optional]
     * @return {Raven}
     */
    captureMessage: function(msg, options) {
        // Fire away!
        send(
            arrayMerge({
                message: msg
            }, options)
        );

        return Raven;
    },

    /*
     * Set/clear a user to be sent along with the payload.
     *
     * @param {object} user An object representing user data [optional]
     * @return {Raven}
     */
    setUser: function(user) {
       globalUser = user;

       return Raven;
    }
};

var uriKeys = 'source protocol authority userInfo user password host port relative path directory file query anchor'.split(' '),
    uriPattern = /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/;

/**** Private functions ****/
function parseUri(str) {
    var m = uriPattern.exec(str),
        uri = {},
        i = 14;

    while (i--) uri[uriKeys[i]] = m[i] || '';

    return uri;
}

function isUndefined(what) {
    return typeof what === 'undefined';
}

function isFunction(what) {
    return typeof what === 'function';
}

function each(obj, callback) {
    var i, j;

    if (isUndefined(obj.length)) {
        for (i in obj) {
            if (obj.hasOwnProperty(i)) {
                callback.call(null, i, obj[i]);
            }
        }
    } else {
        j = obj.length;
        if (j) {
            for (i = 0; i < j; i++) {
                callback.call(null, i, obj[i]);
            }
        }
    }
}

var cachedAuth;

function getAuthQueryString() {
    if (cachedAuth) return cachedAuth;

    var qs = [
        'sentry_version=2.0',
        'sentry_client=raven-js/' + Raven.VERSION
    ];
    if (globalKey) {
        qs.push('sentry_key=' + globalKey);
    }

    cachedAuth = '?' + qs.join('&');
    return cachedAuth;
}

function handleStackInfo(stackInfo, options) {
    var frames = [];

    if (stackInfo.stack && stackInfo.stack.length) {
        each(stackInfo.stack, function(i, stack) {
            var frame = normalizeFrame(stack);
            if (frame) {
                frames.push(frame);
            }
        });
    }

    processException(
        stackInfo.name,
        stackInfo.message,
        stackInfo.url,
        stackInfo.lineno,
        frames,
        options
    );
}

function normalizeFrame(frame) {
    if (!frame.url) return;

    // normalize the frames data
    var normalized = {
        filename:   frame.url,
        lineno:     frame.line,
        colno:      frame.column,
        'function': frame.func || '?'
    }, context = extractContextFromFrame(frame);

    if (context) {
        var i = 3, keys = ['pre_context', 'context_line', 'post_context'];
        while (i--) normalized[keys[i]] = context[i];
    }

    // normalized.in_app = !/(Raven|TraceKit)\./.test(normalized['function']);

    return normalized;
}

function extractContextFromFrame(frame) {
    // immediately check if we should even attempt to parse a context
    if (!frame.context || !globalOptions.fetchContext) return;

    var context = frame.context,
        pivot = ~~(context.length / 2),
        i = context.length, isMinified = false;

    while (i--) {
        // We're making a guess to see if the source is minified or not.
        // To do that, we make the assumption if *any* of the lines passed
        // in are greater than 300 characters long, we bail.
        // Sentry will see that there isn't a context
        if (context[i].length > 300) {
            isMinified = true;
            break;
        }
    }

    if (isMinified) {
        // The source is minified and we don't know which column. Fuck it.
        if (isUndefined(frame.column)) return;

        // If the source is minified and has a frame column
        // we take a chunk of the offending line to hopefully shed some light
        return [
            [],  // no pre_context
            context[pivot].substr(frame.column, 50), // grab 50 characters, starting at the offending column
            []   // no post_context
        ];
    }

    return [
        context.slice(0, pivot),    // pre_context
        context[pivot],             // context_line
        context.slice(pivot + 1)    // post_context
    ];
}

function processException(type, message, fileurl, lineno, frames, options) {
    var stacktrace, label, i;

    // "Script error." is hard coded into browsers for errors that it can't read.
    // this is the result of a script being pulled in from an external domain and CORS.
    if (message === 'Script error.') return;

    if (frames && frames.length) {
        stacktrace = {frames: frames};
        fileurl = fileurl || frames[0].filename;
    } else if (fileurl) {
        stacktrace = {
            frames: [{
                filename: fileurl,
                lineno: lineno
            }]
        };
    }

    i = globalOptions.ignoreUrls.length;
    while (i--) {
        if (globalOptions.ignoreUrls[i].test(fileurl)) {
            return;
        }
    }

    label = lineno ? message + ' at ' + lineno : message;

    // Fire away!
    send(
        arrayMerge({
            'sentry.interfaces.Exception': {
                type: type,
                value: message
            },
            'sentry.interfaces.Stacktrace': stacktrace,
            culprit: fileurl,
            message: label
        }, options)
    );
}

function arrayMerge(arr1, arr2) {
    if (!arr2) {
        return arr1;
    }
    each(arr2, function(key, value){
        arr1[key] = value;
    });
    return arr1;
}

function getHttpData() {
    var http = {
        url: document.location.href,
        headers: {
            'User-Agent': navigator.userAgent
        }
    };

    if (document.referrer) {
        http.headers.Referer = document.referrer;
    }

    return http;
}

function send(data) {
    if (!isSetup()) return;

    data = arrayMerge({
        project: globalProject,
        logger: globalOptions.logger,
        site: globalOptions.site,
        platform: 'javascript',
        'sentry.interfaces.Http': getHttpData()
    }, data);

    if (globalUser) data['sentry.interfaces.User'] = globalUser;

    if (isFunction(globalOptions.dataCallback)) {
        data = globalOptions.dataCallback(data);
    }

    makeRequest(data);
}

function makeRequest(data) {
    new Image().src = globalServer + getAuthQueryString() + '&sentry_data=' + encodeURIComponent(JSON.stringify(data));
}

function isSetup() {
    if (!hasJSON) return false;  // needs JSON support
    if (!globalServer) {
        if (window.console && console.error) {
            console.error("Error: Raven has not been configured.");
        }
        return false;
    }
    return true;
}

function wrapArguments(what) {
    if (!isFunction(what)) return what;

    function wrapped() {
        var args = [], i = arguments.length, arg;
        while(i--) {
            arg = arguments[i];
            args[i] = isFunction(arg) ? Raven.wrap(arg) : arg;
        }
        what.apply(null, args);
    }
    // copy over properties of the old function
    for (var k in what) wrapped[k] = what[k];
    return wrapped;
}
<commit_msg>Revert "Deprecate ignoreErrors, see #73"<commit_after>'use strict';

// First, check for JSON support
// If there is no JSON, we no-op the core features of Raven
// since JSON is required to encode the payload
var _Raven = window.Raven,
    hasJSON = !!(window.JSON && window.JSON.stringify),
    globalServer,
    globalUser,
    globalKey,
    globalProject,
    globalOptions = {
        logger: 'javascript',
        ignoreUrls: []
    };

var TK = TraceKit.noConflict();

// Disable Tracekit's remote fetching by default
TK.remoteFetching = false;

/*
 * The core Raven singleton
 *
 * @this {Raven}
 */
var Raven = {
    VERSION: '@VERSION',

    /*
     * Allow multiple versions of Raven to be installed.
     * Strip Raven from the global context and returns the instance.
     *
     * @return {Raven}
     */
    noConflict: function() {
        window.Raven = _Raven;
        return Raven;
    },

    /*
     * Configure Raven with a DSN and extra options
     *
     * @param {string} dsn The public Sentry DSN
     * @param {object} options Optional set of of global options [optional]
     * @return {Raven}
     */
    config: function(dsn, options) {
        var uri = parseUri(dsn),
            lastSlash = uri.path.lastIndexOf('/'),
            path = uri.path.substr(1, lastSlash);

        // merge in options
        if (options) {
            each(options, function(key, value){
                globalOptions[key] = value;
            });
        }

        globalKey = uri.user;
        globalProject = ~~uri.path.substr(lastSlash + 1);

        // assemble the endpoint from the uri pieces
        globalServer = '//' + uri.host +
                      (uri.port ? ':' + uri.port : '') +
                      '/' + path + 'api/' + globalProject + '/store/';

        if (uri.protocol) {
            globalServer = uri.protocol + ':' + globalServer;
        }

        if (globalOptions.fetchContext) {
            TK.remoteFetching = true;
        }

        // return for chaining
        return Raven;
    },

    /*
     * Installs a global window.onerror error handler
     * to capture and report uncaught exceptions.
     * At this point, install() is required to be called due
     * to the way TraceKit is set up.
     *
     * @return {Raven}
     */
    install: function() {
        if (!isSetup()) return;

        TK.report.subscribe(handleStackInfo);

        return Raven;
    },

    /*
     * Wrap code within a context so Raven can capture errors
     * reliably across domains that is executed immediately.
     *
     * @param {object} options A specific set of options for this context [optional]
     * @param {function} func The callback to be immediately executed within the context
     * @param {array} args An array of arguments to be called with the callback [optional]
     */
    context: function(options, func, args) {
        if (isFunction(options)) {
            args = func || [];
            func = options;
            options = undefined;
        }

        Raven.wrap(options, func).apply(this, args);
    },

    /*
     * Wrap code within a context and returns back a new function to be executed
     *
     * @param {object} options A specific set of options for this context [optional]
     * @param {function} func The function to be wrapped in a new context
     * @return {function} The newly wrapped functions with a context
     */
    wrap: function(options, func) {
        // options is optional
        if (isFunction(options)) {
            func = options;
            options = undefined;
        }

        return function() {
            try {
                func.apply(this, arguments);
            } catch(e) {
                Raven.captureException(e, options);
                throw e;
            }
        };
    },

    /*
     * Uninstalls the global error handler.
     *
     * @return {Raven}
     */
    uninstall: function() {
        TK.report.unsubscribe(handleStackInfo);

        return Raven;
    },

    /*
     * Manually capture an exception and send it over to Sentry
     *
     * @param {error} ex An exception to be logged
     * @param {object} options A specific set of options for this error [optional]
     * @return {Raven}
     */
    captureException: function(ex, options) {
        // If a string is passed through, recall as a message
        if (typeof ex === 'string') {
            return Raven.captureMessage(ex, options);
        }

        // TraceKit.report will re-raise any exception passed to it,
        // which means you have to wrap it in try/catch. Instead, we
        // can wrap it here and only re-raise if TraceKit.report
        // raises an exception different from the one we asked to
        // report on.
        try {
            TK.report(ex, options);
        } catch(ex1) {
            if(ex !== ex1) {
                throw ex1;
            }
        }

        return Raven;
    },

    /*
     * Manually send a message to Sentry
     *
     * @param {string} msg A plain message to be captured in Sentry
     * @param {object} options A specific set of options for this message [optional]
     * @return {Raven}
     */
    captureMessage: function(msg, options) {
        // Fire away!
        send(
            arrayMerge({
                message: msg
            }, options)
        );

        return Raven;
    },

    /*
     * Set/clear a user to be sent along with the payload.
     *
     * @param {object} user An object representing user data [optional]
     * @return {Raven}
     */
    setUser: function(user) {
       globalUser = user;

       return Raven;
    }
};

var uriKeys = 'source protocol authority userInfo user password host port relative path directory file query anchor'.split(' '),
    uriPattern = /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/;

/**** Private functions ****/
function parseUri(str) {
    var m = uriPattern.exec(str),
        uri = {},
        i = 14;

    while (i--) uri[uriKeys[i]] = m[i] || '';

    return uri;
}

function isUndefined(what) {
    return typeof what === 'undefined';
}

function isFunction(what) {
    return typeof what === 'function';
}

function each(obj, callback) {
    var i, j;

    if (isUndefined(obj.length)) {
        for (i in obj) {
            if (obj.hasOwnProperty(i)) {
                callback.call(null, i, obj[i]);
            }
        }
    } else {
        j = obj.length;
        if (j) {
            for (i = 0; i < j; i++) {
                callback.call(null, i, obj[i]);
            }
        }
    }
}

var cachedAuth;

function getAuthQueryString() {
    if (cachedAuth) return cachedAuth;

    var qs = [
        'sentry_version=2.0',
        'sentry_client=raven-js/' + Raven.VERSION
    ];
    if (globalKey) {
        qs.push('sentry_key=' + globalKey);
    }

    cachedAuth = '?' + qs.join('&');
    return cachedAuth;
}

function handleStackInfo(stackInfo, options) {
    var frames = [];

    if (stackInfo.stack && stackInfo.stack.length) {
        each(stackInfo.stack, function(i, stack) {
            var frame = normalizeFrame(stack);
            if (frame) {
                frames.push(frame);
            }
        });
    }

    processException(
        stackInfo.name,
        stackInfo.message,
        stackInfo.url,
        stackInfo.lineno,
        frames,
        options
    );
}

function normalizeFrame(frame) {
    if (!frame.url) return;

    // normalize the frames data
    var normalized = {
        filename:   frame.url,
        lineno:     frame.line,
        colno:      frame.column,
        'function': frame.func || '?'
    }, context = extractContextFromFrame(frame);

    if (context) {
        var i = 3, keys = ['pre_context', 'context_line', 'post_context'];
        while (i--) normalized[keys[i]] = context[i];
    }

    // normalized.in_app = !/(Raven|TraceKit)\./.test(normalized['function']);

    return normalized;
}

function extractContextFromFrame(frame) {
    // immediately check if we should even attempt to parse a context
    if (!frame.context || !globalOptions.fetchContext) return;

    var context = frame.context,
        pivot = ~~(context.length / 2),
        i = context.length, isMinified = false;

    while (i--) {
        // We're making a guess to see if the source is minified or not.
        // To do that, we make the assumption if *any* of the lines passed
        // in are greater than 300 characters long, we bail.
        // Sentry will see that there isn't a context
        if (context[i].length > 300) {
            isMinified = true;
            break;
        }
    }

    if (isMinified) {
        // The source is minified and we don't know which column. Fuck it.
        if (isUndefined(frame.column)) return;

        // If the source is minified and has a frame column
        // we take a chunk of the offending line to hopefully shed some light
        return [
            [],  // no pre_context
            context[pivot].substr(frame.column, 50), // grab 50 characters, starting at the offending column
            []   // no post_context
        ];
    }

    return [
        context.slice(0, pivot),    // pre_context
        context[pivot],             // context_line
        context.slice(pivot + 1)    // post_context
    ];
}

function processException(type, message, fileurl, lineno, frames, options) {
    var stacktrace, label, i;

    // "Script error." is hard coded into browsers for errors that it can't read.
    // this is the result of a script being pulled in from an external domain and CORS.
    if (message === 'Script error.') return;

    if (frames && frames.length) {
        stacktrace = {frames: frames};
        fileurl = fileurl || frames[0].filename;
    } else if (fileurl) {
        stacktrace = {
            frames: [{
                filename: fileurl,
                lineno: lineno
            }]
        };
    }

    i = globalOptions.ignoreUrls.length;
    while (i--) {
        if (globalOptions.ignoreUrls[i].test(fileurl)) {
            return;
        }
    }

    label = lineno ? message + ' at ' + lineno : message;

    // Fire away!
    send(
        arrayMerge({
            'sentry.interfaces.Exception': {
                type: type,
                value: message
            },
            'sentry.interfaces.Stacktrace': stacktrace,
            culprit: fileurl,
            message: label
        }, options)
    );
}

function arrayMerge(arr1, arr2) {
    if (!arr2) {
        return arr1;
    }
    each(arr2, function(key, value){
        arr1[key] = value;
    });
    return arr1;
}

function getHttpData() {
    var http = {
        url: document.location.href,
        headers: {
            'User-Agent': navigator.userAgent
        }
    };

    if (document.referrer) {
        http.headers.Referer = document.referrer;
    }

    return http;
}

function send(data) {
    if (!isSetup()) return;

    data = arrayMerge({
        project: globalProject,
        logger: globalOptions.logger,
        site: globalOptions.site,
        platform: 'javascript',
        'sentry.interfaces.Http': getHttpData()
    }, data);

    if (globalUser) data['sentry.interfaces.User'] = globalUser;

    if (isFunction(globalOptions.dataCallback)) {
        data = globalOptions.dataCallback(data);
    }

    makeRequest(data);
}

function makeRequest(data) {
    new Image().src = globalServer + getAuthQueryString() + '&sentry_data=' + encodeURIComponent(JSON.stringify(data));
}

function isSetup() {
    if (!hasJSON) return false;  // needs JSON support
    if (!globalServer) {
        if (window.console && console.error) {
            console.error("Error: Raven has not been configured.");
        }
        return false;
    }
    return true;
}

function wrapArguments(what) {
    if (!isFunction(what)) return what;

    function wrapped() {
        var args = [], i = arguments.length, arg;
        while(i--) {
            arg = arguments[i];
            args[i] = isFunction(arg) ? Raven.wrap(arg) : arg;
        }
        what.apply(null, args);
    }
    // copy over properties of the old function
    for (var k in what) wrapped[k] = what[k];
    return wrapped;
}
<|endoftext|>


<commit_before>/* jshint node:true */
var compiler = require('./compiler.js');

var Razor = (function() {
    'use strict';

    function _indent(count) {
        count *= 4;
        return new Array(++count).join(' ');
    }

    function _escape(string) {
        return string.replace(/%([\w\-]+)/g, 'this.escape(@$1)');
    }

    function _templateNameFromView(view) {
        return view.split('.')[0];
    }

    function _replaceArgs(string) {
        return string.replace(/\$([\w\-]+)/g, function(match, arg) {
            if (arg.indexOf('-') === -1) {
                return 'args.' + arg;
            }

            return 'args[\'' + arg + '\']';
        });
    }

    function _templateToJavascript(string) {

        string = string.replace(/\s{2,}/g, ' ').replace(/> </g, '><');

        // replace inline variables
        string = string.replace(new RegExp('{{\\s*(.*?);?\\s*}}', 'g'), function(group, code) {
            code = _replaceArgs(_escape(code));
            code = "' + " + code + " + '";
            return code.replace(/\'/g, '_QUOTE_');
        });

        var regex = new RegExp('{%\\s*(.*?):?\\s*%}', 'g'),
            bits = string.split(regex),
            length = bits.length,
            matches,
            bit,
            line,
            start,
            definedVars = {},
            activeVar = 't',
            line_ending,
            code = [],
            first_word,
            expression,
            extend,
            indent = 0,
            i;

        for (i = 0; i < length; i++) {
            line = bits[i].replace(/^\n+/, '').replace(/\n+$/, '');

            if (!line) {
                continue;
            }

            if (i % 2) {
                first_word = line.split(' ')[0];
                bit = line.replace(first_word, '');
                line_ending = ';';

                if (first_word === 'elseif') {
                    first_word = 'else if';
                }

                switch (first_word) {
                    case 'case':
                        line_ending = ':';
                        break;
                    case 'if':
                    case 'for':
                    case 'switch':
                        line_ending = ' {';
                        break;
                    case 'else if':
                    case 'else':
                        indent -= 1;
                        first_word = '} ' + first_word;
                        line_ending = ' {';
                        break;
                }

                // if the first line is an if statement or loop we need to make
                // sure that t is defined for later
                if (!start) {
                    start = 'var ' + activeVar + ' = \'\';\n\n';
                    definedVars[activeVar] = 1;
                    code.push(start);
                }

                if (first_word.indexOf('end') === 0) {
                    if (extend && --extend.level === 0) {
                        code.push(_indent(indent) + 't += this.render(\'' + extend.templateName + '\', {' + extend.variableName + ': ' + extend.variableName + '});\n');
                        extend = false;
                        continue;
                    }

                    indent -= 1;
                    code.push(_indent(Math.max(indent, 0)) + '}\n\n');
                    continue;
                }

                expression = line_ending === ';';

                if (expression && bit.charAt(bit.length - 1) === ';') {
                    line_ending = '';
                }

                // special case for extending views
                if (first_word === 'extend' || first_word.indexOf('extend(') === 0) {
                    matches = /extend\s*\((['"])(.*?)\1\s*,\s*\$(.*?)\)/.exec(line);
                    extend = {};
                    extend.level = 1;
                    extend.templateName = _templateNameFromView(matches[2]);
                    extend.variableName = matches[3];
                    activeVar = extend.variableName;
                    continue;
                }

                // special case for rendering sub views
                if (first_word === 'render' || first_word.indexOf('render(') === 0) {
                    matches = /render\s*\((['"])(.*?)\1(,(.*?)$)?/.exec(line);
                    var templateName = _templateNameFromView(matches[2]);
                    code.push(_indent(indent) + activeVar + ' += this.' + _replaceArgs(line.replace(matches[2], templateName)) + line_ending + '\n');
                    continue;
                }

                if (extend) {
                    extend.level++;
                }

                code.push(_indent(indent) + first_word + _replaceArgs(_escape(bit)) + line_ending + '\n');

                if (!expression) {
                    indent += 1;
                }

                if (first_word === 'break') {
                    indent -= 1;
                }

                continue;
            }

            start = activeVar + ' += ';
            if (!definedVars[activeVar]) {
                start = 'var ' + activeVar + ' = ';
                definedVars[activeVar] = 1;
            }

            code.push(_indent(indent) + start + '\'' + line.replace(/\'/g, "\\'").replace(/\n/g, '').replace(/_QUOTE_/g, "'") + '\'' + ';\n');
        }

        code.push('return t;');
        return code.join('');
    }

    return {
        generate: function(string) {
            return _templateToJavascript(string);
        },

        compile: function(string) {
            return new Function(string);
        },

        process: compiler.process
    };
}) ();

module.exports = Razor;
<commit_msg>Trim space and new lines<commit_after>/* jshint node:true */
var compiler = require('./compiler.js');

var Razor = (function() {
    'use strict';

    function _indent(count) {
        count *= 4;
        return new Array(++count).join(' ');
    }

    function _escape(string) {
        return string.replace(/%([\w\-]+)/g, 'this.escape(@$1)');
    }

    function _templateNameFromView(view) {
        return view.split('.')[0];
    }

    function _replaceArgs(string) {
        return string.replace(/\$([\w\-]+)/g, function(match, arg) {
            if (arg.indexOf('-') === -1) {
                return 'args.' + arg;
            }

            return 'args[\'' + arg + '\']';
        });
    }

    function _templateToJavascript(string) {

        string = string.replace(/\s{2,}/g, ' ').replace(/> </g, '><');

        // replace inline variables
        string = string.replace(new RegExp('{{\\s*(.*?);?\\s*}}', 'g'), function(group, code) {
            code = _replaceArgs(_escape(code));
            code = "' + " + code + " + '";
            return code.replace(/\'/g, '_QUOTE_');
        });

        var regex = new RegExp('{%\\s*(.*?):?\\s*%}', 'g'),
            bits = string.split(regex),
            length = bits.length,
            matches,
            bit,
            line,
            start,
            definedVars = {},
            activeVar = 't',
            line_ending,
            code = [],
            first_word,
            expression,
            extend,
            indent = 0,
            i;

        for (i = 0; i < length; i++) {
            line = bits[i].replace(/^\s+/, '').replace(/\s+$/, '');

            if (!line) {
                continue;
            }

            if (i % 2) {
                first_word = line.split(' ')[0];
                bit = line.replace(first_word, '');
                line_ending = ';';

                if (first_word === 'elseif') {
                    first_word = 'else if';
                }

                switch (first_word) {
                    case 'case':
                        line_ending = ':';
                        break;
                    case 'if':
                    case 'for':
                    case 'switch':
                        line_ending = ' {';
                        break;
                    case 'else if':
                    case 'else':
                        indent -= 1;
                        first_word = '} ' + first_word;
                        line_ending = ' {';
                        break;
                }

                // if the first line is an if statement or loop we need to make
                // sure that t is defined for later
                if (!start) {
                    start = 'var ' + activeVar + ' = \'\';\n\n';
                    definedVars[activeVar] = 1;
                    code.push(start);
                }

                if (first_word.indexOf('end') === 0) {
                    if (extend && --extend.level === 0) {
                        code.push(_indent(indent) + 't += this.render(\'' + extend.templateName + '\', {' + extend.variableName + ': ' + extend.variableName + '});\n');
                        extend = false;
                        continue;
                    }

                    indent -= 1;
                    code.push(_indent(Math.max(indent, 0)) + '}\n\n');
                    continue;
                }

                expression = line_ending === ';';

                if (expression && bit.charAt(bit.length - 1) === ';') {
                    line_ending = '';
                }

                // special case for extending views
                if (first_word === 'extend' || first_word.indexOf('extend(') === 0) {
                    matches = /extend\s*\((['"])(.*?)\1\s*,\s*\$(.*?)\)/.exec(line);
                    extend = {};
                    extend.level = 1;
                    extend.templateName = _templateNameFromView(matches[2]);
                    extend.variableName = matches[3];
                    activeVar = extend.variableName;
                    continue;
                }

                // special case for rendering sub views
                if (first_word === 'render' || first_word.indexOf('render(') === 0) {
                    matches = /render\s*\((['"])(.*?)\1(,(.*?)$)?/.exec(line);
                    var templateName = _templateNameFromView(matches[2]);
                    code.push(_indent(indent) + activeVar + ' += this.' + _replaceArgs(line.replace(matches[2], templateName)) + line_ending + '\n');
                    continue;
                }

                if (extend) {
                    extend.level++;
                }

                code.push(_indent(indent) + first_word + _replaceArgs(_escape(bit)) + line_ending + '\n');

                if (!expression) {
                    indent += 1;
                }

                if (first_word === 'break') {
                    indent -= 1;
                }

                continue;
            }

            start = activeVar + ' += ';
            if (!definedVars[activeVar]) {
                start = 'var ' + activeVar + ' = ';
                definedVars[activeVar] = 1;
            }

            code.push(_indent(indent) + start + '\'' + line.replace(/\'/g, "\\'").replace(/\n/g, '').replace(/_QUOTE_/g, "'") + '\'' + ';\n');
        }

        code.push('return t;');
        return code.join('');
    }

    return {
        generate: function(string) {
            return _templateToJavascript(string);
        },

        compile: function(string) {
            return new Function(string);
        },

        process: compiler.process
    };
}) ();

module.exports = Razor;
<|endoftext|>


<commit_before>function RegExConstant() {
  return {
    email:      /^[a-z0-9!#$%&'*+\/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+\/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,
    latLong:    /^[-+]?([1-8]?\d(\.\d+)?|90(\.0+)?),\s*[-+]?(180(\.0+)?|((1[0-7]\d)|([1-9]?\d))(\.\d+)?)$/,
    zip:        /^\d{5}(?:[-\s]\d{4})?$/,
    timeZone:   /^GMT\s[+-]\d{2}:\d{2}$/,
    timeStr:    /^([01]?[0-9]|2[0-3]):[0-5][0-9]$/,
    number:     /^[+\-]?(?:0|[1-9]\d*)(?:\.\d*)?(?:[eE][+\-]?\d+)?$/,
    object:     /^{.*}$/,
    array:      /^\[.*]$/,
    boolean:    /^true|false$/
  };
}

angular.module( 'angular-m' )
  .constant( 'REGEX', RegExConstant );
<commit_msg>Fixing email regex<commit_after>function RegExConstant() {
  return {
    email:      /^[a-z0-9!#$%&'*+\/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+\/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])+$/i,
    latLong:    /^[-+]?([1-8]?\d(\.\d+)?|90(\.0+)?),\s*[-+]?(180(\.0+)?|((1[0-7]\d)|([1-9]?\d))(\.\d+)?)$/,
    zip:        /^\d{5}(?:[-\s]\d{4})?$/,
    timeZone:   /^GMT\s[+-]\d{2}:\d{2}$/,
    timeStr:    /^([01]?[0-9]|2[0-3]):[0-5][0-9]$/,
    number:     /^[+\-]?(?:0|[1-9]\d*)(?:\.\d*)?(?:[eE][+\-]?\d+)?$/,
    object:     /^{.*}$/,
    array:      /^\[.*]$/,
    boolean:    /^true|false$/
  };
}

angular.module( 'angular-m' )
  .constant( 'REGEX', RegExConstant );
<|endoftext|>


<commit_before>import {
  fromGlobalId,
  connectionFromArray,
  nodeDefinitions,
  connectionDefinitions,
  connectionArgs
} from 'graphql-relay';

import {
  GraphQLList
} from 'graphql';

import {
  base64,
  unbase64,
} from './base64.js';

import _ from 'lodash';
import simplifyAST from './simplifyAST';

export class NodeTypeMapper {
  constructor() {
    this.map = { };
  }

  mapTypes(types) {
    Object.keys(types).forEach((k) => {
      let v = types[k];
      this.map[k] = v.type
        ? v
        : { type: v };
    });
  }

  item(type) {
    return this.map[type];
  }
}

export function idFetcher(sequelize, nodeTypeMapper) {
  return async (globalId, context) => {
    const {type, id} = fromGlobalId(globalId);

    const nodeType = nodeTypeMapper.item(type);
    if (nodeType && typeof nodeType.resolve === 'function') {
      const res = await Promise.resolve(nodeType.resolve(globalId, context));
      if (res) res.__graphqlType__ = type;
      return res;
    }

    const model = Object.keys(sequelize.models).find(model => model === type);
    return model
      ? sequelize.models[model].findById(id)
      : nodeType
        ? nodeType.type
        : null;
  };
}

export function typeResolver(nodeTypeMapper) {
  return obj => {
    var type = obj.__graphqlType__
               || (obj.Model
                 ? obj.Model.options.name.singular
                 : obj._modelOptions
                 ? obj._modelOptions.name.singular
                 : obj.name);

    if (!type) {
      throw new Error(`Unable to determine type of ${ typeof obj }. ` +
        `Either specify a resolve function in 'NodeTypeMapper' object, or specify '__graphqlType__' property on object.`);
    }

    const nodeType = nodeTypeMapper.item(type);
    return nodeType && nodeType.type || null;
  };
}

export function isConnection(type) {
  return typeof type.name !== 'undefined' && type.name.endsWith('Connection');
}

export function handleConnection(values, args) {
  return connectionFromArray(values, args);
}

export function sequelizeNodeInterface(sequelize) {
  let nodeTypeMapper = new NodeTypeMapper();
  const nodeObjects = nodeDefinitions(
    idFetcher(sequelize, nodeTypeMapper),
    typeResolver(nodeTypeMapper)
  );

  return {
    nodeTypeMapper,
    ...nodeObjects
  };
}

export function nodeType(connectionType) {
  return connectionType._fields.edges.type.ofType._fields.node.type;
}

export function sequelizeConnection({
  name,
  nodeType,
  target: targetMaybeThunk,
  orderBy: orderByEnum,
  before,
  after,
  connectionFields,
  edgeFields,
  where
}) {
  const {
    edgeType,
    connectionType
  } = connectionDefinitions({
    name,
    nodeType,
    connectionFields,
    edgeFields
  });

  const SEPERATOR = '$';
  const PREFIX = 'arrayconnection' + SEPERATOR;

  before = before || ((options) => options);
  after = after || ((result) => result);

  let $connectionArgs = {
    ...connectionArgs
  };

  if (orderByEnum) {
    $connectionArgs.orderBy = {
      type: new GraphQLList(orderByEnum)
    };
  }

  let orderByAttribute = function (orderAttr, {source, args, context, info}) {
    return typeof orderAttr === 'function' ? orderAttr(source, args, context, info) : orderAttr;
  };

  let orderByDirection = function (orderDirection, args) {
    if (args.last) {
      return orderDirection.indexOf('ASC') >= 0
              ? orderDirection.replace('ASC', 'DESC')
              : orderDirection.replace('DESC', 'ASC');
    }
    return orderDirection;
  };

  /**
   * Creates a cursor given a item returned from the Database
   * @param  {Object}   item   sequelize model instance
   * @param  {Integer}  index  the index of this item within the results, 0 indexed
   * @return {String}          The Base64 encoded cursor string
   */
  let toCursor = function (item, index) {
    let id = item.get(item.constructor ? item.constructor.primaryKeyAttribute : item.Model.primaryKeyAttribute);
    return base64(PREFIX + id + SEPERATOR + index);
  };

  /**
   * Decode a cursor into its component parts
   * @param  {String} cursor Base64 encoded cursor
   * @return {Object}        Object containing ID and index
   */
  let fromCursor = function (cursor) {
    cursor = unbase64(cursor);
    cursor = cursor.substring(PREFIX.length, cursor.length);
    let [id, index] = cursor.split(SEPERATOR);

    return {
      id,
      index
    };
  };

  let argsToWhere = function (args) {
    let result = {};

    if (where === undefined) return result;

    _.each(args, (value, key) => {
      if (key in $connectionArgs) return;
      _.assign(result, where(key, value, result));
    });

    return result;
  };

  let resolveEdge = function (item, index, queriedCursor, args = {}, source) {
    let startIndex = null;
    if (queriedCursor) startIndex = Number(queriedCursor.index);
    if (startIndex !== null) {
      startIndex++;
    } else {
      startIndex = 0;
    }

    return {
      cursor: toCursor(item, index + startIndex),
      node: item,
      source: source
    };
  };

  let $resolver = require('./resolver')(targetMaybeThunk, {
    handleConnection: false,
    list: true,
    before: function (options, args, context, info) {
      const target = info.target;
      const model = target.target ? target.target : target;

      if (args.first || args.last) {
        options.limit = parseInt(args.first || args.last, 10);
      }
      if (!args.orderBy) {
        args.orderBy = [
          [model.primaryKeyAttribute, 'ASC']
        ];
      } else if (orderByEnum && typeof args.orderBy === 'string') {
        args.orderBy = [orderByEnum._nameLookup[args.orderBy].value];
      }

      let orderBy = args.orderBy;
      let orderAttribute = orderByAttribute(orderBy[0][0], {
        source: info.source,
        args,
        context,
        info
      });
      let orderDirection = orderByDirection(orderBy[0][1], args);

      options.order = [
        [orderAttribute, orderDirection]
      ];

      if (orderAttribute !== model.primaryKeyAttribute) {
        options.order.push([model.primaryKeyAttribute, orderByDirection('ASC', args)]);
      }

      if (typeof orderAttribute === 'string') {
        options.attributes.push(orderAttribute);
      }

      if (options.limit && !options.attributes.some(attribute => attribute.length === 2 && attribute[1] === 'full_count')) {
        if (model.sequelize.dialect.name === 'postgres') {
          options.attributes.push([
            model.sequelize.literal('COUNT(*) OVER()'),
            'full_count'
          ]);
        } else if (model.sequelize.dialect.name === 'mssql') {
          options.attributes.push([
            model.sequelize.literal('COUNT(1) OVER()'),
            'full_count'
          ]);
        }
      }

      options.where = argsToWhere(args);

      if (args.after || args.before) {
        let cursor = fromCursor(args.after || args.before);
        let startIndex = Number(cursor.index);

        if (startIndex >= 0) options.offset = startIndex + 1;
      }
      options.attributes = _.uniq(options.attributes);
      return before(options, args, context, info);
    },
    after: async function (values, args, context, info) {
      const {
        source,
        target
      } = info;

      var cursor = null;

      if (args.after || args.before) {
        cursor = fromCursor(args.after || args.before);
      }

      let edges = values.map((value, idx) => {
        return resolveEdge(value, idx, cursor, args, source);
      });

      let firstEdge = edges[0];
      let lastEdge = edges[edges.length - 1];
      let fullCount = values[0] && values[0].dataValues.full_count && parseInt(values[0].dataValues.full_count, 10);

      if (!values[0]) {
        fullCount = 0;
      }

      if ((args.first || args.last) && (fullCount === null || fullCount === undefined)) {
        // In case of `OVER()` is not available, we need to get the full count from a second query.
        const options = await Promise.resolve(before({
          where: argsToWhere(args)
        }, args, context, info));

        if (target.count) {
          if (target.associationType) {
            fullCount = await target.count(source, options);
          } else {
            fullCount = await target.count(options);
          }
        } else {
          fullCount = await target.manyFromSource.count(source, options);
        }
      }

      let hasNextPage = false;
      let hasPreviousPage = false;
      if (args.first || args.last) {
        const count = parseInt(args.first || args.last, 10);
        let index = cursor ? Number(cursor.index) : null;
        if (index !== null) {
          index++;
        } else {
          index = 0;
        }

        hasNextPage = index + 1 + count <= fullCount;
        hasPreviousPage = index - count >= 0;

        if (args.last) {
          [hasNextPage, hasPreviousPage] = [hasPreviousPage, hasNextPage];
        }
      }

      return after({
        source,
        args,
        where: argsToWhere(args),
        edges,
        pageInfo: {
          startCursor: firstEdge ? firstEdge.cursor : null,
          endCursor: lastEdge ? lastEdge.cursor : null,
          hasNextPage: hasNextPage,
          hasPreviousPage: hasPreviousPage
        },
        fullCount
      }, args, context, info);
    }
  });

  let resolver = (source, args, context, info) => {
    var fieldNodes = info.fieldASTs || info.fieldNodes;
    if (simplifyAST(fieldNodes[0], info).fields.edges) {
      return $resolver(source, args, context, info);
    }

    return {
      source,
      args,
      where: argsToWhere(args)
    };
  };

  return {
    connectionType,
    edgeType,
    nodeType,
    resolveEdge,
    connectionArgs: $connectionArgs,
    resolve: resolver
  };
}
<commit_msg>dont mutate args object<commit_after>import {
  fromGlobalId,
  connectionFromArray,
  nodeDefinitions,
  connectionDefinitions,
  connectionArgs
} from 'graphql-relay';

import {
  GraphQLList
} from 'graphql';

import {
  base64,
  unbase64,
} from './base64.js';

import _ from 'lodash';
import simplifyAST from './simplifyAST';

export class NodeTypeMapper {
  constructor() {
    this.map = { };
  }

  mapTypes(types) {
    Object.keys(types).forEach((k) => {
      let v = types[k];
      this.map[k] = v.type
        ? v
        : { type: v };
    });
  }

  item(type) {
    return this.map[type];
  }
}

export function idFetcher(sequelize, nodeTypeMapper) {
  return async (globalId, context) => {
    const {type, id} = fromGlobalId(globalId);

    const nodeType = nodeTypeMapper.item(type);
    if (nodeType && typeof nodeType.resolve === 'function') {
      const res = await Promise.resolve(nodeType.resolve(globalId, context));
      if (res) res.__graphqlType__ = type;
      return res;
    }

    const model = Object.keys(sequelize.models).find(model => model === type);
    return model
      ? sequelize.models[model].findById(id)
      : nodeType
        ? nodeType.type
        : null;
  };
}

export function typeResolver(nodeTypeMapper) {
  return obj => {
    var type = obj.__graphqlType__
               || (obj.Model
                 ? obj.Model.options.name.singular
                 : obj._modelOptions
                 ? obj._modelOptions.name.singular
                 : obj.name);

    if (!type) {
      throw new Error(`Unable to determine type of ${ typeof obj }. ` +
        `Either specify a resolve function in 'NodeTypeMapper' object, or specify '__graphqlType__' property on object.`);
    }

    const nodeType = nodeTypeMapper.item(type);
    return nodeType && nodeType.type || null;
  };
}

export function isConnection(type) {
  return typeof type.name !== 'undefined' && type.name.endsWith('Connection');
}

export function handleConnection(values, args) {
  return connectionFromArray(values, args);
}

export function sequelizeNodeInterface(sequelize) {
  let nodeTypeMapper = new NodeTypeMapper();
  const nodeObjects = nodeDefinitions(
    idFetcher(sequelize, nodeTypeMapper),
    typeResolver(nodeTypeMapper)
  );

  return {
    nodeTypeMapper,
    ...nodeObjects
  };
}

export function nodeType(connectionType) {
  return connectionType._fields.edges.type.ofType._fields.node.type;
}

export function sequelizeConnection({
  name,
  nodeType,
  target: targetMaybeThunk,
  orderBy: orderByEnum,
  before,
  after,
  connectionFields,
  edgeFields,
  where
}) {
  const {
    edgeType,
    connectionType
  } = connectionDefinitions({
    name,
    nodeType,
    connectionFields,
    edgeFields
  });

  const SEPERATOR = '$';
  const PREFIX = 'arrayconnection' + SEPERATOR;

  before = before || ((options) => options);
  after = after || ((result) => result);

  let $connectionArgs = {
    ...connectionArgs
  };

  if (orderByEnum) {
    $connectionArgs.orderBy = {
      type: new GraphQLList(orderByEnum)
    };
  }

  let orderByAttribute = function (orderAttr, {source, args, context, info}) {
    return typeof orderAttr === 'function' ? orderAttr(source, args, context, info) : orderAttr;
  };

  let orderByDirection = function (orderDirection, args) {
    if (args.last) {
      return orderDirection.indexOf('ASC') >= 0
              ? orderDirection.replace('ASC', 'DESC')
              : orderDirection.replace('DESC', 'ASC');
    }
    return orderDirection;
  };

  /**
   * Creates a cursor given a item returned from the Database
   * @param  {Object}   item   sequelize model instance
   * @param  {Integer}  index  the index of this item within the results, 0 indexed
   * @return {String}          The Base64 encoded cursor string
   */
  let toCursor = function (item, index) {
    let id = item.get(item.constructor ? item.constructor.primaryKeyAttribute : item.Model.primaryKeyAttribute);
    return base64(PREFIX + id + SEPERATOR + index);
  };

  /**
   * Decode a cursor into its component parts
   * @param  {String} cursor Base64 encoded cursor
   * @return {Object}        Object containing ID and index
   */
  let fromCursor = function (cursor) {
    cursor = unbase64(cursor);
    cursor = cursor.substring(PREFIX.length, cursor.length);
    let [id, index] = cursor.split(SEPERATOR);

    return {
      id,
      index
    };
  };

  let argsToWhere = function (args) {
    let result = {};

    if (where === undefined) return result;

    _.each(args, (value, key) => {
      if (key in $connectionArgs) return;
      _.assign(result, where(key, value, result));
    });

    return result;
  };

  let resolveEdge = function (item, index, queriedCursor, args = {}, source) {
    let startIndex = null;
    if (queriedCursor) startIndex = Number(queriedCursor.index);
    if (startIndex !== null) {
      startIndex++;
    } else {
      startIndex = 0;
    }

    return {
      cursor: toCursor(item, index + startIndex),
      node: item,
      source: source
    };
  };

  let $resolver = require('./resolver')(targetMaybeThunk, {
    handleConnection: false,
    list: true,
    before: function (options, args, context, info) {
      const target = info.target;
      const model = target.target ? target.target : target;

      if (args.first || args.last) {
        options.limit = parseInt(args.first || args.last, 10);
      }

      let orderBy = args.orderBy || [[model.primaryKeyAttribute, 'ASC']];
      if (orderByEnum && typeof orderBy === 'string') {
        orderBy = [orderByEnum._nameLookup[args.orderBy].value];
      }

      let orderAttribute = orderByAttribute(orderBy[0][0], {
        source: info.source,
        args,
        context,
        info
      });
      let orderDirection = orderByDirection(orderBy[0][1], args);

      options.order = [
        [orderAttribute, orderDirection]
      ];

      if (orderAttribute !== model.primaryKeyAttribute) {
        options.order.push([model.primaryKeyAttribute, orderByDirection('ASC', args)]);
      }

      if (typeof orderAttribute === 'string') {
        options.attributes.push(orderAttribute);
      }

      if (options.limit && !options.attributes.some(attribute => attribute.length === 2 && attribute[1] === 'full_count')) {
        if (model.sequelize.dialect.name === 'postgres') {
          options.attributes.push([
            model.sequelize.literal('COUNT(*) OVER()'),
            'full_count'
          ]);
        } else if (model.sequelize.dialect.name === 'mssql') {
          options.attributes.push([
            model.sequelize.literal('COUNT(1) OVER()'),
            'full_count'
          ]);
        }
      }

      options.where = argsToWhere(args);

      if (args.after || args.before) {
        let cursor = fromCursor(args.after || args.before);
        let startIndex = Number(cursor.index);

        if (startIndex >= 0) options.offset = startIndex + 1;
      }
      options.attributes = _.uniq(options.attributes);
      return before(options, args, context, info);
    },
    after: async function (values, args, context, info) {
      const {
        source,
        target
      } = info;

      var cursor = null;

      if (args.after || args.before) {
        cursor = fromCursor(args.after || args.before);
      }

      let edges = values.map((value, idx) => {
        return resolveEdge(value, idx, cursor, args, source);
      });

      let firstEdge = edges[0];
      let lastEdge = edges[edges.length - 1];
      let fullCount = values[0] && values[0].dataValues.full_count && parseInt(values[0].dataValues.full_count, 10);

      if (!values[0]) {
        fullCount = 0;
      }

      if ((args.first || args.last) && (fullCount === null || fullCount === undefined)) {
        // In case of `OVER()` is not available, we need to get the full count from a second query.
        const options = await Promise.resolve(before({
          where: argsToWhere(args)
        }, args, context, info));

        if (target.count) {
          if (target.associationType) {
            fullCount = await target.count(source, options);
          } else {
            fullCount = await target.count(options);
          }
        } else {
          fullCount = await target.manyFromSource.count(source, options);
        }
      }

      let hasNextPage = false;
      let hasPreviousPage = false;
      if (args.first || args.last) {
        const count = parseInt(args.first || args.last, 10);
        let index = cursor ? Number(cursor.index) : null;
        if (index !== null) {
          index++;
        } else {
          index = 0;
        }

        hasNextPage = index + 1 + count <= fullCount;
        hasPreviousPage = index - count >= 0;

        if (args.last) {
          [hasNextPage, hasPreviousPage] = [hasPreviousPage, hasNextPage];
        }
      }

      return after({
        source,
        args,
        where: argsToWhere(args),
        edges,
        pageInfo: {
          startCursor: firstEdge ? firstEdge.cursor : null,
          endCursor: lastEdge ? lastEdge.cursor : null,
          hasNextPage: hasNextPage,
          hasPreviousPage: hasPreviousPage
        },
        fullCount
      }, args, context, info);
    }
  });

  let resolver = (source, args, context, info) => {
    var fieldNodes = info.fieldASTs || info.fieldNodes;
    if (simplifyAST(fieldNodes[0], info).fields.edges) {
      return $resolver(source, args, context, info);
    }

    return {
      source,
      args,
      where: argsToWhere(args)
    };
  };

  return {
    connectionType,
    edgeType,
    nodeType,
    resolveEdge,
    connectionArgs: $connectionArgs,
    resolve: resolver
  };
}
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2015 TechnologyAdvice
 */
import types from './types'
import modifiers from './modifiers'
import generators from './generators'
import Promise from 'bluebird'
import validators from './lib/validators'
import ValidationError from './lib/error'

/**
 * Defines all definition property checks available
 */
const allProps = {
  generator: { name: 'generator', fn: generators.validator },
  default: { name: 'default', fn: validators.default },
  modifier: { name: 'modifier', fn: modifiers.validator },
  allow: { name: 'allow', fn: validators.allow },
  min: { name: 'min', fn: validators.min },
  max: { name: 'max', fn: validators.max },
  type: { name: 'type', fn: types.validator }
}

const rules = {
  /**
   * Acts as validation setup for, and respective order of operations
   * of, properties for a def-prop configuration
   */
  props: {
    // Default props
    default: [
      allProps.generator,
      allProps.default,
      allProps.modifier,
      allProps.allow,
      allProps.min,
      allProps.max,
      allProps.type
    ],
    // When no value/undefined
    noVal: [
      allProps.generator,
      allProps.default
    ]
  },

  /**
   * Binds rule definition in validate method
   * @param {Object} def The rule definition object
   */
  makeValidate: def => rules.validate.bind(null, def),

  /**
   * Processes definition validation
   * @param {Object} def The rule definition object
   * @param {*} data The data to validate
   * @param {String} (key) Key for tracking parent in nested iterations
   */
  validate: (def, data, key = null) => {
    const context = { errors: [] }
    const props = !def.required && data === undefined ? rules.props.noVal : rules.props.default
    if (!def.type) throw new Error('Model properties must define a \'type\'')
    let chain = Promise.resolve(data)
    props.forEach(prop => {
      if (def[prop.name]) {
        chain = chain.then(prop.fn.bind(context, def, key)).then(res => {
          return res === undefined ? data : res
        })
      }
    })
    return chain.then(res => {
      if (context.errors.length > 0) throw new ValidationError(context.errors)
      return res
    })
  },

  /**
   * Adds new rule
   * @param {Object} def The rule definition
   * @returns {Object}
   */
  build: def => {
    return {
      def,
      validate: rules.makeValidate(def)
    }
  }
}

export default rules
<commit_msg>Add modifier to list of noVal checks<commit_after>/*
 * Copyright (c) 2015 TechnologyAdvice
 */
import types from './types'
import modifiers from './modifiers'
import generators from './generators'
import Promise from 'bluebird'
import validators from './lib/validators'
import ValidationError from './lib/error'

/**
 * Defines all definition property checks available
 */
const allProps = {
  generator: { name: 'generator', fn: generators.validator },
  default: { name: 'default', fn: validators.default },
  modifier: { name: 'modifier', fn: modifiers.validator },
  allow: { name: 'allow', fn: validators.allow },
  min: { name: 'min', fn: validators.min },
  max: { name: 'max', fn: validators.max },
  type: { name: 'type', fn: types.validator }
}

const rules = {
  /**
   * Acts as validation setup for, and respective order of operations
   * of, properties for a def-prop configuration
   */
  props: {
    // Default props
    default: [
      allProps.generator,
      allProps.default,
      allProps.modifier,
      allProps.allow,
      allProps.min,
      allProps.max,
      allProps.type
    ],
    // When no value/undefined
    noVal: [
      allProps.generator,
      allProps.default,
      allProps.modifier
    ]
  },

  /**
   * Binds rule definition in validate method
   * @param {Object} def The rule definition object
   */
  makeValidate: def => rules.validate.bind(null, def),

  /**
   * Processes definition validation
   * @param {Object} def The rule definition object
   * @param {*} data The data to validate
   * @param {String} (key) Key for tracking parent in nested iterations
   */
  validate: (def, data, key = null) => {
    const context = { errors: [] }
    const props = !def.required && data === undefined ? rules.props.noVal : rules.props.default
    if (!def.type) throw new Error('Model properties must define a \'type\'')
    let chain = Promise.resolve(data)
    props.forEach(prop => {
      if (def[prop.name]) {
        chain = chain.then(prop.fn.bind(context, def, key)).then(res => {
          return res === undefined ? data : res
        })
      }
    })
    return chain.then(res => {
      if (context.errors.length > 0) throw new ValidationError(context.errors)
      return res
    })
  },

  /**
   * Adds new rule
   * @param {Object} def The rule definition
   * @returns {Object}
   */
  build: def => {
    return {
      def,
      validate: rules.makeValidate(def)
    }
  }
}

export default rules
<|endoftext|>


<commit_before>var ioc = require('./ioc');

// Register Base Classes
require('./model/base');
require('./provider/base');
require('./service/base');
require('./view/base');
require('./view/control');
require('./view/page');
require('./view-model/base');
require('./view-model/item');

ioc.registerProvider("network", require('./provider/network'));
ioc.registerProvider("lokiStorage", require('./provider/loki-storage'));
ioc.registerProvider("localStorage", require('./provider/local-storage'));

ioc.registerService("navigation", require('./service/navigation'));
ioc.registerService("message", require('./service/message'));
ioc.registerService("application", require('./service/application'));
ioc.registerService("data", require('./service/data'));
<commit_msg>Travis CI auto-merge from travis build 182  - [ci skip]<commit_after>var ioc = require('./ioc');

// Register Base Classes
require('./model/base');
require('./provider/base');
require('./service/base');
require('./view/base');
require('./view/control');
require('./view/page');
require('./view-model/base');
require('./view-model/item');

ioc.registerProvider("network", require('./provider/network'));
ioc.registerProvider("lokiStorage", require('./provider/loki-storage'));
ioc.registerProvider("localStorage", require('./provider/local-storage'));

ioc.registerService("navigation", require('./service/navigation'));
ioc.registerService("message", require('./service/message'));
ioc.registerService("application", require('./service/application'));
ioc.registerService("data", require('./service/data'));

// Export globals
window.Binding = window.Binding || {};
window.Binding.Mode = window.Binding.Mode || {};
window.Binding.Mode.Command = require('./binding/mode').command;
<|endoftext|>


<commit_before>// Load in dependencies
var async = require('async');
var concat = require('concat-stream');
var Layout = require('layout');
var semver = require('semver');

// Specify defaults
var engineDefault = 'pixelsmith';
var algorithmDefault = 'binary-tree';
var SPEC_VERSION_RANGE = '>=2.0.0 <3.0.0';

// Define our spritesmith utility
// Gist of params: {src: files, engine: 'pixelsmith', algorithm: 'binary-tree'}
// Gist of result: {image: binary, coordinates: {filepath: {x, y, width, height}}, properties: {width, height}}
function spritesmith(params, callback) {
  // Set up return items and fallback parameters
  var retObj = {};
  var files = params.src;
  var engineName = params.engine || engineDefault;
  var Engine = engineName;
  var algorithmName = params.algorithm || algorithmDefault;

  // If the engine is a `require` path, attempt to load it
  if (typeof engineName === 'string') {
    // Attempt to resolve the engine to verify it is installed at all
    try {
      require.resolve(engineName);
    } catch (err) {
      console.error('Attempted to find spritesmith engine "' + engineName + '" but could not.');
      console.error('Please verify you have installed "' + engineName + '" and saved it to your `package.json`');
      console.error('');
      console.error('    npm install ' + engineName + ' --save-dev');
      console.error('');
      throw err;
    }

    // Attempt to load the engine
    try {
      Engine = require(engineName);
    } catch (err) {
      console.error('Attempted to load spritesmith engine "' + engineName + '" but could not.');
      console.error('Please verify you have installed its dependencies. Documentation should be available at ');
      console.error('');
      // TODO: Consider using pkg.homepage and pkg.repository
      console.error('    https://npm.im/' + encodeURIComponent(engineName));
      console.error('');
      throw err;
    }
  }

  // Verify we are on a matching `specVersion`
  if (!semver.satisfies(Engine.specVersion, SPEC_VERSION_RANGE)) {
    throw new Error('Expected `engine` to have `specVersion` within "' + SPEC_VERSION_RANGE + '" ' +
      'but it was "' + Engine.specVersion + '". Please verify you are on the latest version of your engine: ' +
      '`npm install my-engine@latest`');
  }

  // Create our smiths
  var engine = new Engine(params.engineOpts || {});
  var layer = new Layout(algorithmName, params.algorithmOpts);
  var padding = params.padding || 0;
  var exportOpts = params.exportOpts || {};
  var packedObj;

  // In a waterfall fashion
  async.waterfall([
    function grabImages (cb) {
      // Map the files into their image counterparts
      engine.createImages(files, cb);
    },
    function saveImagePaths (images, cb) {
      // Iterate over the images and save their paths
      images.forEach(function saveImagePath (img, i) {
        img._filepath = files[i];
      });

      // Callback with the images
      cb(null, images);
    },
    // Then, add the images to our canvas (dry run)
    function smithAddFiles (images, cb) {
      images.forEach(function (img) {
        // Save the non-padded properties as meta data
        var width = img.width;
        var height = img.height;
        var meta = {img: img, actualWidth: width, actualHeight: height};

        // Add the item with padding to our layer
        layer.addItem({
          width: width + padding,
          height: height + padding,
          meta: meta
        });
      });

      // Callback with nothing
      cb(null);
    },
    // Then, output the coordinates
    function smithOutputCoordinates (cb) {
      // Export and saved packedObj for later
      packedObj = layer['export']();

      // Extract the coordinates
      var coordinates = {};
      var packedItems = packedObj.items;
      packedItems.forEach(function (item) {
        var meta = item.meta;
        var img = meta.img;
        var name = img._filepath;
        coordinates[name] = {
          x: item.x,
          y: item.y,
          width: meta.actualWidth,
          height: meta.actualHeight
        };
      });

      // Save the coordinates
      retObj.coordinates = coordinates;

      // Continue
      cb(null);
    },
    // Then, generate a canvas
    function generateCanvas (cb) {
      // Grab and fallback the width/height
      var width = Math.max(packedObj.width || 0, 0);
      var height = Math.max(packedObj.height || 0, 0);

      // If there are items
      var itemsExist = packedObj.items.length;
      if (itemsExist) {
        // Remove the last item's padding
        width -= padding;
        height -= padding;
      }

      // Export the total width and height of the generated canvas
      retObj.properties = {
        width: width,
        height: height
      };

      // If there are items, generate the canvas
      if (itemsExist) {
        var canvas = engine.createCanvas(width, height);
        process.nextTick(function handleNextTick () {
          cb(null, canvas);
        });
      // Otherwise, skip over potential errors/CPU
      } else {
        cb(null, '');
      }
    },
    // Then, export the canvas
    function exportCanvas (canvas, cb) {
      // If there is no canvas, callback with an empty string
      var items = packedObj.items;
      if (!canvas) {
        return cb(null, new Buffer(0));
      }

      // Add the images onto canvas
      try {
        items.forEach(function addImage (item) {
          var img = item.meta.img;
          canvas.addImage(img, item.x, item.y);
        });
      } catch (err) {
        return cb(err);
      }

      // Export our canvas
      var imageStream = canvas['export'](exportOpts);
      imageStream.on('error', cb);
      imageStream.pipe(concat(function handleResult (image) {
        cb(null, image);
      }));
    },
    function saveImage (image, cb) {
      // Save the image to the retObj
      retObj.image = image;

      // Callback
      cb(null);
    },
    function smithCallbackData (cb) {
      // Callback with the return object
      cb(null, retObj);
    }
  ], callback);
}

// Export spritesmith
module.exports = spritesmith;
<commit_msg>Replaced annoyance of '' with null<commit_after>// Load in dependencies
var async = require('async');
var concat = require('concat-stream');
var Layout = require('layout');
var semver = require('semver');

// Specify defaults
var engineDefault = 'pixelsmith';
var algorithmDefault = 'binary-tree';
var SPEC_VERSION_RANGE = '>=2.0.0 <3.0.0';

// Define our spritesmith utility
// Gist of params: {src: files, engine: 'pixelsmith', algorithm: 'binary-tree'}
// Gist of result: {image: binary, coordinates: {filepath: {x, y, width, height}}, properties: {width, height}}
function spritesmith(params, callback) {
  // Set up return items and fallback parameters
  var retObj = {};
  var files = params.src;
  var engineName = params.engine || engineDefault;
  var Engine = engineName;
  var algorithmName = params.algorithm || algorithmDefault;

  // If the engine is a `require` path, attempt to load it
  if (typeof engineName === 'string') {
    // Attempt to resolve the engine to verify it is installed at all
    try {
      require.resolve(engineName);
    } catch (err) {
      console.error('Attempted to find spritesmith engine "' + engineName + '" but could not.');
      console.error('Please verify you have installed "' + engineName + '" and saved it to your `package.json`');
      console.error('');
      console.error('    npm install ' + engineName + ' --save-dev');
      console.error('');
      throw err;
    }

    // Attempt to load the engine
    try {
      Engine = require(engineName);
    } catch (err) {
      console.error('Attempted to load spritesmith engine "' + engineName + '" but could not.');
      console.error('Please verify you have installed its dependencies. Documentation should be available at ');
      console.error('');
      // TODO: Consider using pkg.homepage and pkg.repository
      console.error('    https://npm.im/' + encodeURIComponent(engineName));
      console.error('');
      throw err;
    }
  }

  // Verify we are on a matching `specVersion`
  if (!semver.satisfies(Engine.specVersion, SPEC_VERSION_RANGE)) {
    throw new Error('Expected `engine` to have `specVersion` within "' + SPEC_VERSION_RANGE + '" ' +
      'but it was "' + Engine.specVersion + '". Please verify you are on the latest version of your engine: ' +
      '`npm install my-engine@latest`');
  }

  // Create our smiths
  var engine = new Engine(params.engineOpts || {});
  var layer = new Layout(algorithmName, params.algorithmOpts);
  var padding = params.padding || 0;
  var exportOpts = params.exportOpts || {};
  var packedObj;

  // In a waterfall fashion
  async.waterfall([
    function grabImages (cb) {
      // Map the files into their image counterparts
      engine.createImages(files, cb);
    },
    function saveImagePaths (images, cb) {
      // Iterate over the images and save their paths
      images.forEach(function saveImagePath (img, i) {
        img._filepath = files[i];
      });

      // Callback with the images
      cb(null, images);
    },
    // Then, add the images to our canvas (dry run)
    function smithAddFiles (images, cb) {
      images.forEach(function (img) {
        // Save the non-padded properties as meta data
        var width = img.width;
        var height = img.height;
        var meta = {img: img, actualWidth: width, actualHeight: height};

        // Add the item with padding to our layer
        layer.addItem({
          width: width + padding,
          height: height + padding,
          meta: meta
        });
      });

      // Callback with nothing
      cb(null);
    },
    // Then, output the coordinates
    function smithOutputCoordinates (cb) {
      // Export and saved packedObj for later
      packedObj = layer['export']();

      // Extract the coordinates
      var coordinates = {};
      var packedItems = packedObj.items;
      packedItems.forEach(function (item) {
        var meta = item.meta;
        var img = meta.img;
        var name = img._filepath;
        coordinates[name] = {
          x: item.x,
          y: item.y,
          width: meta.actualWidth,
          height: meta.actualHeight
        };
      });

      // Save the coordinates
      retObj.coordinates = coordinates;

      // Continue
      cb(null);
    },
    // Then, generate a canvas
    function generateCanvas (cb) {
      // Grab and fallback the width/height
      var width = Math.max(packedObj.width || 0, 0);
      var height = Math.max(packedObj.height || 0, 0);

      // If there are items
      var itemsExist = packedObj.items.length;
      if (itemsExist) {
        // Remove the last item's padding
        width -= padding;
        height -= padding;
      }

      // Export the total width and height of the generated canvas
      retObj.properties = {
        width: width,
        height: height
      };

      // If there are items, generate the canvas
      if (itemsExist) {
        var canvas = engine.createCanvas(width, height);
        process.nextTick(function handleNextTick () {
          cb(null, canvas);
        });
      // Otherwise, skip over potential errors/CPU
      } else {
        cb(null, null);
      }
    },
    // Then, export the canvas
    function exportCanvas (canvas, cb) {
      // If there is no canvas, callback with an empty string
      var items = packedObj.items;
      if (!canvas) {
        return cb(null, new Buffer(0));
      }

      // Add the images onto canvas
      try {
        items.forEach(function addImage (item) {
          var img = item.meta.img;
          canvas.addImage(img, item.x, item.y);
        });
      } catch (err) {
        return cb(err);
      }

      // Export our canvas
      var imageStream = canvas['export'](exportOpts);
      imageStream.on('error', cb);
      imageStream.pipe(concat(function handleResult (image) {
        cb(null, image);
      }));
    },
    function saveImage (image, cb) {
      // Save the image to the retObj
      retObj.image = image;

      // Callback
      cb(null);
    },
    function smithCallbackData (cb) {
      // Callback with the return object
      cb(null, retObj);
    }
  ], callback);
}

// Export spritesmith
module.exports = spritesmith;
<|endoftext|>


<commit_before>import io from 'socket.io-client'
import dotenv from 'dotenv'
import winston from 'winston'
import path from 'path'

import Presence from './modules/presence'
import music from './modules/music'

if (process.env.NODE_ENV !== 'production') {
    dotenv.config()
}

let presence = new Presence({
    interval: 5 * 1000
})

let socket = io(process.env.SERVER_URL, {
    reconnection: true
})

socket.on('connect', () => {
    winston.info('connected', { host: process.env.SERVER_URL })
    socket.emit('hello', {
        token: process.env.HOME_SPARK_TOKEN
    })

    socket.on('set-behavior', (behaviors) => {
        for (let behavior of behaviors) {
            if (behavior.type === 'watch-presence') {
                presence.addDevice({
                    device: behavior.device,
                    ip: behavior.device.ip,
                    isPresent: null
                })
                // console.log(behavior)
            }
        }
        winston.info('behavior-ready', { behaviors: behaviors })
    })

    socket.on('start-music', ({ speed }) => {
      winston.info('start-music')
      music.setVolume(0)
      if (speed !== 'none') {
        let volume = 0
        let intervalTimeout = 100
        let pitch = 1
        if (speed === 'fast') {
          intervalTimeout = 50
        } else if (speed === 'medium') {
          intervalTimeout = 150
        } else if (speed === 'slow') {
          intervalTimeout = 250
        }
        let interval = setInterval(() => {
          volume += pitch
          music.setVolume(volume)
          winston.info('setVolume', volume)
          if (volume >= 100) {
            clearInterval(interval)
          }
        }, intervalTimeout)
      }
      music.play(path.join(__dirname, '../', process.env.MUSIC))
    })

    socket.on('stop-music', ({ speed }) => {
      winston.info('stop-music')
      music.stop()
    })

    socket.on('volume-up', () => {
      winston.info('volume-up')
      music.setVolume(music.getVolume() + 20)
    })

    socket.on('volume-down', () => {
      winston.info('volume-down')
      music.setVolume(music.getVolume() - 20)
    })
})
/*
presence.watch()

presence.on('device-presence-changed', ({ device, previous }) => {

    socket.emit('behavior-result', {
        token: process.env.HOME_SPARK_TOKEN,
        type: 'watch-presence',
        payload: {
            device: device.device,
            currentState: device.isPresent,
            previousState: previous
        }
    })
    winston.info('device-presence-changed', { name: device.name, previous: previous, new:device.isPresent })
})*/
<commit_msg>change order start music<commit_after>import io from 'socket.io-client'
import dotenv from 'dotenv'
import winston from 'winston'
import path from 'path'

import Presence from './modules/presence'
import music from './modules/music'

if (process.env.NODE_ENV !== 'production') {
    dotenv.config()
}

let presence = new Presence({
    interval: 5 * 1000
})

let socket = io(process.env.SERVER_URL, {
    reconnection: true
})

socket.on('connect', () => {
    winston.info('connected', { host: process.env.SERVER_URL })
    socket.emit('hello', {
        token: process.env.HOME_SPARK_TOKEN
    })

    socket.on('set-behavior', (behaviors) => {
        for (let behavior of behaviors) {
            if (behavior.type === 'watch-presence') {
                presence.addDevice({
                    device: behavior.device,
                    ip: behavior.device.ip,
                    isPresent: null
                })
                // console.log(behavior)
            }
        }
        winston.info('behavior-ready', { behaviors: behaviors })
    })

    socket.on('start-music', ({ speed }) => {
      winston.info('start-music')
      music.setVolume(0)
      music.play(path.join(__dirname, '../', process.env.MUSIC))
      if (speed !== 'none') {
        let volume = 0
        let intervalTimeout = 100
        let pitch = 1
        if (speed === 'fast') {
          intervalTimeout = 50
        } else if (speed === 'medium') {
          intervalTimeout = 150
        } else if (speed === 'slow') {
          intervalTimeout = 250
        }

        let interval = setInterval(() => {
          volume += pitch
          music.setVolume(volume)
          winston.info('setVolume', volume)
          if (volume >= 90) {
            clearInterval(interval)
          }
        }, intervalTimeout)
      }
    })

    socket.on('stop-music', ({ speed }) => {
      winston.info('stop-music')
      music.stop()
    })

    socket.on('volume-up', () => {
      winston.info('volume-up')
      music.setVolume(music.getVolume() + 5)
    })

    socket.on('volume-down', () => {
      winston.info('volume-down')
      music.setVolume(music.getVolume() - 5)
    })
})
/*
presence.watch()

presence.on('device-presence-changed', ({ device, previous }) => {

    socket.emit('behavior-result', {
        token: process.env.HOME_SPARK_TOKEN,
        type: 'watch-presence',
        payload: {
            device: device.device,
            currentState: device.isPresent,
            previousState: previous
        }
    })
    winston.info('device-presence-changed', { name: device.name, previous: previous, new:device.isPresent })
})*/
<|endoftext|>


<commit_before>
import { start as startPot, resolveConfig } from 'pot-js';
import { resolve } from 'path';
import { init, defaultConfigFilename } from './config';
import workspace from './utils/workspace';
import { appLogger } from './utils/logger';
import outputHost from 'output-host';
import { isUndefined } from 'lodash';

export default async function start(options = {}) {
	const config = init(await resolveConfig({
		config: defaultConfigFilename,
		configWalk: true,
		...options,
		workspace,
		configToEnv: 'CLAYPOT_CONFIG',
		entry: resolve(__dirname, 'app.js'),
	}));

	await startPot(config);

	const enableHttps = config.ssl.enable;

	const logger = appLogger.info.bind(appLogger);

	if ((!config.outputHost && !isUndefined(config.outputHost)) ||
		config.production) {
		return;
	}

	outputHost({
		port: config.port,
		name: config.name,
		useCopy: !config.production && !enableHttps,
		logger,
	});

	if (enableHttps) {
		outputHost({
			port: config.ssl.port,
			name: `${config.name} HTTPS`,
			protocol: 'https',
			useCopy: !config.production,
			logger,
		});

	}
}
<commit_msg>add `outputHost` config<commit_after>
import { start as startPot, resolveConfig } from 'pot-js';
import { resolve } from 'path';
import { init, defaultConfigFilename } from './config';
import workspace from './utils/workspace';
import { appLogger } from './utils/logger';
import outputHost from 'output-host';
import { isUndefined, isObject } from 'lodash';

export default async function start(options = {}) {
	const config = init(await resolveConfig({
		config: defaultConfigFilename,
		configWalk: true,
		...options,
		workspace,
		configToEnv: 'CLAYPOT_CONFIG',
		entry: resolve(__dirname, 'app.js'),
	}));

	await startPot(config);

	const enableHttps = config.ssl.enable;

	const logger = appLogger.info.bind(appLogger);

	if ((!config.outputHost && !isUndefined(config.outputHost)) ||
		config.production) {
		return;
	}

	const outputHostConfig = isObject(config.outputHost) ? config.outputHost : {};

	outputHost({
		port: config.port,
		name: config.name,
		useCopy: !config.production && !enableHttps,
		logger,
		...outputHostConfig,
	});

	if (enableHttps) {
		outputHost({
			port: config.ssl.port,
			name: `${config.name} HTTPS`,
			protocol: 'https',
			useCopy: !config.production,
			logger,
			...outputHostConfig,
		});

	}
}
<|endoftext|>


<commit_before>import { EventEmitter2 } from 'eventemitter2';
import { Observable } from 'rxjs/Observable';
import { fromEvent } from 'rxjs/observable/fromEvent';
import Store from './store';
import { normalizePath } from './utils';

export default class State {

  constructor({
    store = new Store(),
    cursor = [],
    emitter = new EventEmitter2({
      wildcard: true,
      delimiter: '.',
      // FIXME: is it good?
      maxListeners: Infinity,
    }),
  } = {}) {
    this.__store = store;
    this.__cursor = cursor;
    this.__emitter = emitter;
  }

  cursor(subPath = '') {
    const { __store, __cursor, __emitter } = this;
    subPath = normalizePath(subPath);
    return new State({
      store: __store,
      cursor: __cursor.concat(subPath),
      emitter: __emitter,
    });
  }

  get(subPath = '') {
    const { length } = arguments;
    if (length !== 0) {
      return this.cursor(subPath).get();
    }
    return this.__store.read(this.__cursor);
  }

  set(subPath, value) {
    const { length } = arguments;
    if (length < 1) {
      throw new TypeError('value argument must be set');
    }
    if (length === 1) {
      value = subPath;
      subPath = undefined;
    }
    if (subPath !== undefined) {
      return this.cursor(subPath).set(value);
    }
    this.__store.write(this.__cursor, value);
    this.__emitter.emit(['change', ...this.__cursor], value);
  }

  currentCursor() {
    return this.__cursor.join('.');
  }

  listen(message) {
    let generatedMessage;
    switch (message) {
      case 'change':
        generatedMessage = ['change', ...this.__cursor, '**'].join('.');
        break;
      default:
        generatedMessage = message;
        break;
    }
    return Observable::fromEvent(this.__emitter, generatedMessage);
  }
}
<commit_msg>a little change, great eventemitter2<commit_after>import { EventEmitter2 } from 'eventemitter2';
import { Observable } from 'rxjs/Observable';
import { fromEvent } from 'rxjs/observable/fromEvent';
import Store from './store';
import { normalizePath } from './utils';

export default class State {

  constructor({
    store = new Store(),
    cursor = [],
    emitter = new EventEmitter2({
      wildcard: true,
      delimiter: '.',
      // FIXME: is it good?
      maxListeners: Infinity,
    }),
  } = {}) {
    this.__store = store;
    this.__cursor = cursor;
    this.__emitter = emitter;
  }

  cursor(subPath = '') {
    const { __store, __cursor, __emitter } = this;
    subPath = normalizePath(subPath);
    return new State({
      store: __store,
      cursor: __cursor.concat(subPath),
      emitter: __emitter,
    });
  }

  get(subPath = '') {
    const { length } = arguments;
    if (length !== 0) {
      return this.cursor(subPath).get();
    }
    return this.__store.read(this.__cursor);
  }

  set(subPath, value) {
    const { length } = arguments;
    if (length < 1) {
      throw new TypeError('value argument must be set');
    }
    if (length === 1) {
      value = subPath;
      subPath = undefined;
    }
    if (subPath !== undefined) {
      return this.cursor(subPath).set(value);
    }
    this.__store.write(this.__cursor, value);
    this.__emitter.emit(['change', ...this.__cursor, '**'].join('.'), value);
  }

  currentCursor() {
    return this.__cursor.join('.');
  }

  listen(message) {
    let generatedMessage;
    switch (message) {
      case 'change':
        generatedMessage = ['change', ...this.__cursor, '**'].join('.');
        break;
      default:
        generatedMessage = message;
        break;
    }
    return Observable::fromEvent(this.__emitter, generatedMessage);
  }
}
<|endoftext|>


<commit_before>'use strict';

/*!
 * koa-generic-session-mongo
 * Copyright(c) 2013 Pavel Vlasov <freakycue@gmail.com>
 * MIT Licensed
 */

import {EventEmitter} from 'events';
import {MongoClient} from 'mongodb';
import thunkify from 'thunkify';
import debug from 'debug';

const log = debug('koa-generic-session-mongo:store');
const ONE_DAY = 86400 * 1000;
const DEFAULT_COLLECTION = 'sessions';

export default class MongoStore extends EventEmitter {
  /**
   * Initialize MongoStore with the given `options`.
   *
   * @param {Object} options
   * @api public
   */
  constructor(options = {}) {
    super();
    const {
      db,
      collection,
      url,
      user,
      password
    } = options;

    if (url && ('host' in options || 'port' in options || 'db' in options || 'ssl' in options)) {
      throw new Error('url option is exclusive from host, port, db and ssl options, please include as a full url connection string');
    }

    this.col = db && typeof db !== 'string' && typeof db.dropDatabase === 'function' ?
      this._initWithDb({db, collection}) :
      this._initWithUrl({
        url: url || MongoStore._makeConnectionString(options),
        user,
        password
      });

    this.col
      .then(MongoStore._ensureIndexes)
      .then((collection) => {
        this.emit('connect', collection);
      }).catch((err) => {
        this.emit('error', err);
      });
  }

  /**
   * Init session collection with given database object
   * @param db Database object
   * @param collection Collection name which will store our sessions
   * @returns {Promise.<*>}
   * @private
   */
  _initWithDb({db, collection=DEFAULT_COLLECTION}) {
    return Promise.resolve(db.collection(collection));
  }

  /**
   *
   * @param url Connection string to db
   * @param user
   * @param password
   * @param collection Collection name which will store our sessions
   * @returns {Promise}
   * @private
   */
  _initWithUrl({url, user, password, collection=DEFAULT_COLLECTION}) {
    return new Promise((resolve, reject) => {
      new MongoClient().connect(url, function (err, db) {
        if (err) {
          reject(err);
          return;
        }
        const col = db.collection(collection);
        if (user && password) {
          db.authenticate(user, password, function (err, res) {
            if (err) {
              reject(err);
            } else if (!res) {
              reject(new Error('mongodb authentication failed'));
            } else {
              resolve(col);
            }
          });
        } else {
          resolve(col);
        }
      });
    })
  }

  static _makeConnectionString({host='127.0.0.1', port=27017, db='test', ssl=false}) {
    return `mongodb://${host}:${port}/${db}?ssl=${ssl}`;
  }

  /**
   * Create ttl and sid indexes
   * @param col
   * @returns {Promise}
   */
  static _ensureIndexes(col) {
    return new Promise(function (resolve, reject) {
      let times = 2;

      function done(err) {
        if (err) {
          reject(err);
        } else if (--times < 1) {
          resolve(col);
        }
      }

      col.ensureIndex({ttl: 1}, {expireAfterSeconds: 0}, done);
      col.ensureIndex({sid: 1}, {unique: true}, done);
    });
  }

  /**
   * Attempt to fetch session by the given `sid`.
   *
   * @param {String} sid
   * @param {Function} fn
   * @api public
   */
  *get(sid) {
    const col = yield this.col;
    const findOne = thunkify(col.findOne.bind(col));

    return yield findOne({sid: sid}, {_id: 0, ttl: 0, sid: 0});
  }

  /**
   * Commit the given `sess` object associated with the given `sid`.
   *
   * @param {String} sid
   * @param {Session} sess
   * @api public
   */
  *set(sid, sess, ttl) {
    const maxAge = sess.cookie && (sess.cookie.maxAge || sess.cookie.maxage);
    const col = yield this.col;
    const update = thunkify(col.update.bind(col));

    sess.sid = sid;
    sess.ttl = new Date((ttl || ('number' == typeof maxAge
      ? maxAge : ONE_DAY)) + Date.now());

    return yield update({sid: sid}, sess, {upsert: true});
  }

  /**
   * Destroy the session associated with the given `sid`.
   *
   * @param {String} sid
   * @api public
   */
  *destroy(sid) {
    const col = yield this.col;
    const remove = thunkify(col.remove.bind(col));

    yield remove({sid: sid});
  }
}
<commit_msg>not mutate original sess object in set method<commit_after>'use strict';

/*!
 * koa-generic-session-mongo
 * Copyright(c) 2013 Pavel Vlasov <freakycue@gmail.com>
 * MIT Licensed
 */

import {EventEmitter} from 'events';
import {MongoClient} from 'mongodb';
import thunkify from 'thunkify';
import debug from 'debug';

const log = debug('koa-generic-session-mongo:store');
const ONE_DAY = 86400 * 1000;
const DEFAULT_COLLECTION = 'sessions';

export default class MongoStore extends EventEmitter {
  /**
   * Initialize MongoStore with the given `options`.
   *
   * @param {Object} options
   * @api public
   */
  constructor(options = {}) {
    super();
    const {
      db,
      collection,
      url,
      user,
      password
    } = options;

    if (url && ('host' in options || 'port' in options || 'db' in options || 'ssl' in options)) {
      throw new Error('url option is exclusive from host, port, db and ssl options, please include as a full url connection string');
    }

    this.col = db && typeof db !== 'string' && typeof db.dropDatabase === 'function' ?
      this._initWithDb({db, collection}) :
      this._initWithUrl({
        url: url || MongoStore._makeConnectionString(options),
        user,
        password
      });

    this.col
      .then(MongoStore._ensureIndexes)
      .then((collection) => {
        this.emit('connect', collection);
      }).catch((err) => {
        this.emit('error', err);
      });
  }

  /**
   * Init session collection with given database object
   * @param db Database object
   * @param collection Collection name which will store our sessions
   * @returns {Promise.<*>}
   * @private
   */
  _initWithDb({db, collection=DEFAULT_COLLECTION}) {
    return Promise.resolve(db.collection(collection));
  }

  /**
   *
   * @param url Connection string to db
   * @param user
   * @param password
   * @param collection Collection name which will store our sessions
   * @returns {Promise}
   * @private
   */
  _initWithUrl({url, user, password, collection=DEFAULT_COLLECTION}) {
    return new Promise((resolve, reject) => {
      new MongoClient().connect(url, function (err, db) {
        if (err) {
          reject(err);
          return;
        }
        const col = db.collection(collection);
        if (user && password) {
          db.authenticate(user, password, function (err, res) {
            if (err) {
              reject(err);
            } else if (!res) {
              reject(new Error('mongodb authentication failed'));
            } else {
              resolve(col);
            }
          });
        } else {
          resolve(col);
        }
      });
    })
  }

  static _makeConnectionString({host='127.0.0.1', port=27017, db='test', ssl=false}) {
    return `mongodb://${host}:${port}/${db}?ssl=${ssl}`;
  }

  /**
   * Create ttl and sid indexes
   * @param col
   * @returns {Promise}
   */
  static _ensureIndexes(col) {
    return new Promise(function (resolve, reject) {
      let times = 2;

      function done(err) {
        if (err) {
          reject(err);
        } else if (--times < 1) {
          resolve(col);
        }
      }

      col.ensureIndex({ttl: 1}, {expireAfterSeconds: 0}, done);
      col.ensureIndex({sid: 1}, {unique: true}, done);
    });
  }

  /**
   * Attempt to fetch session by the given `sid`.
   *
   * @param {String} sid
   * @param {Function} fn
   * @api public
   */
  *get(sid) {
    const col = yield this.col;
    const findOne = thunkify(col.findOne.bind(col));

    return yield findOne({sid: sid}, {_id: 0, ttl: 0, sid: 0});
  }

  /**
   * Commit the given `sess` object associated with the given `sid`.
   *
   * @param {String} sid
   * @param {Session} sess
   * @api public
   */
  *set(sid, sess, ttl) {
    // clone original sess
    sess = {...sess};
    const maxAge = sess.cookie && (sess.cookie.maxAge || sess.cookie.maxage);
    const col = yield this.col;
    const update = thunkify(col.update.bind(col));

    sess.sid = sid;
    sess.ttl = new Date((ttl || ('number' == typeof maxAge
      ? maxAge : ONE_DAY)) + Date.now());

    return yield update({sid: sid}, sess, {upsert: true});
  }

  /**
   * Destroy the session associated with the given `sid`.
   *
   * @param {String} sid
   * @api public
   */
  *destroy(sid) {
    const col = yield this.col;
    const remove = thunkify(col.remove.bind(col));

    yield remove({sid: sid});
  }
}
<|endoftext|>