<commit_before>/* jshint esnext: true, node: true */
'use strict'

/*******************************************************************************
Import month-to-date DBRs, overwriting the existing month-to-date.
*******************************************************************************/

var util = require('util')

var log = require('loglevel')
var rollbar = require('rollbar')
var moment = require('moment')

var BaseParser = require('./lib/baseparser.js')
var DBR = require('./lib/dbr.js')
var Redshift = require('./lib/redshift.js')
var cliUtils = require('./lib/cliutils.js')

rollbar.init(process.env.ROLLBAR_TOKEN, {environment: process.env.ROLLBAR_ENVIRONMENT})
rollbar.handleUncaughtExceptions(process.env.ROLLBAR_TOKEN,
                                 {exitOnUncaughtException: true})

var parser = new BaseParser({
  version: '0.0.1',
  addHelp: true,
  description: 'Imports month-to-date detailed billing reports'
})

parser.addArgument(
  ['--no-stage'], {
    action: 'storeConst',
    dest: 'no_stage',
    help: 'Use an existing staged month-to-date DBR.',
    constant: true
  }
)

var args = parser.parseArgs()

if (args.debug) {
  log.setLevel('debug')
  log.debug('Debugging output enabled.')
} else {
  log.setLevel('info')
}
log.debug(`Resolved invocation arguments were:\n${util.inspect(args)}`)

// Instantiate a DBR object to work with.
var dbrClientOptions = {
  accessKeyId: args.source_key,
  secretAccessKey: args.source_secret
}

var stagingClientOptions = {
  accessKeyId: args.staging_key,
  secretAccessKey: args.staging_secret
}

var dbr = new DBR(dbrClientOptions, stagingClientOptions,
                  args.source_bucket, args.staging_bucket)

// Instantiate a Redshift object to work with.
var redshift = new Redshift(args.redshift_uri, {
      key: args.staging_key,
      secret: args.staging_secret
})

let startTime = moment.utc()

dbr.getMonthToDateDBR()
  .then(stageDBRCheck)
  .then(importDBR)
  .then(vacuum)
  .then(function () {
    cliUtils.runCompleteHandler(startTime, 0)
  })
  .catch(cliUtils.rejectHandler)

// Determine whether to stage the latest month-to-date DBR or reuse existing
function stageDBRCheck (monthToDateDBR) {
  log.info(`Found month-to-date for ${monthToDateDBR.Month.format('MMMM YYYY')}...`)
  if (args.no_stage) {
    let s3uri = dbr.composeStagedURI(monthToDateDBR)
    log.info(`--no-stage specified, Attempting to use existing staged month-to-date DBR`)
    return s3uri
  } else {
    log.info(`Staging DBR file for ${monthToDateDBR.Month.format('MMMM YYYY')}.`)
    return dbr.stageDBR(monthToDateDBR.Month)
  }
}

// Import the staged month-to-date DBR
// TODO if we just chain like .then(redshift.importMonthToDate), it fails
// because 'this' inside importMonthToDate will be undefined. Why?
function importDBR (s3uri) {
  log.info(`Importing ${s3uri} into month_to_date...`)
  return redshift.importMonthToDate(s3uri)
}

// Run VACUUM on the month_to_date table
function vacuum () {
  if (!args.no_vacuum) {
    log.info('Running VACUUM on line_items...')
    return redshift.vacuum('month_to_date')
  } else {
    log.info('--no-vacuum specified, skiping vacuum.')
    return
  }
}
<commit_msg>Remove jshint config line<commit_after>'use strict'

/*******************************************************************************
Import month-to-date DBRs, overwriting the existing month-to-date.
*******************************************************************************/

var util = require('util')

var log = require('loglevel')
var rollbar = require('rollbar')
var moment = require('moment')

var BaseParser = require('./lib/baseparser.js')
var DBR = require('./lib/dbr.js')
var Redshift = require('./lib/redshift.js')
var cliUtils = require('./lib/cliutils.js')

rollbar.init(process.env.ROLLBAR_TOKEN, {environment: process.env.ROLLBAR_ENVIRONMENT})
rollbar.handleUncaughtExceptions(process.env.ROLLBAR_TOKEN,
                                 {exitOnUncaughtException: true})

var parser = new BaseParser({
  version: '0.0.1',
  addHelp: true,
  description: 'Imports month-to-date detailed billing reports'
})

parser.addArgument(
  ['--no-stage'], {
    action: 'storeConst',
    dest: 'no_stage',
    help: 'Use an existing staged month-to-date DBR.',
    constant: true
  }
)

var args = parser.parseArgs()

if (args.debug) {
  log.setLevel('debug')
  log.debug('Debugging output enabled.')
} else {
  log.setLevel('info')
}
log.debug(`Resolved invocation arguments were:\n${util.inspect(args)}`)

// Instantiate a DBR object to work with.
var dbrClientOptions = {
  accessKeyId: args.source_key,
  secretAccessKey: args.source_secret
}

var stagingClientOptions = {
  accessKeyId: args.staging_key,
  secretAccessKey: args.staging_secret
}

var dbr = new DBR(dbrClientOptions, stagingClientOptions,
                  args.source_bucket, args.staging_bucket)

// Instantiate a Redshift object to work with.
var redshift = new Redshift(args.redshift_uri, {
      key: args.staging_key,
      secret: args.staging_secret
})

let startTime = moment.utc()

dbr.getMonthToDateDBR()
  .then(stageDBRCheck)
  .then(importDBR)
  .then(vacuum)
  .then(function () {
    cliUtils.runCompleteHandler(startTime, 0)
  })
  .catch(cliUtils.rejectHandler)

// Determine whether to stage the latest month-to-date DBR or reuse existing
function stageDBRCheck (monthToDateDBR) {
  log.info(`Found month-to-date for ${monthToDateDBR.Month.format('MMMM YYYY')}...`)
  if (args.no_stage) {
    let s3uri = dbr.composeStagedURI(monthToDateDBR)
    log.info(`--no-stage specified, Attempting to use existing staged month-to-date DBR`)
    return s3uri
  } else {
    log.info(`Staging DBR file for ${monthToDateDBR.Month.format('MMMM YYYY')}.`)
    return dbr.stageDBR(monthToDateDBR.Month)
  }
}

// Import the staged month-to-date DBR
// TODO if we just chain like .then(redshift.importMonthToDate), it fails
// because 'this' inside importMonthToDate will be undefined. Why?
function importDBR (s3uri) {
  log.info(`Importing ${s3uri} into month_to_date...`)
  return redshift.importMonthToDate(s3uri)
}

// Run VACUUM on the month_to_date table
function vacuum () {
  if (!args.no_vacuum) {
    log.info('Running VACUUM on line_items...')
    return redshift.vacuum('month_to_date')
  } else {
    log.info('--no-vacuum specified, skiping vacuum.')
    return
  }
}
<|endoftext|>


<commit_before>import { Meteor } from 'meteor/meteor';
import { expect } from 'meteor/practicalmeteor:chai';
import fetch from 'isomorphic-unfetch';

// In theory this test could actually be run on the server as well. Regrettably
// the test runner starts the server tests before the database is fully
// populated. As a result those tests will very likely time out.
if (Meteor.isClient) {
	describe('GroupApi', function () {
		it('should return JSON response', async function () {
			const groups = Meteor.absoluteUrl('/api/0/json/groups');
			const result = await fetch(groups);

			expect(result.status).to.equal(200);
			expect(result.headers.get('Content-Type')).to.equal('application/json; charset=utf-8');
		});
	});
}
<commit_msg>deasyncify API test<commit_after>import { Meteor } from 'meteor/meteor';
import { expect } from 'meteor/practicalmeteor:chai';
import fetch from 'isomorphic-unfetch';

// In theory this test could actually be run on the server as well. Regrettably
// the test runner starts the server tests before the database is fully
// populated. As a result those tests will very likely time out.
if (Meteor.isClient) {
	describe('GroupApi', function () {
		it('should return JSON response', function (done) {
			const groups = Meteor.absoluteUrl('/api/0/json/groups');
			fetch(groups).then((result) => {
				expect(result.status).to.equal(200);
				expect(result.headers.get('Content-Type')).to.equal('application/json; charset=utf-8');
				done();
			});
		});
	});
}
<|endoftext|>


<commit_before>/***
 Copyright (c) 2012 Tony Findeisen, Marcus Krejpowicz

 (The MIT License)

 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 THE SOFTWARE.

 */
(function (exports, requirejs, define, window, XMLHttpRequest) {
    /** ECMA SCRIPT COMPLIANT**/
    if (!String.prototype.trim) {
        String.prototype.trim = function () {
            return this.replace(/^\s+|\s+$/g, '');
        };
    }

    var underscore,
        Stage,
        document = window.document; // TODO: create workaround for node

    /***
     * marks a function to be executed asycn
     * @return {*}
     */
    Function.prototype.async = function () {
        this._async = true;
        return this;
    };

    var xamlApplication = /^(xaml!)?(.+?)(\.xml)?$/;

    var Rewrite = function (from, to) {
            this.$from = from;
            this.$to = to;
        },
        defaultNamespaceMap = {
            "http://www.w3.org/1999/xhtml": "js.html",
            "http://www.w3.org/2000/svg": "js.svg"
        },
        defaultRewriteMap = [
            new Rewrite(/^js\/html\/(a)$/, "js/html/a"),
            new Rewrite(/^js\/html\/(input)$/, "js/html/Input"),
            new Rewrite(/^js\/html\/(select)$/, "js/html/Select"),
            new Rewrite(/^js\/html\/(textarea)$/, "js/html/TextArea"),
            new Rewrite(/^js\/html\/(option)$/, "js/html/Option"),
            new Rewrite(/^js\/html\/(.+)$/, "js/html/HtmlElement"),

            new Rewrite(/^js\/svg\/svg$/, "js/svg/Svg"),
            new Rewrite(/^js\/svg\/(.+)$/, "js/svg/SvgElement")
        ];

    if (typeof JSON !== "undefined") {
        define("JSON", function () {
            return JSON;
        });
    } else {
        requirejs.config({
            paths: {
                JSON: "js/lib/json2"
            },
            shim: {
                JSON: {
                    exports: "JSON"
                }
            }
        });
    }

    requirejs.config({
        paths: {
            json: "js/plugin/json"
        }
    });

    var rAppid = {

        createApplicationContext: function (mainClass, config, callback) {

            config = config || {};

            var internalCreateApplicationContext = function (config) {

                config.xamlClasses = config.xamlClasses || [];
                config.namespaceMap = config.namespaceMap || defaultNamespaceMap;
                config.rewriteMap = config.rewriteMap || defaultRewriteMap;

                var requirejsContext = requirejs.config(config),
                    applicationContext = new ApplicationContext(requirejsContext, config);

                define("applicationContext", function () {
                    return applicationContext;
                });

                if (typeof JSON !== "undefined") {
                    define("JSON", function () {
                        return JSON;
                    });
                }

                requirejsContext(["inherit", "underscore", "js/core/Stage"], function (inherit, _, s) {
                    // we have to load inherit.js in order that inheritance is working
                    underscore = _;
                    Stage = s;

                    if (inherit && _) {

                        if (mainClass) {
                            //TODO: have a look at xamlClasses
                            var parts = xamlApplication.exec(mainClass);
                            if (parts) {
                                // mainClass is xaml
                                mainClass = "xaml!" + parts[2];
                            } else {
                                // mainClass is javascript factory
                                mainClass = mainClass.replace(/\./g, "/");
                            }

                            requirejsContext([mainClass], function (applicationFactory) {
                                applicationContext.$applicationFactory = applicationFactory;
                                callback(null, applicationContext);
                            }, function (err) {
                                callback(err);
                            });
                        } else {
                            callback(null, applicationContext);
                        }

                    } else {
                        callback("inherit or underscore missing");
                    }
                });

            };

            if (Object.prototype.toString.call(config) == '[object String]') {
                requirejs(["json!" + config], function (config) {
                    internalCreateApplicationContext(config);
                });
            } else {

                if (config.loadConfiguration) {

                    if (config.baseUrl) {
                        requirejs.config({
                            baseUrl: config.baseUrl
                        });
                    }

                    requirejs(["json!" + config.loadConfiguration], function (loadedConfig) {
                        loadedConfig = loadedConfig || {};
                        for (var key in config) {
                            if (config.hasOwnProperty(key)) {
                                loadedConfig[key] = config[key];
                            }
                        }

                        internalCreateApplicationContext(loadedConfig);
                    });
                } else {
                    internalCreateApplicationContext(config);
                }
            }

        },

        /***
         *
         * @param {js.core.Application} mainClass the application main class to load and start
         * @param {Element} [target=document.body] the target where the application is rendered
         * @param {Object} [parameter] an object defining the parameters passed to the Application.start method
         * @param {String|Object} [config=config.json] filename of the config file to load or configuration object
         * @param {Function} [callback] callback function in the form function (err, systemManager, application)
         */
        bootStrap: function (mainClass, target, parameter, config, callback) {

            parameter = parameter || {};

            if (typeof window !== 'undefined' && window.location && !parameter.initialHash) {
                var param = window.location.search.replace(/^\?/, '').split('&');
                for (var i = 0; i < param.length; i++) {
                    var result = /^([^=]+)=(.*)$/.exec(param[i]);
                    if (result && result[1] === 'fragment') {

                        var redirectUrl = location.protocol + '//' + location.host + location.pathname;
                        param.splice(i, 1);

                        if (param.length) {
                            redirectUrl += '?' + param.join('&');
                        }

                        redirectUrl += '#' + result[2];
                        window.location = redirectUrl;

                        return;
                    }
                }
            }

            if (!target && document && document.body) {
                // render default into document.body
                target = document.body;
            }

            config = config || "config.json";

            callback = callback || function (err) {
                if (err && typeof console !== "undefined") {
                    console.error(err.stack || err);
                }
            };

            if (!document) {
                callback("Document missing");
                return;
            }

            if (!target) {
                callback("Target missing");
                return;
            }

            // flow.js is not available here, so do it in a dirty way
            rAppid.createApplicationContext(mainClass, config, function (err, applicationContext) {
                if (err) {
                    callback(err);
                } else {
                    applicationContext.createApplicationInstance(window, function (err, stage, application) {
                        if (err) {
                            callback(err);
                        } else {

                            application.start(parameter, function (err) {
                                if (err) {
                                    callback(err);
                                } else {
                                    // render stage to target
                                    stage.render(target);
                                    callback(null, stage, application);
                                }
                            });

                        }
                    })
                }
            });

        },

        rewriteMapEntry: Rewrite,

        createQueryString: function (parameter) {
            var ret = [];

            for (var key in parameter) {
                if (parameter.hasOwnProperty(key)) {
                    ret.push(encodeURIComponent(key) + "=" + encodeURIComponent(parameter[key]));
                }
            }

            return ret.join("&");
        },

        ajax: function (url, options, callback) {

            var s = {
                url: url
            };

            underscore.extend(s, rAppid.ajaxSettings, options);

            if (s.data && !(underscore.isString(s.data) || (typeof FormData !== "undefined" && s.data instanceof FormData))) {
                throw "data must be a string";
            }

            s.hasContent = !/^(?:GET|HEAD)$/.test(s.type);

            if (s.queryParameter && underscore.keys(s.queryParameter).length > 0) {
                // append query parameter to url
                s.url += /\?/.test(s.url) ? "&" : "?" + this.createQueryString(s.queryParameter);
            }

            // create new xhr
            var xhr = s.xhr();
            options && options.xhrCreated instanceof Function && options.xhrCreated(xhr);
            xhr.open(s.type, s.url, s.async);

            if (s.hasContent && s.contentType !== false) {
                xhr.setRequestHeader("Content-Type", s.contentType);
                if (typeof window === "undefined") {
                    // On NodeJs the XMLHttprequest does not set Content-Length
                    // In the browser it's not allowed to set the Content-length
                    xhr.setRequestHeader("Content-Length", s.data ? s.data.length.toString() : "0");
                }
            }

            try {
                for (var header in s.headers) {
                    if (s.headers.hasOwnProperty(header)) {
                        xhr.setRequestHeader(header, s.headers[header]);
                    }
                }
            } catch (e) {
            } // FF3

            options && options.xhrBeforeSend instanceof Function && options.xhrBeforeSend(xhr);
            xhr.send(s.data);

            var xhrCallback = function (_, isAbort) {

                var wrappedXhr;

                if (xhrCallback && (isAbort || xhr.readyState === 4)) {
                    xhrCallback = undefined;

                    if (isAbort) {
                        // Abort it manually if needed
                        if (xhr.readyState !== 4) {
                            xhr.abort();
                        }
                    } else {
                        wrappedXhr = new rAppidXhr(xhr);
                    }

                    if (callback) {
                        callback(isAbort, wrappedXhr)
                    }
                }
            };

            if (!s.async || xhr.readyState === 4) {
                xhrCallback();
            } else {
                xhr.onreadystatechange = xhrCallback
            }

            return xhr;
        },

        instances: []
    };

    var rheaders = /^(.*?):[ \t]*([^\r\n]*)\r?$/mg; // IE leaves an \r character at EOL

    var rAppidXhr = function (xhr) {
        this.xhr = xhr;
        this.status = xhr.status;
        this.$nativeResponseHeaders = xhr.getAllResponseHeaders();
        this.responses = {};

        var xml = xhr.responseXML;

        // Construct response list
        if (xml && xml.documentElement) {
            this.responses.xml = xml;
        }
        this.responses.text = xhr.responseText;

        try {
            this.statusText = xhr.statusText;
        } catch (e) {
            this.statusText = "";
        }
    };

    rAppidXhr.prototype.getResponseHeader = function (key) {
        var match;
        if (!this.$responseHeaders) {
            this.$responseHeaders = {};
            while (( match = rheaders.exec(this.$nativeResponseHeaders) )) {
                this.$responseHeaders[match[1].toLowerCase()] = match[2];
            }
        }
        return this.$responseHeaders[key.toLowerCase()];
    };

    rAppid.ajaxSettings = {
        type: "GET",
        contentType: "application/x-www-form-urlencoded",
        async: true,
        xhr: function () {
            return new XMLHttpRequest();
        },
        headers: {
        },
        data: null
    };

    var ApplicationContext = function (requirejsContext, config) {
        this.$requirejsContext = requirejsContext;
        this.$config = config;
    };

    var interCommunicationBus;

    ApplicationContext.prototype.createApplicationInstance = function (window, callback) {

        var document;

        // create instance
        var applicationFactory = this.$applicationFactory;

        if (window.document) {
            document = window.document;
        } else {
            document = window;
            window = null;
        }

        var stage = new Stage(this.$requirejsContext, this, document, window);

        this.$requirejsContext(["js/core/Application", "js/core/HeadManager", "js/core/History", "js/core/Injection", "js/core/InterCommunicationBus", "js/core/Bindable"], function (Application, HeadManager, History, Injection, InterCommunicationBus, Bindable) {

            interCommunicationBus = interCommunicationBus || new InterCommunicationBus();

            stage.$headManager = new HeadManager(document);
            stage.$history = new History();
            var injection = stage.$injection = new Injection(null, null, stage);

            stage.$environment = new Bindable();

            injection.addInstance(stage.$bus);
            injection.addInstance(stage.$history);
            injection.addInstance(stage.$headManager);
            injection.addInstance(stage.$externalInterface);
            injection.addInstance(interCommunicationBus);
            injection.addInstance("ENV", stage.$environment);

            var application = new applicationFactory(null, false, stage, null, null);

            if (application instanceof Application) {

                var environmentSetupComplete = function (err) {
                    if (!err) {
                        application.set('ENV', stage.$environment);

                        stage.$application = application;
                        stage._initialize("auto");

                        application._initialize("auto");

                        // return rAppid instance
                        if (callback) {
                            callback(null, stage, application);
                        }
                    } else {
                        callback && callback(err, stage, application);
                    }
                };

                if (application.supportEnvironments) {
                    Application.setupEnvironment(stage.$environment, application._getEnvironment(), application.applicationDefaultNamespace, environmentSetupComplete);
                } else {
                    environmentSetupComplete();
                }

            } else {
                var errMessage = "mainClass isn't an instance of js.core.Application";
                if (callback) {
                    callback(errMessage);
                } else {
                    throw(errMessage);
                }
            }
        });

    };

    ApplicationContext.prototype.getFqClassName = function (namespace, className, useRewriteMap) {
        if (useRewriteMap == undefined || useRewriteMap == null) {
            useRewriteMap = true;
        }

        if (namespace && className) {
            namespace = (this.$config.namespaceMap[namespace] || namespace).replace(/\./g, '/');
            var fqClassName = [namespace, className].join("/");
        } else {
            fqClassName = (namespace || className).replace(/\./g, '/');
        }

        if (underscore.indexOf(this.$config.xamlClasses, fqClassName) !== -1) {
            fqClassName = 'xaml!' + fqClassName;
        }

        if (useRewriteMap) {
            for (var i = 0; i < this.$config.rewriteMap.length; i++) {
                var entry = this.$config.rewriteMap[i];
                if (entry instanceof rAppid.rewriteMapEntry) {
                    if (entry.$from.test(fqClassName)) {
                        return fqClassName.replace(entry.$from, entry.$to);
                    }
                }
            }
        }

        return fqClassName;
    };

    ApplicationContext.prototype.createInstance = function (fqClassName, args, className) {
        args = args || [];

        var classDefinition;

        if (fqClassName instanceof Function) {
            classDefinition = fqClassName;
            fqClassName = classDefinition.prototype.constructor.name;
        } else {
            fqClassName = fqClassName.replace(/\./g, "/");
            classDefinition = this.$requirejsContext(fqClassName);
        }

        className = className || fqClassName;

        function construct(constructor, args) {
            function F() {
                return constructor.apply(this, args);
            }

            F.prototype = constructor.prototype;
            return new F();
        }

        var ret;
        try {
            ret = construct(classDefinition, args);
            ret.className = className;
        } catch (e) {
            console.warn(["Cannot create instance of '" + fqClassName + "'", e, args]);
            throw e;
        }

        return ret;
    };

    ApplicationContext.prototype.ajax = function (url, options, callback) {

        if (!(/^http.*$/.test(url)) && this.$config.applicationUrl) {
            url = this.$config.applicationUrl + '/' + url;
        }

        rAppid.ajax(url, options, callback);
    };

    rAppid.defaultNamespaceMap = defaultNamespaceMap;
    rAppid.defaultRewriteMap = defaultRewriteMap;
    rAppid.ApplicationContext = ApplicationContext;
    rAppid.Rewrite = Rewrite;

    exports.rAppid = rAppid;

}(typeof exports !== "undefined" ? exports : window,
    typeof requirejs !== "undefined" ? requirejs : require('requirejs'),
    typeof requirejs !== "undefined" ? define : require('requirejs').define,
    typeof window !== "undefined" ? window : exports,
    typeof window !== "undefined" ? window.XMLHttpRequest : require('xmlhttprequest').XMLHttpRequest));
<commit_msg>added creationTime for applicationContext and application<commit_after>/***
 Copyright (c) 2012 Tony Findeisen, Marcus Krejpowicz

 (The MIT License)

 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 THE SOFTWARE.

 */
(function (exports, requirejs, define, window, XMLHttpRequest) {
    /** ECMA SCRIPT COMPLIANT**/
    if (!String.prototype.trim) {
        String.prototype.trim = function () {
            return this.replace(/^\s+|\s+$/g, '');
        };
    }

    var underscore,
        Stage,
        document = window.document; // TODO: create workaround for node

    /***
     * marks a function to be executed asycn
     * @return {*}
     */
    Function.prototype.async = function () {
        this._async = true;
        return this;
    };

    var xamlApplication = /^(xaml!)?(.+?)(\.xml)?$/;

    var Rewrite = function (from, to) {
            this.$from = from;
            this.$to = to;
        },
        defaultNamespaceMap = {
            "http://www.w3.org/1999/xhtml": "js.html",
            "http://www.w3.org/2000/svg": "js.svg"
        },
        defaultRewriteMap = [
            new Rewrite(/^js\/html\/(a)$/, "js/html/a"),
            new Rewrite(/^js\/html\/(input)$/, "js/html/Input"),
            new Rewrite(/^js\/html\/(select)$/, "js/html/Select"),
            new Rewrite(/^js\/html\/(textarea)$/, "js/html/TextArea"),
            new Rewrite(/^js\/html\/(option)$/, "js/html/Option"),
            new Rewrite(/^js\/html\/(.+)$/, "js/html/HtmlElement"),

            new Rewrite(/^js\/svg\/svg$/, "js/svg/Svg"),
            new Rewrite(/^js\/svg\/(.+)$/, "js/svg/SvgElement")
        ];

    if (typeof JSON !== "undefined") {
        define("JSON", function () {
            return JSON;
        });
    } else {
        requirejs.config({
            paths: {
                JSON: "js/lib/json2"
            },
            shim: {
                JSON: {
                    exports: "JSON"
                }
            }
        });
    }

    requirejs.config({
        paths: {
            json: "js/plugin/json"
        }
    });

    var rAppid = {

        createApplicationContext: function (mainClass, config, callback) {

            var time = (new Date()).getTime();
            config = config || {};

            var internalCreateApplicationContext = function (config) {

                config.xamlClasses = config.xamlClasses || [];
                config.namespaceMap = config.namespaceMap || defaultNamespaceMap;
                config.rewriteMap = config.rewriteMap || defaultRewriteMap;

                var requirejsContext = requirejs.config(config),
                    applicationContext = new ApplicationContext(requirejsContext, config);

                define("applicationContext", function () {
                    return applicationContext;
                });

                if (typeof JSON !== "undefined") {
                    define("JSON", function () {
                        return JSON;
                    });
                }

                requirejsContext(["inherit", "underscore", "js/core/Stage"], function (inherit, _, s) {
                    // we have to load inherit.js in order that inheritance is working
                    underscore = _;
                    Stage = s;

                    if (inherit && _) {

                        if (mainClass) {
                            //TODO: have a look at xamlClasses
                            var parts = xamlApplication.exec(mainClass);
                            if (parts) {
                                // mainClass is xaml
                                mainClass = "xaml!" + parts[2];
                            } else {
                                // mainClass is javascript factory
                                mainClass = mainClass.replace(/\./g, "/");
                            }

                            requirejsContext([mainClass], function (applicationFactory) {
                                applicationContext.$applicationFactory = applicationFactory;
                                applicationContext.$creationTime = (new Date()).getTime() - time;
                                callback(null, applicationContext);
                            }, function (err) {
                                callback(err);
                            });
                        } else {
                            applicationContext.$creationTime = (new Date()).getTime() - time;
                            callback(null, applicationContext);
                        }
                    } else {
                        callback("inherit or underscore missing");
                    }
                });

            };

            if (Object.prototype.toString.call(config) == '[object String]') {
                requirejs(["json!" + config], function (config) {
                    internalCreateApplicationContext(config);
                });
            } else {

                if (config.loadConfiguration) {

                    if (config.baseUrl) {
                        requirejs.config({
                            baseUrl: config.baseUrl
                        });
                    }

                    requirejs(["json!" + config.loadConfiguration], function (loadedConfig) {
                        loadedConfig = loadedConfig || {};
                        for (var key in config) {
                            if (config.hasOwnProperty(key)) {
                                loadedConfig[key] = config[key];
                            }
                        }

                        internalCreateApplicationContext(loadedConfig);
                    });
                } else {
                    internalCreateApplicationContext(config);
                }
            }

        },

        /***
         *
         * @param {js.core.Application} mainClass the application main class to load and start
         * @param {Element} [target=document.body] the target where the application is rendered
         * @param {Object} [parameter] an object defining the parameters passed to the Application.start method
         * @param {String|Object} [config=config.json] filename of the config file to load or configuration object
         * @param {Function} [callback] callback function in the form function (err, systemManager, application)
         */
        bootStrap: function (mainClass, target, parameter, config, callback) {

            parameter = parameter || {};

            if (typeof window !== 'undefined' && window.location && !parameter.initialHash) {
                var param = window.location.search.replace(/^\?/, '').split('&');
                for (var i = 0; i < param.length; i++) {
                    var result = /^([^=]+)=(.*)$/.exec(param[i]);
                    if (result && result[1] === 'fragment') {

                        var redirectUrl = location.protocol + '//' + location.host + location.pathname;
                        param.splice(i, 1);

                        if (param.length) {
                            redirectUrl += '?' + param.join('&');
                        }

                        redirectUrl += '#' + result[2];
                        window.location = redirectUrl;

                        return;
                    }
                }
            }

            if (!target && document && document.body) {
                // render default into document.body
                target = document.body;
            }

            config = config || "config.json";

            callback = callback || function (err) {
                if (err && typeof console !== "undefined") {
                    console.error(err.stack || err);
                }
            };

            if (!document) {
                callback("Document missing");
                return;
            }

            if (!target) {
                callback("Target missing");
                return;
            }

            // flow.js is not available here, so do it in a dirty way
            rAppid.createApplicationContext(mainClass, config, function (err, applicationContext) {
                if (err) {
                    callback(err);
                } else {
                    applicationContext.createApplicationInstance(window, function (err, stage, application) {
                        if (err) {
                            callback(err);
                        } else {

                            application.start(parameter, function (err) {
                                if (err) {
                                    callback(err);
                                } else {
                                    // render stage to target
                                    stage.render(target);
                                    callback(null, stage, application);
                                }
                            });

                        }
                    })
                }
            });

        },

        rewriteMapEntry: Rewrite,

        createQueryString: function (parameter) {
            var ret = [];

            for (var key in parameter) {
                if (parameter.hasOwnProperty(key)) {
                    ret.push(encodeURIComponent(key) + "=" + encodeURIComponent(parameter[key]));
                }
            }

            return ret.join("&");
        },

        ajax: function (url, options, callback) {

            var s = {
                url: url
            };

            underscore.extend(s, rAppid.ajaxSettings, options);

            if (s.data && !(underscore.isString(s.data) || (typeof FormData !== "undefined" && s.data instanceof FormData))) {
                throw "data must be a string";
            }

            s.hasContent = !/^(?:GET|HEAD)$/.test(s.type);

            if (s.queryParameter && underscore.keys(s.queryParameter).length > 0) {
                // append query parameter to url
                s.url += /\?/.test(s.url) ? "&" : "?" + this.createQueryString(s.queryParameter);
            }

            // create new xhr
            var xhr = s.xhr();
            options && options.xhrCreated instanceof Function && options.xhrCreated(xhr);
            xhr.open(s.type, s.url, s.async);

            if (s.hasContent && s.contentType !== false) {
                xhr.setRequestHeader("Content-Type", s.contentType);
                if (typeof window === "undefined") {
                    // On NodeJs the XMLHttprequest does not set Content-Length
                    // In the browser it's not allowed to set the Content-length
                    xhr.setRequestHeader("Content-Length", s.data ? s.data.length.toString() : "0");
                }
            }

            try {
                for (var header in s.headers) {
                    if (s.headers.hasOwnProperty(header)) {
                        xhr.setRequestHeader(header, s.headers[header]);
                    }
                }
            } catch (e) {
            } // FF3

            options && options.xhrBeforeSend instanceof Function && options.xhrBeforeSend(xhr);
            xhr.send(s.data);

            var xhrCallback = function (_, isAbort) {

                var wrappedXhr;

                if (xhrCallback && (isAbort || xhr.readyState === 4)) {
                    xhrCallback = undefined;

                    if (isAbort) {
                        // Abort it manually if needed
                        if (xhr.readyState !== 4) {
                            xhr.abort();
                        }
                    } else {
                        wrappedXhr = new rAppidXhr(xhr);
                    }

                    if (callback) {
                        callback(isAbort, wrappedXhr)
                    }
                }
            };

            if (!s.async || xhr.readyState === 4) {
                xhrCallback();
            } else {
                xhr.onreadystatechange = xhrCallback
            }

            return xhr;
        },

        instances: []
    };

    var rheaders = /^(.*?):[ \t]*([^\r\n]*)\r?$/mg; // IE leaves an \r character at EOL

    var rAppidXhr = function (xhr) {
        this.xhr = xhr;
        this.status = xhr.status;
        this.$nativeResponseHeaders = xhr.getAllResponseHeaders();
        this.responses = {};

        var xml = xhr.responseXML;

        // Construct response list
        if (xml && xml.documentElement) {
            this.responses.xml = xml;
        }
        this.responses.text = xhr.responseText;

        try {
            this.statusText = xhr.statusText;
        } catch (e) {
            this.statusText = "";
        }
    };

    rAppidXhr.prototype.getResponseHeader = function (key) {
        var match;
        if (!this.$responseHeaders) {
            this.$responseHeaders = {};
            while (( match = rheaders.exec(this.$nativeResponseHeaders) )) {
                this.$responseHeaders[match[1].toLowerCase()] = match[2];
            }
        }
        return this.$responseHeaders[key.toLowerCase()];
    };

    rAppid.ajaxSettings = {
        type: "GET",
        contentType: "application/x-www-form-urlencoded",
        async: true,
        xhr: function () {
            return new XMLHttpRequest();
        },
        headers: {
        },
        data: null
    };

    var ApplicationContext = function (requirejsContext, config) {
        this.$requirejsContext = requirejsContext;
        this.$config = config;
    };

    var interCommunicationBus;

    ApplicationContext.prototype.createApplicationInstance = function (window, callback) {

        var document,
            time = (new Date()).getTime(),
            self = this;

        // create instance
        var applicationFactory = this.$applicationFactory;

        if (window.document) {
            document = window.document;
        } else {
            document = window;
            window = null;
        }

        var stage = new Stage(this.$requirejsContext, this, document, window);

        this.$requirejsContext(["js/core/Application", "js/core/HeadManager", "js/core/History", "js/core/Injection", "js/core/InterCommunicationBus", "js/core/Bindable"], function (Application, HeadManager, History, Injection, InterCommunicationBus, Bindable) {

            interCommunicationBus = interCommunicationBus || new InterCommunicationBus();

            stage.$headManager = new HeadManager(document);
            stage.$history = new History();
            var injection = stage.$injection = new Injection(null, null, stage);

            stage.$environment = new Bindable();

            injection.addInstance(stage.$bus);
            injection.addInstance(stage.$history);
            injection.addInstance(stage.$headManager);
            injection.addInstance(stage.$externalInterface);
            injection.addInstance(interCommunicationBus);
            injection.addInstance("ENV", stage.$environment);

            var application = new applicationFactory(null, false, stage, null, null);

            if (application instanceof Application) {

                var environmentSetupComplete = function (err) {
                    if (!err) {
                        application.set('ENV', stage.$environment);

                        stage.$application = application;
                        stage._initialize("auto");

                        application._initialize("auto");

                        application.$creationTime = (new Date()).getTime() - time;

                        // return rAppid instance
                        if (callback) {
                            callback(null, stage, application);
                        }
                    } else {
                        callback && callback(err, stage, application);
                    }
                };

                if (application.supportEnvironments) {
                    Application.setupEnvironment(stage.$environment, application._getEnvironment(), application.applicationDefaultNamespace, environmentSetupComplete);
                } else {
                    environmentSetupComplete();
                }

            } else {
                var errMessage = "mainClass isn't an instance of js.core.Application";
                if (callback) {
                    callback(errMessage);
                } else {
                    throw(errMessage);
                }
            }
        });

    };

    ApplicationContext.prototype.getFqClassName = function (namespace, className, useRewriteMap) {
        if (useRewriteMap == undefined || useRewriteMap == null) {
            useRewriteMap = true;
        }

        if (namespace && className) {
            namespace = (this.$config.namespaceMap[namespace] || namespace).replace(/\./g, '/');
            var fqClassName = [namespace, className].join("/");
        } else {
            fqClassName = (namespace || className).replace(/\./g, '/');
        }

        if (underscore.indexOf(this.$config.xamlClasses, fqClassName) !== -1) {
            fqClassName = 'xaml!' + fqClassName;
        }

        if (useRewriteMap) {
            for (var i = 0; i < this.$config.rewriteMap.length; i++) {
                var entry = this.$config.rewriteMap[i];
                if (entry instanceof rAppid.rewriteMapEntry) {
                    if (entry.$from.test(fqClassName)) {
                        return fqClassName.replace(entry.$from, entry.$to);
                    }
                }
            }
        }

        return fqClassName;
    };

    ApplicationContext.prototype.createInstance = function (fqClassName, args, className) {
        args = args || [];

        var classDefinition;

        if (fqClassName instanceof Function) {
            classDefinition = fqClassName;
            fqClassName = classDefinition.prototype.constructor.name;
        } else {
            fqClassName = fqClassName.replace(/\./g, "/");
            classDefinition = this.$requirejsContext(fqClassName);
        }

        className = className || fqClassName;

        function construct(constructor, args) {
            function F() {
                return constructor.apply(this, args);
            }

            F.prototype = constructor.prototype;
            return new F();
        }

        var ret;
        try {
            ret = construct(classDefinition, args);
            ret.className = className;
        } catch (e) {
            console.warn(["Cannot create instance of '" + fqClassName + "'", e, args]);
            throw e;
        }

        return ret;
    };

    ApplicationContext.prototype.ajax = function (url, options, callback) {

        if (!(/^http.*$/.test(url)) && this.$config.applicationUrl) {
            url = this.$config.applicationUrl + '/' + url;
        }

        rAppid.ajax(url, options, callback);
    };

    rAppid.defaultNamespaceMap = defaultNamespaceMap;
    rAppid.defaultRewriteMap = defaultRewriteMap;
    rAppid.ApplicationContext = ApplicationContext;
    rAppid.Rewrite = Rewrite;

    exports.rAppid = rAppid;

}(typeof exports !== "undefined" ? exports : window,
    typeof requirejs !== "undefined" ? requirejs : require('requirejs'),
    typeof requirejs !== "undefined" ? define : require('requirejs').define,
    typeof window !== "undefined" ? window : exports,
    typeof window !== "undefined" ? window.XMLHttpRequest : require('xmlhttprequest').XMLHttpRequest));
<|endoftext|>


<commit_before>function add(a, b){
  if (b === undefined) {
    return c => add(a, c)
  }

  return a + b
}

function adjust(fn, index, arr){
  if (index === undefined) {
    return (indexHolder, arrHolder) => adjust(fn, indexHolder, arrHolder)
  } else if (arr === undefined) {
    return holder => adjust(fn, index, holder)
  }

  return arr.map((val, key) => {
    if (key === index) {
      return fn(arr[ index ])
    }

    return val
  })
}

function any(fn, arr){
  if (arr === undefined) {
    return holder => any(fn, holder)
  }

  let counter = 0
  while (counter < arr.length) {
    if (fn(arr[ counter ])) {
      return true
    }
    counter++
  }

  return false
}

function append (val, arr) {
  if (arr === undefined) {
    return holder => append(val, holder)
  }
  const clone = arr
  clone.push(val)

  return clone
}

function isFunction(value){

  return typeof value === "function"
}

function compose () {
  const funcs = arguments
  let length = funcs.length

  while (length--) {
    if (!isFunction(funcs[ length ])) {
      throw new TypeError
    }
  }

  return function () {
    let args = arguments
    let len = funcs.length

    while (len--) {
      args = [ funcs[ len ].apply(this, args) ]
    }

    return args[ 0 ]
  }
}

function contains(val, arr) {
  if (arr === undefined) {
    return holder => contains(val, holder)
  }

  let index = -1
  let flag = false
  while (++index < arr.length && !flag) {
    if (equals(arr[ index ], val)) {
      flag = true
    }
  }

  return flag
}

function filter(fn, arr) {
  if (arr === undefined) {
    return holder => filter(fn, holder)
  }

  let index = -1
  let resIndex = 0
  const len =  arr.length
  const willReturn = []

  while (++index < len) {
    const value = arr[ index ]
    if (fn(value)) {
      willReturn[ resIndex++ ] = value
    }
  }

  return willReturn
}

function find(fn, arr){
  if (arr === undefined) {
    return holder => find(fn, holder)
  }

  return arr.find(fn)
}

function findIndex(fn, arr){
  if (arr === undefined) {
    return holder => findIndex(fn, holder)
  }

  const length = arr.length
  let index = -1

  while (++index < length) {
    if (fn(arr[ index ])) {
      return index
    }
  }

  return -1
}

function flatten(arr, willReturn){
  willReturn = willReturn === undefined ?
    [] :
    willReturn

  for (let i = 0; i < arr.length; i++) {
    if (Array.isArray(arr[ i ])) {
      flatten(arr[ i ], willReturn)
    } else {
      willReturn.push(arr[ i ])
    }
  }

  return willReturn
}

function drop(dropNumber, a){
  if (a === undefined) {
    return holder => drop(dropNumber, holder)
  }

  return a.slice(dropNumber)
}

function dropLast(dropNumber, a){
  if (a === undefined) {
    return holder => dropLast(dropNumber, holder)
  }

  return a.slice(0, -dropNumber)
}

function equals(a, b) {
  if (b === undefined) {

    return holder => equals(a, holder)
  } else if (a === b) {

    return a !== 0 || 1 / a === 1 / b
  }
  const aType = type(a)
  if (aType !== type(b)) {
    return false
  }

  if (aType === "Array") {
    const aClone = a
    const bClone = b

    return aClone.sort().toString() === bClone.sort().toString()
  }

  if (aType === "Object") {
    const aKeys = Object.keys(a)
    if (aKeys.length === Object.keys(b).length) {
      if (aKeys.length === 0) {
        return true
      }
      let flag = true
      aKeys.map(val => {
        if (flag) {
          const aValType = type(a[ val ])
          const bValType = type(b[ val ])
          if (aValType === bValType) {
            if (aValType === "Object") {
              if (Object.keys(a[ val ]).length === Object.keys(b[ val ]).length) {
                if (Object.keys(a[ val ]).length !== 0) {
                  if (!equals(a[ val ], b[ val ])) {
                    flag = false
                  }
                }
              } else {
                flag = false
              }
            } else if (!equals(a[ val ], b[ val ])) {
              flag = false
            }
          } else {
            flag = false
          }
        }
      })

      return flag
    }
  }

  return false
}

function head(a){
  if (typeof a === "string") {
    return a[ 0 ] || ""
  }

  return a[ 0 ]
}

function indexOf(question, arr) {
  if (arr === undefined) {
    return holder => indexOf(question, holder)
  }

  let index = -1
  const length = arr.length

  while (++index < length) {
    if (arr[ index ] === question) {
      return index
    }
  }

  return -1
}

function baseSlice(array, start, end) {
  let index = -1
  let length = array.length

  end = end > length ? length : end
  if (end < 0) {
    end += length
  }
  length = start > end ? 0 : end - start >>> 0
  start >>>= 0

  const result = Array(length)
  while (++index < length) {
    result[ index ] = array[ index + start ]
  }

  return result
}

function init(a){
  if (typeof a === "string") {
    return a.slice(0, -1)
  }

  return a.length ? baseSlice(a, 0, -1) : []
}

function join(glue, arr) {
  if (arr === undefined) {
    return holder => join(glue, holder)
  }

  return arr.join(glue)
}

function map(fn, arr) {
  if (arr === undefined) {
    return holder => map(fn, holder)
  }

  let index = -1
  const length = arr.length
  const willReturn = Array(length)

  while (++index < length) {
    willReturn[ index ] = fn(arr[ index ])
  }

  return willReturn
}

function last(a){
  if (typeof a === "string") {
    return a[ a.length - 1 ] || ""
  }

  return a[ a.length - 1 ]
}

function length(arr){

  return arr.length
}

function match(regex, str) {
  if (str === undefined) {
    return holder => match(regex, holder)
  }
  const willReturn = str.match(regex)

  return willReturn === null ?
    [] :
    willReturn
}

function merge(obj, newProps) {
  if (newProps === undefined) {
    return holder => merge(obj, holder)
  }

  return Object.assign({}, obj, newProps)
}

function omit(keys, obj){
  if (obj === undefined) {
    return holder => omit(keys, holder)
  }

  const willReturn = {}
  for (key in obj) {
    if (!keys.includes(key)) {
      willReturn[ key ] = obj[ key ]
    }
  }

  return willReturn
}

function path(pathArr, obj) {
  if (obj === undefined) {
    return holder => path(pathArr, holder)
  }

  let holder = obj
  let counter = 0
  while (counter < pathArr.length) {
    if (holder === null) {
      return undefined
    }
    holder = holder[ pathArr[ counter ] ]
    counter++
  }

  return holder
}

function pick(keys, obj) {
  if (obj === undefined) {
    return holder => pick(keys, holder)
  }
  const willReturn = {}
  let counter = 0
  while (counter < keys.length) {
    if (keys[ counter ] in obj) {
      willReturn[ keys[ counter ] ] = obj[ keys[ counter ] ]
    }
    counter++
  }

  return willReturn
}

function prepend(val, arr) {
  if (arr === undefined) {
    return holder => prepend(val, holder)
  }

  const clone = arr
  clone.unshift(val)

  return clone
}

function prop(key, obj) {
  if (obj === undefined) {
    return holder => prop(key, holder)
  }

  return obj[ key ]
}

function propEq(key, val, obj) {
  if (val === undefined) {
    return (valHolder, objHolder) => propEq(key, valHolder, objHolder)
  } else if (obj === undefined) {
    return holder => propEq(key, val, holder)
  }

  return obj[ key ] === val
}

function range(start, end) {
  const willReturn = []
  for (let i = start; i < end; i++) {
    willReturn.push(i)
  }

  return willReturn
}

function repeat(a, num) {
  if (num === undefined) {
    return holder => repeat(a, holder)
  }
  const willReturn = Array(num)

  return willReturn.fill(a)
}

function replace(regex, replacer, str) {
  if (replacer === undefined) {
    return (replacerHolder, strHolder) => replace(regex, replacerHolder, strHolder)
  } else if (str === undefined) {
    return holder => replace(regex, replacer, holder)
  }

  return str.replace(regex, replacer)
}

function subtract(a, b) {
  if (b === undefined) {
    return holder => subtract(a, holder)
  }

  return a - b
}

function sort(fn, arr) {
  if (arr === undefined) {
    return holder => sort(fn, holder)
  }
  const arrClone = Array.from(arr)

  return arrClone.sort(fn)
}

function sortBy(fn, arr) {
  if (arr === undefined) {
    return holder => sortBy(fn, holder)
  }
  const arrClone = Array.from(arr)

  return arrClone.sort((a, b) => {
    const fnA = fn(a)
    const fnB = fn(b)
    return fnA < fnB ?
      -1 :
      fnA > fnB ?
        1 :
        0
  })
}

function split(glue, str) {
  if (str === undefined) {
    return holder => split(glue, holder)
  }

  return str.split(glue)
}

function splitEvery(num, a) {
  if (a === undefined) {
    return holder => splitEvery(num, holder)
  }
  num = num > 1 ?
    num :
    1

  const willReturn = []
  let counter = 0
  while (counter < a.length) {
    willReturn.push(a.slice(counter, counter += num))
  }

  return willReturn
}

function tail(arr){

  return drop(1, arr)
}

function take(takeNumber, a) {
  if (a === undefined) {
    return holder => take(takeNumber, holder)
  } else if (typeof a === "string") {
    return a.slice(0, takeNumber)
  }

  return baseSlice(a, 0, takeNumber)
}

function takeLast(takeNumber, a) {
  if (a === undefined) {
    return holder => takeLast(takeNumber, holder)
  }
  const len = a.length
  takeNumber = takeNumber > len ?
    len :
    takeNumber

  if (typeof a === "string") {
    return a.slice(len - takeNumber)
  }
  takeNumber = len - takeNumber

  return baseSlice(a, takeNumber, len)
}

function toLower(str){

  return str.toLowerCase()
}

function toUpper(str){

  return str.toUpperCase()
}

function test(regex, str){
  if (str === undefined) {
    return holder => test(regex, holder)
  }

  return str.search(regex) === -1 ?
    false :
    true
}

function trim(str){

  return str.trim()
}

function type(a){
  if (a === null) {

    return "Null"
  } else if (Array.isArray(a)) {

    return "Array"
  } else if (typeof a === "boolean") {

    return "Boolean"
  } else if (typeof a === "number") {

    return "Number"
  } else if (typeof a === "string") {

    return "String"
  } else if (a === undefined) {

    return "Undefined"
  } else if (a instanceof RegExp) {

    return "RegExp"
  }

  const asStr = a.toString()
  if(asStr.startsWith("async")){
    return "Async"
  }else if(asStr.includes("function")||asStr.includes("=>")){
    return "Function"
  }

  return "Object"
}

function values(obj){
  const willReturn = []
  for (key in obj) {
    willReturn.push(obj[ key ])
  }

  return willReturn
}

function uniq(arr){
  let index = -1
  const willReturn = []
  while (++index < arr.length) {
    const value = arr[ index ]
    if (!contains(value, willReturn)) {
      willReturn.push(value)
    }
  }

  return willReturn
}

function update(index, newValue, arr){
  if (newValue === undefined) {
    return (newValueHolder, arrHolder) => update(index, newValueHolder, arrHolder)
  } else if (arr === undefined) {
    return holder => update(index, newValue, holder)
  }
  const arrClone = Array.from(arr)

  return arrClone.fill(newValue, index, index + 1)
}

exports.add = add
exports.adjust = adjust
exports.any = any
exports.append = append
exports.compose = compose
exports.contains = contains
exports.drop = drop
exports.dropLast = dropLast
exports.equals = equals
exports.filter = filter
exports.find = find
exports.findIndex = findIndex
exports.flatten = flatten
exports.head = head
exports.indexOf = indexOf
exports.init = init
exports.join = join
exports.last = last
exports.length = length
exports.map = map
exports.match = match
exports.merge = merge
exports.omit = omit
exports.path = path
exports.pick = pick
exports.prepend = prepend
exports.prop = prop
exports.propEq = propEq
exports.range = range
exports.repeat = repeat
exports.replace = replace
exports.sort = sort
exports.sortBy = sortBy
exports.split = split
exports.splitEvery = splitEvery
exports.subtract = subtract
exports.tail = tail
exports.take = take
exports.takeLast = takeLast
exports.test = test
exports.toLower = toLower
exports.toUpper = toUpper
exports.trim = trim
exports.type = type
exports.uniq = uniq
exports.update = update
exports.values = values
<commit_msg>initial<commit_after>function add(a, b){
  if (b === undefined) {
    return c => add(a, c)
  }

  return a + b
}

function adjust(fn, index, arr){
  if (index === undefined) {
    return (indexHolder, arrHolder) => adjust(fn, indexHolder, arrHolder)
  } else if (arr === undefined) {
    return holder => adjust(fn, index, holder)
  }

  return arr.map((val, key) => {
    if (key === index) {
      return fn(arr[ index ])
    }

    return val
  })
}

function any(fn, arr){
  if (arr === undefined) {
    return holder => any(fn, holder)
  }

  let counter = 0
  while (counter < arr.length) {
    if (fn(arr[ counter ])) {
      return true
    }
    counter++
  }

  return false
}

function append (val, arr) {
  if (arr === undefined) {
    return holder => append(val, holder)
  }
  const clone = arr
  clone.push(val)

  return clone
}

function isFunction(value){

  return typeof value === "function"
}

function compose () {
  const funcs = arguments
  let length = funcs.length

  while (length--) {
    if (!isFunction(funcs[ length ])) {
      throw new TypeError
    }
  }

  return function () {
    let args = arguments
    let len = funcs.length

    while (len--) {
      args = [ funcs[ len ].apply(this, args) ]
    }

    return args[ 0 ]
  }
}

function contains(val, arr) {
  if (arr === undefined) {
    return holder => contains(val, holder)
  }

  let index = -1
  let flag = false
  while (++index < arr.length && !flag) {
    if (equals(arr[ index ], val)) {
      flag = true
    }
  }

  return flag
}

function filter(fn, arr) {
  if (arr === undefined) {
    return holder => filter(fn, holder)
  }

  let index = -1
  let resIndex = 0
  const len =  arr.length
  const willReturn = []

  while (++index < len) {
    const value = arr[ index ]
    if (fn(value)) {
      willReturn[ resIndex++ ] = value
    }
  }

  return willReturn
}

function find(fn, arr){
  if (arr === undefined) {
    return holder => find(fn, holder)
  }

  return arr.find(fn)
}

function findIndex(fn, arr){
  if (arr === undefined) {
    return holder => findIndex(fn, holder)
  }

  const length = arr.length
  let index = -1

  while (++index < length) {
    if (fn(arr[ index ])) {
      return index
    }
  }

  return -1
}

function flatten(arr, willReturn){
  willReturn = willReturn === undefined ?
    [] :
    willReturn

  for (let i = 0; i < arr.length; i++) {
    if (Array.isArray(arr[ i ])) {
      flatten(arr[ i ], willReturn)
    } else {
      willReturn.push(arr[ i ])
    }
  }

  return willReturn
}

function drop(dropNumber, a){
  if (a === undefined) {
    return holder => drop(dropNumber, holder)
  }

  return a.slice(dropNumber)
}

function dropLast(dropNumber, a){
  if (a === undefined) {
    return holder => dropLast(dropNumber, holder)
  }

  return a.slice(0, -dropNumber)
}

function equals(a, b) {
  if (b === undefined) {

    return holder => equals(a, holder)
  } else if (a === b) {

    return a !== 0 || 1 / a === 1 / b
  }
  const aType = type(a)
  if (aType !== type(b)) {
    return false
  }

  if (aType === "Array") {
    const aClone = a
    const bClone = b

    return aClone.sort().toString() === bClone.sort().toString()
  }

  if (aType === "Object") {
    const aKeys = Object.keys(a)
    if (aKeys.length === Object.keys(b).length) {
      if (aKeys.length === 0) {
        return true
      }
      let flag = true
      aKeys.map(val => {
        if (flag) {
          const aValType = type(a[ val ])
          const bValType = type(b[ val ])
          if (aValType === bValType) {
            if (aValType === "Object") {
              if (Object.keys(a[ val ]).length === Object.keys(b[ val ]).length) {
                if (Object.keys(a[ val ]).length !== 0) {
                  if (!equals(a[ val ], b[ val ])) {
                    flag = false
                  }
                }
              } else {
                flag = false
              }
            } else if (!equals(a[ val ], b[ val ])) {
              flag = false
            }
          } else {
            flag = false
          }
        }
      })

      return flag
    }
  }

  return false
}

function head(a){
  if (typeof a === "string") {
    return a[ 0 ] || ""
  }

  return a[ 0 ]
}

function indexOf(question, arr) {
  if (arr === undefined) {
    return holder => indexOf(question, holder)
  }

  let index = -1
  const length = arr.length

  while (++index < length) {
    if (arr[ index ] === question) {
      return index
    }
  }

  return -1
}

function baseSlice(array, start, end) {
  let index = -1
  let length = array.length

  end = end > length ? length : end
  if (end < 0) {
    end += length
  }
  length = start > end ? 0 : end - start >>> 0
  start >>>= 0

  const result = Array(length)
  while (++index < length) {
    result[ index ] = array[ index + start ]
  }

  return result
}

function init(a){
  if (typeof a === "string") {
    return a.slice(0, -1)
  }

  return a.length ? baseSlice(a, 0, -1) : []
}

function join(glue, arr) {
  if (arr === undefined) {
    return holder => join(glue, holder)
  }

  return arr.join(glue)
}

function map(fn, arr) {
  if (arr === undefined) {
    return holder => map(fn, holder)
  }

  let index = -1
  const length = arr.length
  const willReturn = Array(length)

  while (++index < length) {
    willReturn[ index ] = fn(arr[ index ])
  }

  return willReturn
}

function last(a){
  if (typeof a === "string") {
    return a[ a.length - 1 ] || ""
  }

  return a[ a.length - 1 ]
}

function length(arr){

  return arr.length
}

function match(regex, str) {
  if (str === undefined) {
    return holder => match(regex, holder)
  }
  const willReturn = str.match(regex)

  return willReturn === null ?
    [] :
    willReturn
}

function merge(obj, newProps) {
  if (newProps === undefined) {
    return holder => merge(obj, holder)
  }

  return Object.assign({}, obj, newProps)
}

function omit(keys, obj){
  if (obj === undefined) {
    return holder => omit(keys, holder)
  }

  const willReturn = {}
  for (key in obj) {
    if (!keys.includes(key)) {
      willReturn[ key ] = obj[ key ]
    }
  }

  return willReturn
}

function path(pathArr, obj) {
  if (obj === undefined) {
    return holder => path(pathArr, holder)
  }

  let holder = obj
  let counter = 0
  while (counter < pathArr.length) {
    if (holder === null) {
      return undefined
    }
    holder = holder[ pathArr[ counter ] ]
    counter++
  }

  return holder
}

function pick(keys, obj) {
  if (obj === undefined) {
    return holder => pick(keys, holder)
  }
  const willReturn = {}
  let counter = 0
  while (counter < keys.length) {
    if (keys[ counter ] in obj) {
      willReturn[ keys[ counter ] ] = obj[ keys[ counter ] ]
    }
    counter++
  }

  return willReturn
}

function prepend(val, arr) {
  if (arr === undefined) {
    return holder => prepend(val, holder)
  }

  const clone = arr
  clone.unshift(val)

  return clone
}

function prop(key, obj) {
  if (obj === undefined) {
    return holder => prop(key, holder)
  }

  return obj[ key ]
}

function propEq(key, val, obj) {
  if (val === undefined) {
    return (valHolder, objHolder) => propEq(key, valHolder, objHolder)
  } else if (obj === undefined) {
    return holder => propEq(key, val, holder)
  }

  return obj[ key ] === val
}

function range(start, end) {
  const willReturn = []
  for (let i = start; i < end; i++) {
    willReturn.push(i)
  }

  return willReturn
}

function repeat(a, num) {
  if (num === undefined) {
    return holder => repeat(a, holder)
  }
  const willReturn = Array(num)

  return willReturn.fill(a)
}

function replace(regex, replacer, str) {
  if (replacer === undefined) {
    return (replacerHolder, strHolder) => replace(regex, replacerHolder, strHolder)
  } else if (str === undefined) {
    return holder => replace(regex, replacer, holder)
  }

  return str.replace(regex, replacer)
}

function subtract(a, b) {
  if (b === undefined) {
    return holder => subtract(a, holder)
  }

  return a - b
}

function sort(fn, arr) {
  if (arr === undefined) {
    return holder => sort(fn, holder)
  }
  const arrClone = Array.from(arr)

  return arrClone.sort(fn)
}

function sortBy(fn, arr) {
  if (arr === undefined) {
    return holder => sortBy(fn, holder)
  }
  const arrClone = Array.from(arr)

  return arrClone.sort((a, b) => {
    const fnA = fn(a)
    const fnB = fn(b)
    return fnA < fnB ?
      -1 :
      fnA > fnB ?
        1 :
        0
  })
}

function split(glue, str) {
  if (str === undefined) {
    return holder => split(glue, holder)
  }

  return str.split(glue)
}

function splitEvery(num, a) {
  if (a === undefined) {
    return holder => splitEvery(num, holder)
  }
  num = num > 1 ?
    num :
    1

  const willReturn = []
  let counter = 0
  while (counter < a.length) {
    willReturn.push(a.slice(counter, counter += num))
  }

  return willReturn
}

function tail(arr){

  return drop(1, arr)
}

function take(takeNumber, a) {
  if (a === undefined) {
    return holder => take(takeNumber, holder)
  } else if (typeof a === "string") {
    return a.slice(0, takeNumber)
  }

  return baseSlice(a, 0, takeNumber)
}

function takeLast(takeNumber, a) {
  if (a === undefined) {
    return holder => takeLast(takeNumber, holder)
  }
  const len = a.length
  takeNumber = takeNumber > len ?
    len :
    takeNumber

  if (typeof a === "string") {
    return a.slice(len - takeNumber)
  }
  takeNumber = len - takeNumber

  return baseSlice(a, takeNumber, len)
}

function toLower(str){

  return str.toLowerCase()
}

function toUpper(str){

  return str.toUpperCase()
}

function test(regex, str){
  if (str === undefined) {
    return holder => test(regex, holder)
  }

  return str.search(regex) === -1 ?
    false :
    true
}

function trim(str){

  return str.trim()
}

function type(a){
  if (a === null) {

    return "Null"
  } else if (Array.isArray(a)) {

    return "Array"
  } else if (typeof a === "boolean") {

    return "Boolean"
  } else if (typeof a === "number") {

    return "Number"
  } else if (typeof a === "string") {

    return "String"
  } else if (a === undefined) {

    return "Undefined"
  } else if (a instanceof RegExp) {

    return "RegExp"
  }

  const asStr = a.toString()
  if(asStr.startsWith("async")){
    return "Async"
  }else if(asStr.includes("function")||asStr.includes("=>")){
    return "Function"
  }

  return "Object"
}

function values(obj){
  const willReturn = []
  for (key in obj) {
    willReturn.push(obj[ key ])
  }

  return willReturn
}

function uniq(arr){
  let index = -1
  const willReturn = []
  while (++index < arr.length) {
    const value = arr[ index ]
    if (!contains(value, willReturn)) {
      willReturn.push(value)
    }
  }

  return willReturn
}

function update(index, newValue, arr){
  if (newValue === undefined) {
    return (newValueHolder, arrHolder) => update(index, newValueHolder, arrHolder)
  } else if (arr === undefined) {
    return holder => update(index, newValue, holder)
  }
  const arrClone = Array.from(arr)

  return arrClone.fill(newValue, index, index + 1)
}

function flip (fnToCurry){
    return (...curryArguments)=>{
      const len = fnToCurry.length
      if(curryArguments[1]===undefined){
        if(len > 1){
          return (...futureArguments) => fnToCurry(...futureArguments.reverse(),curryArguments[0])
        }
        return fnToCurry(...curryArguments.reverse())
      }else if(curryArguments[2]===undefined && len === 3){
        return futureArgument => fnToCurry(futureArgument,...curryArguments.reverse())
      }

      return fnToCurry(...curryArguments.reverse())
    }
}

function curry(fnToCurry){
  return (...curryArguments)=>{
    const len = fnToCurry.length
    if(curryArguments[1]===undefined){
      if(len > 1){
        return (...futureArguments) => fnToCurry(curryArguments[0],...futureArguments)
      }
      return fnToCurry(...curryArguments)
    }else if(curryArguments[2]===undefined && len === 3){
      return (futureArgument) => fnToCurry(...curryArguments,futureArgument)
    }

    return fnToCurry(...curryArguments)
  }
}

exports.add = add
exports.adjust = adjust
exports.any = any
exports.append = append
exports.compose = compose
exports.contains = contains
exports.drop = drop
exports.dropLast = dropLast
exports.equals = equals
exports.filter = filter
exports.find = find
exports.findIndex = findIndex
exports.flatten = flatten
exports.head = head
exports.indexOf = indexOf
exports.init = init
exports.join = join
exports.last = last
exports.length = length
exports.map = map
exports.match = match
exports.merge = merge
exports.omit = omit
exports.path = path
exports.pick = pick
exports.prepend = prepend
exports.prop = prop
exports.propEq = propEq
exports.range = range
exports.repeat = repeat
exports.replace = replace
exports.sort = sort
exports.sortBy = sortBy
exports.split = split
exports.splitEvery = splitEvery
exports.subtract = subtract
exports.tail = tail
exports.take = take
exports.takeLast = takeLast
exports.test = test
exports.toLower = toLower
exports.toUpper = toUpper
exports.trim = trim
exports.type = type
exports.uniq = uniq
exports.update = update
exports.values = values
<|endoftext|>


<commit_before>"use strict";
var EventEmitter = require('events').EventEmitter;

var uuid = require('node-uuid');
var iter = require('super-iter');
var forEach = iter.forEach;
var filter = iter.filter;
var chain = iter.chain;

var func = require('super-func');
var partial = func.partial;
var lateBind = func.lateBind;
var identity = func.identity;

var is = require('super-is');
var enforce = is.enforce;
var typeOf = is.typeOf;

/**
  @description  loops over all the enumerable properties
                and updates their values from data
  @param        {Object} object
  @param        {Object} data
  @param        {Array} e
*/
function updateProperties (object, data, e) {

  object.id = data.id || uuid.v4();

  forEach(object, function (property, name) {

    if (data.hasOwnProperty(name)) {

      try {
        object[name] = data[name];
      }
      catch (err) {
        e.push(err);
      }
    }

  });

}

/**
  @description  create has one child entities
  @param        {Object} model
  @param        {Object} hasOne
*/
function updateHasOne (object, data, e) {

  if (object.hasOne) {

    forEach(object.hasOne, function(Relation, name) {

      if (data.hasOwnProperty(name)) {

        object[name] = new Relation(data[name], e);
      }

    });
  }
}

/**
  @description  generic setter - binds to internal __data__ structure
  @param        {String} prop
  @param        {Function} set
*/
function set (prop, set, type, value) {

  if (type) {
    enforce(type, value);
  }

  var data = set.call(this, value);
  this.__data__[prop] = data;

  this.emit(prop, {
    object: this,
    value: data
  });
}

/**
  @description  generic getter - binds to internal __data__ structure
  @param        {String} prop
*/
function get (prop) {
  return this.__data__[prop];
}

function serialise (object, recurse) {

  var serialised = filter(object, partial(identity, true));

  if (recurse) {

    forEach(object.hasOne, function (relation, name) {

      serialised[name] = serialise(object[name], recurse);
    });
  }
  return serialised;

}

module.exports = function define (name, definition) {

  var def = Object.create(null);

  //  set up has one relationships
  if (definition.hasOne) {

    def.hasOne = {
      value: {}
    };

    forEach(definition.hasOne, function (Relation, prop) {

      def.hasOne.value[prop] = Relation;

      def[prop] = {
        set: lateBind(set, prop, identity, null),
        get: lateBind(get, prop)
      }

    });
  }

  if (definition.properties) {

    //  late bind the generic getters and setters
    forEach(chain(definition.properties), function (descriptor, prop) {

      if (typeOf('undefined', descriptor.type) && !typeOf('function', descriptor.set)) {
        throw new TypeError('Object (' + name + ') property definition (' + prop + ') requires either a setter or type');
      }

      def[prop] = {
        enumerable: !! descriptor.enumerable,
        set: lateBind(set, prop, descriptor.set || identity, descriptor.type || null),
        get: lateBind(get, prop)
      };

    });
  }

  var Constructor = function (data, e) {

    Object.defineProperties(this, def);
    Object.defineProperties(this, {
      id: {
        value: undefined,
        writable: true
      },
      __data__: {
        value: Object.create(null)
      },
      _events: {
        value: Object.create(null)
      },
      _maxListeners: {
        value: Object.create(null)
      },
      domain: {
        value: null
      }
    });

    EventEmitter.call(this);

    var throwErrors = false;

    data = data || {};

    if (!e) {

      throwErrors = true;
      e = [];
    }

    updateProperties(this, data, e);
    updateHasOne(this, data, e);
    // updateHasMany(this, data, e);

    if (throwErrors && e.length > 0) {
      throw e;
    }

  }

  Constructor.prototype = Object.create(EventEmitter.prototype, {
    constructor: {
      value: Constructor
    },
    name: {
      value: name
    },
    serialise: {
      value: function (recurse) {
        return serialise(this, recurse);
      }
    }
  });

  Constructor.propertyDefinitions = definition;

  return Constructor;

}
<commit_msg>fixed a couple of issues<commit_after>"use strict";
var EventEmitter = require('events').EventEmitter;

var uuid = require('node-uuid');
var iter = require('super-iter');
var forEach = iter.forEach;
var filter = iter.filter;
var chain = iter.chain;

var func = require('super-func');
var partial = func.partial;
var lateBind = func.lateBind;
var identity = func.identity;

var is = require('super-is');
var enforce = is.enforce;
var typeOf = is.typeOf;

function updateDefaultValues (object, def) {

  forEach(def, function (descriptor, prop) {
    if (descriptor.hasOwnProperty('defaultValue')) {
      object[prop] = descriptor.defaultValue;
    }
  });
}

/**
  @description  loops over all the enumerable properties
                and updates their values from data
  @param        {Object} object
  @param        {Object} data
  @param        {Array} e
*/
function updateProperties (object, data, e) {

  object.id = data.id || uuid.v4();

  forEach(object, function (property, name) {

    if (data.hasOwnProperty(name)) {

      try {
        object[name] = data[name];
      }
      catch (err) {
        e.push(err);
      }
    }

  });

}

/**
  @description  create has one child entities
  @param        {Object} model
  @param        {Object} hasOne
*/
function updateHasOne (object, data, e) {

  if (object.hasOne) {

    forEach(object.hasOne, function(Relation, name) {

      if (data.hasOwnProperty(name)) {

        object[name] = new Relation(data[name], e);
      }

    });
  }
}

/**
  @description  generic setter - binds to internal __data__ structure
  @param        {String} prop
  @param        {Function} set
*/
function set (prop, set, type, value) {

  if (type) {
    enforce(type, value);
  }

  var data = set.call(this, value);
  this.__data__[prop] = data;

  this.emit(prop, {
    object: this,
    value: data
  });
}

/**
  @description  generic getter - binds to internal __data__ structure
  @param        {String} prop
*/
function get (prop) {
  return this.__data__[prop];
}

function serialise (object, recurse) {

  var serialised = filter(object, partial(identity, true));

  if (recurse) {

    forEach(object.hasOne, function (relation, name) {

      serialised[name] = serialise(object[name], recurse);
    });
  }
  return serialised;

}

module.exports = function define (name, definition) {

  var def = Object.create(null);

  //  set up has one relationships
  if (definition.hasOne) {

    def.hasOne = {
      value: {}
    };

    forEach(definition.hasOne, function (Relation, prop) {

      def.hasOne.value[prop] = Relation;

      def[prop] = {
        set: lateBind(set, prop, identity, null),
        get: lateBind(get, prop)
      }

    });
  }

  if (definition.properties) {

    //  late bind the generic getters and setters
    forEach(chain(definition.properties), function (descriptor, prop) {

      if (typeOf('undefined', descriptor.type) && !typeOf('function', descriptor.set)) {
        throw new TypeError('Object (' + name + ') property definition (' + prop + ') requires either a setter or type');
      }

      def[prop] = {
        enumerable: !! descriptor.enumerable,
        set: lateBind(set, prop, descriptor.set || identity, descriptor.type || null),
        get: lateBind(get, prop)
      };

      if (descriptor.hasOwnProperty('value')) {
        def[prop].defaultValue = descriptor.value;
      }

    });
  }

  var Constructor = function (data, e) {

    Object.defineProperties(this, {
      id: {
        value: undefined,
        writable: true,
        configurable: true
      },
      __data__: {
        value: Object.create(null)
      },
      _events: {
        value: Object.create(null)
      },
      _maxListeners: {
        value: Object.create(null)
      },
      domain: {
        value: null
      }
    });
    Object.defineProperties(this, def);

    updateDefaultValues(this, def);

    EventEmitter.call(this);

    var throwErrors = false;

    data = data || {};

    if (!e) {

      throwErrors = true;
      e = [];
    }

    updateProperties(this, data, e);
    updateHasOne(this, data, e);
    // updateHasMany(this, data, e);

    if (throwErrors && e.length > 0) {
      throw e;
    }

  }

  Constructor.prototype = Object.create(EventEmitter.prototype, {
    constructor: {
      value: Constructor
    },
    name: {
      value: name
    },
    serialise: {
      value: function (recurse) {
        return serialise(this, recurse);
      }
    }
  });

  Constructor.propertyDefinitions = definition;

  return Constructor;

}
<|endoftext|>


<commit_before>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
const htmlentities = require('htmlentities')
const jsesc = require('jsesc')
const utils = require('../utils')

class common extends utils {
  /**
   * Escape and quote a string
   * @param s - String to be quoted
   * @param {boolean} html - Identifies whether the string must be HTML safe
   * @returns {*}
   */
  static quote (s, html = false) {
    const options = {
      minimal: true,
      isScriptContext: html
    }

    if (typeof s === 'string') {
      return `'${jsesc(s, options)}'`
    } else {
      return jsesc(s, options)
    }
  }

  /**
   * Remove quotes and escape sequence from string
   * @param {string} s
   * @returns {string}
   */
  static unquote (s) {
    return s.replace(/\\'/g, '\'')
      .replace(/\\"/g, '"')
      .replace(/\\0/g, '\0')
      .replace(/\\\\/g, '\\')
      .replace(/(^['|"])(.*)\1$/gm, '$2')
  }

  /**
   * Unicode safe b64 encoding
   * https://developer.mozilla.org/en-US/docs/Web/API/WindowBase64/Base64_encoding_and_decoding#The_Unicode_Problem
   * @param {string} str
   * @returns {*}
   */
  static b64encode (str) {
    if (process.browser) {
      return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g,
        function toSolidBytes (match, p1) {
          // noinspection JSCheckFunctionSignatures
          return String.fromCharCode('0x' + p1)
        })
      )
    } else {
      return Buffer.from(str).toString('base64')
    }
  }

  /**
   * Unicode safe b64 decoding
   * https://developer.mozilla.org/en-US/docs/Web/API/WindowBase64/Base64_encoding_and_decoding#The_Unicode_Problem
   * @param {string} str
   * @returns {*}
   */
  static b64decode (str) {
    if (process.browser) {
      return decodeURIComponent(atob(str).split('').map(function (c) {
        return `%${('00' + c.charCodeAt(0).toString(16)).slice(-2)}`
      }).join(''))
    } else {
      return Buffer.from(str, 'base64').toString('ascii')
    }
  }

  /**
   * Escape special characters using HTML entities
   * @param {string} str
   * @returns {string}
   */
  static htmlEncode (str) {
    return htmlentities.encode(str)
  }

  /**
   * Remove HTML entities from string
   * @param {string} str
   * @returns {string}
   */
  static htmlDencode (str) {
    return htmlentities.decode(str)
  }

  /**
   * Remove duplicate items from a list
   * @param {Array} list
   * @returns {Array}
   */
  static uniqueList (list) {
    let tmp = {}
    let r = []
    for (let i = 0; i < list.length; i++) {
      tmp[list[i]] = list[i]
    }
    for (let i in tmp) {
      r.push(tmp[i])
    }
    return r
  }

  /**
   * Merge two objects recursively
   * @param {Object} obj1
   * @param {Object} obj2
   * @returns {*}
   */
  static mergeHash (obj1, obj2) {
    for (let p in obj2) {
      try {
        if (obj2[p].constructor === Object) {
          obj1[p] = utils.common.mergeHash(obj1[p], obj2[p])
        } else {
          obj1[p] = obj2[p]
        }
      } catch (e) {
        obj1[p] = obj2[p]
      }
    }
    return obj1
  }

  /**
   * Template string beautifier
   * @param {Object} obj
   * @returns {string}
   */
  static mockup (obj) {
    return obj.split('\n').map((ln) => ln.trim()).join('')
  }
}

module.exports = common
<commit_msg>Use format string<commit_after>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
const htmlentities = require('htmlentities')
const jsesc = require('jsesc')
const utils = require('../utils')

class common extends utils {
  /**
   * Escape and quote a string
   * @param s - String to be quoted
   * @param {boolean} html - Identifies whether the string must be HTML safe
   * @returns {*}
   */
  static quote (s, html = false) {
    const options = {
      minimal: true,
      isScriptContext: html
    }

    if (typeof s === 'string') {
      return `'${jsesc(s, options)}'`
    } else {
      return jsesc(s, options)
    }
  }

  /**
   * Remove quotes and escape sequence from string
   * @param {string} s
   * @returns {string}
   */
  static unquote (s) {
    return s.replace(/\\'/g, '\'')
      .replace(/\\"/g, '"')
      .replace(/\\0/g, '\0')
      .replace(/\\\\/g, '\\')
      .replace(/(^['|"])(.*)\1$/gm, '$2')
  }

  /**
   * Unicode safe b64 encoding
   * https://developer.mozilla.org/en-US/docs/Web/API/WindowBase64/Base64_encoding_and_decoding#The_Unicode_Problem
   * @param {string} str
   * @returns {*}
   */
  static b64encode (str) {
    if (process.browser) {
      return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g,
        function toSolidBytes (match, p1) {
          // noinspection JSCheckFunctionSignatures
          return String.fromCharCode(`0x${p1}`)
        })
      )
    } else {
      return Buffer.from(str).toString('base64')
    }
  }

  /**
   * Unicode safe b64 decoding
   * https://developer.mozilla.org/en-US/docs/Web/API/WindowBase64/Base64_encoding_and_decoding#The_Unicode_Problem
   * @param {string} str
   * @returns {*}
   */
  static b64decode (str) {
    if (process.browser) {
      return decodeURIComponent(atob(str).split('').map(function (c) {
        return `%${('00' + c.charCodeAt(0).toString(16)).slice(-2)}`
      }).join(''))
    } else {
      return Buffer.from(str, 'base64').toString('ascii')
    }
  }

  /**
   * Escape special characters using HTML entities
   * @param {string} str
   * @returns {string}
   */
  static htmlEncode (str) {
    return htmlentities.encode(str)
  }

  /**
   * Remove HTML entities from string
   * @param {string} str
   * @returns {string}
   */
  static htmlDencode (str) {
    return htmlentities.decode(str)
  }

  /**
   * Remove duplicate items from a list
   * @param {Array} list
   * @returns {Array}
   */
  static uniqueList (list) {
    let tmp = {}
    let r = []
    for (let i = 0; i < list.length; i++) {
      tmp[list[i]] = list[i]
    }
    for (let i in tmp) {
      r.push(tmp[i])
    }
    return r
  }

  /**
   * Merge two objects recursively
   * @param {Object} obj1
   * @param {Object} obj2
   * @returns {*}
   */
  static mergeHash (obj1, obj2) {
    for (let p in obj2) {
      try {
        if (obj2[p].constructor === Object) {
          obj1[p] = utils.common.mergeHash(obj1[p], obj2[p])
        } else {
          obj1[p] = obj2[p]
        }
      } catch (e) {
        obj1[p] = obj2[p]
      }
    }
    return obj1
  }

  /**
   * Template string beautifier
   * @param {Object} obj
   * @returns {string}
   */
  static mockup (obj) {
    return obj.split('\n').map((ln) => ln.trim()).join('')
  }
}

module.exports = common
<|endoftext|>


<commit_before>let fs = require('../core/fs.js');

let PluginManager = require('live-plugin-manager').PluginManager;

class Npm {

  constructor(options) {
    this.logger = options.logger;
  }

  getPackageVersion(packageName, version, callback) {
    let packageDirectory = './.embark/versions/' + packageName + '/' + version + '/';

    let manager = new PluginManager({pluginsPath: packageDirectory});

    if (fs.existsSync(packageDirectory + packageName)) {
      return callback(null, packageDirectory + packageName);
    }

    this.logger.info("downloading " + packageName + " " + version + "....");
    this.logger.info(__("downloading {{packageName}} {{version}}....", {packageName: packageName, version: version}));
    manager.install(packageName, version).then((result) => {
      callback(null , result.location);
    }).catch(callback);
  }
}

module.exports = Npm;
<commit_msg>Updates console to inform user of an ongoing package download.<commit_after>const fs = require('../core/fs.js');
const {PerformanceObserver, performance} = require('perf_hooks');
const PluginManager = require('live-plugin-manager').PluginManager;
require('colors');
const _ = require('underscore');

class Npm {

  constructor(options) {
    this.logger = options.logger;
  }

  getPackageVersion(packageName, version, callback) {
    let packageDirectory = './.embark/versions/' + packageName + '/' + version + '/';

    let manager = new PluginManager({pluginsPath: packageDirectory});

    if (fs.existsSync(packageDirectory + packageName)) {
      return callback(null, packageDirectory + packageName);
    }

    this.logger.info(__("Downloading {{packageName}} {{version}}...", {packageName: packageName, version: version}));

    const obsMeasure = new PerformanceObserver((items) => {
      let entry;
      let strDuration;

      // find any download ongoing measurements we've made
      entry = _.last(_.where(items.getEntries(), {name: downloadOngoing}));
      if(entry){
        // ongoing performance mark
        strDuration = __('Still downloading {{packageName}} {{version}}... ({{duration}}ms elapsed)', {packageName: packageName, version: version, duration: entry.duration});
      }
      else{
        // otherwise, find our download complete measurement
        entry = _.last(_.where(items.getEntries(), {name: downloadComplete}));

        if(entry){
          strDuration = __('Finished downloading {{packageName}} {{version}} in {{duration}}ms', {packageName: packageName, version: version, duration: entry.duration});
          performance.clearMarks();
        }
      }

      // log our measurement and make it red if it has taken too long
      if(entry && strDuration){
        if(entry.duration > 1000){
          strDuration = strDuration.red;
        }
        this.logger.info(strDuration);
      }

    });
    obsMeasure.observe({entryTypes: ['measure']});

    // define mark and measurement names
    let startMark = 'downloadStart' + packageName + version;
    let ongoingMark = 'downloadOngoingMark' + packageName + version;
    let downloadOngoing = 'downloadOngoing' + packageName + version;
    let endMark = 'downloadEnd' + packageName + version;
    let downloadComplete = 'downloadComplete' + packageName + version;

    // mark our start time
    performance.mark(startMark);

    // function that continually updates the console to show user that we're downloading a library
    let intOngoingDownload = setInterval(
      function(){
        performance.mark(ongoingMark);
        performance.measure(downloadOngoing, startMark, ongoingMark);
      }, 750);

    // do the package download/install
    manager.install(packageName, version).then((result) => {
      // stop updating console for ongoing download
      clearInterval(intOngoingDownload);
      performance.mark(endMark);
      performance.measure(downloadComplete, startMark, endMark);
      callback(null , result.location);
    }).catch(callback);
  }
}

module.exports = Npm;
<|endoftext|>


<commit_before>var exports = {};

exports.simplePrint = function(video) {
  return `**${video.title}**`;
};

exports.prettyPrint = function(video) {
  viewCount = video.view_count.replace(/\B(?=(\d{3})+(?!\d))/g, ',');
  return `**${video.title}** by **${video.author}** *(${viewCount} views)*`;
};

exports.prettyPrintWithUser = function(video) {
  return exports.prettyPrint(video) + `, added by <@${video.userId}>`;
};

module.exports = exports;
<commit_msg>Add a function that minifies a video so it can be saved for less<commit_after>var exports = {};

exports.simplePrint = function(video) {
  return `**${video.title}**`;
};

exports.prettyPrint = function(video) {
  viewCount = video.view_count.replace(/\B(?=(\d{3})+(?!\d))/g, ',');
  return `**${video.title}** by **${video.author}** *(${viewCount} views)*`;
};

exports.prettyPrintWithUser = function(video) {
  return exports.prettyPrint(video) + `, added by <@${video.userId}>`;
};

exports.simplify = function(video) {
  return {
    vid: video.vid,
    title: video.title,
    author: video.author,
    view_count: video.view_count,
  };
};

module.exports = exports;
<|endoftext|>


<commit_before>'use babel';

let VideoPlayerElement = require('./video-player-element');

module.exports = {
  config: {
    vlcPath: {
      title: 'Path to VLC',
      description: 'Set the path to VLC',
      type: 'string',
      default: '/Applications/VLC.app/Contents/MacOS/VLC'
    },
    encoding: {
      title: 'Encoding format',
      description: 'When you convert the video with VLC, this format is used',
      enum: ['ogg', 'webm'],
      default: 'ogg'
    }
  },
  activate: (state) => {
    atom.commands.add('atom-workspace', {
      "video-player:play": () => VideoPlayerElement.play(),
      "video-player:stop": () => VideoPlayerElement.stop(),
      "video-player:toggle-back-forth": () => VideoPlayerElement.toggleBackForth(),
      "video-player:toggle-control": () => VideoPlayerElement.toggleControl(),
      "video-player:reload-source": () => VideoPlayerElement.reloadSrc()
    });
  },
  deactivate: () => VideoPlayerElement.destroy(),
};
<commit_msg>missed type option<commit_after>'use babel';

let VideoPlayerElement = require('./video-player-element');

module.exports = {
  config: {
    vlcPath: {
      title: 'Path to VLC',
      description: 'Set the path to VLC',
      type: 'string',
      default: '/Applications/VLC.app/Contents/MacOS/VLC'
    },
    encoding: {
      title: 'Encoding format',
      description: 'When you convert the video with VLC, this format is used',
      type: 'string',
      enum: ['ogg', 'webm'],
      default: 'ogg'
    }
  },
  activate: (state) => {
    atom.commands.add('atom-workspace', {
      "video-player:play": () => VideoPlayerElement.play(),
      "video-player:stop": () => VideoPlayerElement.stop(),
      "video-player:toggle-back-forth": () => VideoPlayerElement.toggleBackForth(),
      "video-player:toggle-control": () => VideoPlayerElement.toggleControl(),
      "video-player:reload-source": () => VideoPlayerElement.reloadSrc()
    });
  },
  deactivate: () => VideoPlayerElement.destroy(),
};
<|endoftext|>


<commit_before>"use strict";

const apiai = require("../apiai");

const Promise = require("bluebird");

const fs = require("fs");

module.exports = function (opts) {

  return function (voice, options, callback) { //=> This is the actual apiai.voice("hiya.wav") function

    if (typeof(options) == "function" && !callback) {
      callback = options;
      options = {
        language: "en"
      };
    };

    if (!options) options = {
      language: "en"
    };

    let app = apiai(opts.token, options); //=> Attempt connection to api.ai with provided token

    let request = app.voiceRequest();

    if (typeof(voice) == "string") request.write(fs.readFileSync(voice));
    else request.write(voice);

    if (typeof(callback) != "function") return new Promise(function (resolve, reject) { //=> Cause promises are awesome

      request.on("response", resolve);

      request.on("error", reject);

    });
    else { //=> Just in case you prefer callbacks, within code, consistency is key

      request.on("response", function (response) {
        callback(null, response); //=> No error, callback with response
      });

      request.on("error", callback); //=> Callback with error.  Please do check if (err).

    }

    request.end();

  }
}
<commit_msg>Update voiceRequest.js<commit_after>"use strict";

const apiai = require("../apiai");

const Promise = require("bluebird");

const fs = require("fs");

module.exports = function (opts) {

  return function (voice, options, callback) { //=> This is the actual apiai.voice("hiya.wav") function

    if (typeof(options) == "function" && !callback) {
      callback = options;
      options = {
        sessionId: opts.session,
        language: "en"
      };
    };

    if (!options) options = {
      sessionId: opts.session,
      language: "en"
    };

    let app = apiai(opts.token, options); //=> Attempt connection to api.ai with provided token

    let request = app.voiceRequest();

    if (typeof(voice) == "string") request.write(fs.readFileSync(voice));
    else request.write(voice);

    if (typeof(callback) != "function") return new Promise(function (resolve, reject) { //=> Cause promises are awesome

      request.on("response", resolve);

      request.on("error", reject);

    });
    else { //=> Just in case you prefer callbacks, within code, consistency is key

      request.on("response", function (response) {
        callback(null, response); //=> No error, callback with response
      });

      request.on("error", callback); //=> Callback with error.  Please do check if (err).

    }

    request.end();

  }
}
<|endoftext|>