<commit_before>// external modules
var path = require('path');

// configs
var env = process.env.NODE_ENV || 'development';
var config = require(path.join(__dirname, '..', 'config.json'))[env];
var debug = process.env.DEBUG ? (process.env.DEBUG === 'true') : ((typeof config.debug === 'boolean') ? config.debug : (env === 'development'));

// url
var domain = process.env.DOMAIN || process.env.HMD_DOMAIN || config.domain || '';
var urlpath = process.env.URL_PATH || process.env.HMD_URL_PATH || config.urlpath || '';
var port = process.env.PORT || process.env.HMD_PORT || config.port || 3000;
var alloworigin = process.env.HMD_ALLOW_ORIGIN ? process.env.HMD_ALLOW_ORIGIN.split(',') : (config.alloworigin || ['localhost']);

var usessl = !!config.usessl;
var protocolusessl = (usessl === true && typeof process.env.HMD_PROTOCOL_USESSL === 'undefined' && typeof config.protocolusessl === 'undefined')
     ? true : (process.env.HMD_PROTOCOL_USESSL ? (process.env.HMD_PROTOCOL_USESSL === 'true') : !!config.protocolusessl);
var urladdport = process.env.HMD_URL_ADDPORT ? (process.env.HMD_URL_ADDPORT === 'true') : !!config.urladdport;

var usecdn = process.env.HMD_USECDN ? (process.env.HMD_USECDN === 'true') : ((typeof config.usecdn === 'boolean') ? config.usecdn : true);

// db
var db = config.db || {
    dialect: 'sqlite',
    storage: './db.hackmd.sqlite'
};

// ssl path
var sslkeypath = config.sslkeypath || '';
var sslcertpath = config.sslcertpath || '';
var sslcapath = config.sslcapath || '';
var dhparampath = config.dhparampath || '';

// other path
var tmppath = config.tmppath || './tmp';
var defaultnotepath = config.defaultnotepath || './public/default.md';
var docspath = config.docspath || './public/docs';
var indexpath = config.indexpath || './public/views/index.ejs';
var hackmdpath = config.hackmdpath || './public/views/hackmd.ejs';
var errorpath = config.errorpath || './public/views/error.ejs';
var prettypath = config.prettypath || './public/views/pretty.ejs';
var slidepath = config.slidepath || './public/views/slide.ejs';

// session
var sessionname = config.sessionname || 'connect.sid';
var sessionsecret = config.sessionsecret || 'secret';
var sessionlife = config.sessionlife || 14 * 24 * 60 * 60 * 1000; //14 days

// static files
var staticcachetime = config.staticcachetime || 1 * 24 * 60 * 60 * 1000; // 1 day

// socket.io
var heartbeatinterval = config.heartbeatinterval || 5000;
var heartbeattimeout = config.heartbeattimeout || 10000;

// document
var documentmaxlength = config.documentmaxlength || 100000;

// image upload setting, available options are imgur/s3/filesystem
var imageUploadType = config.imageUploadType || 'imgur';

var s3Keys = ['accessKeyId', 'secretAccessKey', 'region'];
config.s3 = config.s3 || {};
var s3 = s3Keys.reduce(function(prev, cur) {
    prev[cur] = config.s3[cur];
    return prev;
}, {});

var s3bucket = config.s3.bucket;

// auth
var facebook = (process.env.HMD_FACEBOOK_CLIENTID && process.env.HMD_FACEBOOK_CLIENTSECRET) ? {
    clientID: process.env.HMD_FACEBOOK_CLIENTID,
    clientSecret: process.env.HMD_FACEBOOK_CLIENTSECRET
} : config.facebook || false;
var twitter = (process.env.HMD_TWITTER_CONSUMERKEY && process.env.HMD_TWITTER_CONSUMERSECRET) ? {
    consumerKey: process.env.HMD_TWITTER_CONSUMERKEY,
    consumerSecret: process.env.HMD_TWITTER_CONSUMERSECRET
} : config.twitter || false;
var github = (process.env.HMD_GITHUB_CLIENTID && process.env.HMD_GITHUB_CLIENTSECRET) ? {
    clientID: process.env.HMD_GITHUB_CLIENTID,
    clientSecret: process.env.HMD_GITHUB_CLIENTSECRET
} : config.github || false;
var gitlab = (process.env.HMD_GITLAB_CLIENTID && process.env.HMD_GITLAB_CLIENTSECRET) ? {
    baseURL: process.env.HMD_GITLAB_BASEURL,
    clientID: process.env.HMD_GITLAB_CLIENTID,
    clientSecret: process.env.HMD_GITLAB_CLIENTSECRET
} : config.gitlab || false;
var dropbox = (process.env.HMD_DROPBOX_CLIENTID && process.env.HMD_DROPBOX_CLIENTSECRET) ? {
    clientID: process.env.HMD_DROPBOX_CLIENTID,
    clientSecret: process.env.HMD_DROPBOX_CLIENTSECRET
} : config.dropbox || false;
var google = (process.env.HMD_GOOGLE_CLIENTID && process.env.HMD_GOOGLE_CLIENTSECRET) ? {
    clientID: process.env.HMD_GOOGLE_CLIENTID,
    clientSecret: process.env.HMD_GOOGLE_CLIENTSECRET
} : config.google || false;
var imgur = process.env.HMD_IMGUR_CLIENTID || config.imgur || false;

function getserverurl() {
    var url = '';
    if (domain) {
        var protocol = protocolusessl ? 'https://' : 'http://';
        url = protocol + domain;
        if (urladdport && ((usessl && port != 443) || (!usessl && port != 80)))
            url += ':' + port;
    }
    if (urlpath)
        url += '/' + urlpath;
    return url;
}

var version = '0.4.5';
var minimumCompatibleVersion = '0.4.5';
var maintenance = true;
var cwd = path.join(__dirname, '..');

module.exports = {
    version: version,
    minimumCompatibleVersion: minimumCompatibleVersion,
    maintenance: maintenance,
    debug: debug,
    urlpath: urlpath,
    port: port,
    alloworigin: alloworigin,
    usessl: usessl,
    serverurl: getserverurl(),
    usecdn: usecdn,
    db: db,
    sslkeypath: path.join(cwd, sslkeypath),
    sslcertpath: path.join(cwd, sslcertpath),
    sslcapath: path.join(cwd, sslcapath),
    dhparampath: path.join(cwd, dhparampath),
    tmppath: path.join(cwd, tmppath),
    defaultnotepath: path.join(cwd, defaultnotepath),
    docspath: path.join(cwd, docspath),
    indexpath: path.join(cwd, indexpath),
    hackmdpath: path.join(cwd, hackmdpath),
    errorpath: path.join(cwd, errorpath),
    prettypath: path.join(cwd, prettypath),
    slidepath: path.join(cwd, slidepath),
    sessionname: sessionname,
    sessionsecret: sessionsecret,
    sessionlife: sessionlife,
    staticcachetime: staticcachetime,
    heartbeatinterval: heartbeatinterval,
    heartbeattimeout: heartbeattimeout,
    documentmaxlength: documentmaxlength,
    facebook: facebook,
    twitter: twitter,
    github: github,
    gitlab: gitlab,
    dropbox: dropbox,
    google: google,
    imgur: imgur,
    imageUploadType: imageUploadType,
    s3: s3,
    s3bucket: s3bucket
};
<commit_msg>Config s3 through env variables<commit_after>// external modules
var path = require('path');

// configs
var env = process.env.NODE_ENV || 'development';
var config = require(path.join(__dirname, '..', 'config.json'))[env];
var debug = process.env.DEBUG ? (process.env.DEBUG === 'true') : ((typeof config.debug === 'boolean') ? config.debug : (env === 'development'));

// url
var domain = process.env.DOMAIN || process.env.HMD_DOMAIN || config.domain || '';
var urlpath = process.env.URL_PATH || process.env.HMD_URL_PATH || config.urlpath || '';
var port = process.env.PORT || process.env.HMD_PORT || config.port || 3000;
var alloworigin = process.env.HMD_ALLOW_ORIGIN ? process.env.HMD_ALLOW_ORIGIN.split(',') : (config.alloworigin || ['localhost']);

var usessl = !!config.usessl;
var protocolusessl = (usessl === true && typeof process.env.HMD_PROTOCOL_USESSL === 'undefined' && typeof config.protocolusessl === 'undefined')
     ? true : (process.env.HMD_PROTOCOL_USESSL ? (process.env.HMD_PROTOCOL_USESSL === 'true') : !!config.protocolusessl);
var urladdport = process.env.HMD_URL_ADDPORT ? (process.env.HMD_URL_ADDPORT === 'true') : !!config.urladdport;

var usecdn = process.env.HMD_USECDN ? (process.env.HMD_USECDN === 'true') : ((typeof config.usecdn === 'boolean') ? config.usecdn : true);

// db
var db = config.db || {
    dialect: 'sqlite',
    storage: './db.hackmd.sqlite'
};

// ssl path
var sslkeypath = config.sslkeypath || '';
var sslcertpath = config.sslcertpath || '';
var sslcapath = config.sslcapath || '';
var dhparampath = config.dhparampath || '';

// other path
var tmppath = config.tmppath || './tmp';
var defaultnotepath = config.defaultnotepath || './public/default.md';
var docspath = config.docspath || './public/docs';
var indexpath = config.indexpath || './public/views/index.ejs';
var hackmdpath = config.hackmdpath || './public/views/hackmd.ejs';
var errorpath = config.errorpath || './public/views/error.ejs';
var prettypath = config.prettypath || './public/views/pretty.ejs';
var slidepath = config.slidepath || './public/views/slide.ejs';

// session
var sessionname = config.sessionname || 'connect.sid';
var sessionsecret = config.sessionsecret || 'secret';
var sessionlife = config.sessionlife || 14 * 24 * 60 * 60 * 1000; //14 days

// static files
var staticcachetime = config.staticcachetime || 1 * 24 * 60 * 60 * 1000; // 1 day

// socket.io
var heartbeatinterval = config.heartbeatinterval || 5000;
var heartbeattimeout = config.heartbeattimeout || 10000;

// document
var documentmaxlength = config.documentmaxlength || 100000;

// image upload setting, available options are imgur/s3/filesystem
var imageUploadType = config.imageUploadType || 'imgur';

config.s3 = config.s3 || {};
var s3 = {
    accessKeyId: process.env.S3_ACCESS_KEY_ID || config.s3.accessKeyId,
    secretAccessKey: process.env.S3_SECRET_ACCESS_KEY || config.s3.secretAccessKey,
    region: process.env.S3_REGION || config.s3.region
}
var s3bucket = process.env.S3_BUCKET || config.s3.bucket;

// auth
var facebook = (process.env.HMD_FACEBOOK_CLIENTID && process.env.HMD_FACEBOOK_CLIENTSECRET) ? {
    clientID: process.env.HMD_FACEBOOK_CLIENTID,
    clientSecret: process.env.HMD_FACEBOOK_CLIENTSECRET
} : config.facebook || false;
var twitter = (process.env.HMD_TWITTER_CONSUMERKEY && process.env.HMD_TWITTER_CONSUMERSECRET) ? {
    consumerKey: process.env.HMD_TWITTER_CONSUMERKEY,
    consumerSecret: process.env.HMD_TWITTER_CONSUMERSECRET
} : config.twitter || false;
var github = (process.env.HMD_GITHUB_CLIENTID && process.env.HMD_GITHUB_CLIENTSECRET) ? {
    clientID: process.env.HMD_GITHUB_CLIENTID,
    clientSecret: process.env.HMD_GITHUB_CLIENTSECRET
} : config.github || false;
var gitlab = (process.env.HMD_GITLAB_CLIENTID && process.env.HMD_GITLAB_CLIENTSECRET) ? {
    baseURL: process.env.HMD_GITLAB_BASEURL,
    clientID: process.env.HMD_GITLAB_CLIENTID,
    clientSecret: process.env.HMD_GITLAB_CLIENTSECRET
} : config.gitlab || false;
var dropbox = (process.env.HMD_DROPBOX_CLIENTID && process.env.HMD_DROPBOX_CLIENTSECRET) ? {
    clientID: process.env.HMD_DROPBOX_CLIENTID,
    clientSecret: process.env.HMD_DROPBOX_CLIENTSECRET
} : config.dropbox || false;
var google = (process.env.HMD_GOOGLE_CLIENTID && process.env.HMD_GOOGLE_CLIENTSECRET) ? {
    clientID: process.env.HMD_GOOGLE_CLIENTID,
    clientSecret: process.env.HMD_GOOGLE_CLIENTSECRET
} : config.google || false;
var imgur = process.env.HMD_IMGUR_CLIENTID || config.imgur || false;

function getserverurl() {
    var url = '';
    if (domain) {
        var protocol = protocolusessl ? 'https://' : 'http://';
        url = protocol + domain;
        if (urladdport && ((usessl && port != 443) || (!usessl && port != 80)))
            url += ':' + port;
    }
    if (urlpath)
        url += '/' + urlpath;
    return url;
}

var version = '0.4.5';
var minimumCompatibleVersion = '0.4.5';
var maintenance = true;
var cwd = path.join(__dirname, '..');

module.exports = {
    version: version,
    minimumCompatibleVersion: minimumCompatibleVersion,
    maintenance: maintenance,
    debug: debug,
    urlpath: urlpath,
    port: port,
    alloworigin: alloworigin,
    usessl: usessl,
    serverurl: getserverurl(),
    usecdn: usecdn,
    db: db,
    sslkeypath: path.join(cwd, sslkeypath),
    sslcertpath: path.join(cwd, sslcertpath),
    sslcapath: path.join(cwd, sslcapath),
    dhparampath: path.join(cwd, dhparampath),
    tmppath: path.join(cwd, tmppath),
    defaultnotepath: path.join(cwd, defaultnotepath),
    docspath: path.join(cwd, docspath),
    indexpath: path.join(cwd, indexpath),
    hackmdpath: path.join(cwd, hackmdpath),
    errorpath: path.join(cwd, errorpath),
    prettypath: path.join(cwd, prettypath),
    slidepath: path.join(cwd, slidepath),
    sessionname: sessionname,
    sessionsecret: sessionsecret,
    sessionlife: sessionlife,
    staticcachetime: staticcachetime,
    heartbeatinterval: heartbeatinterval,
    heartbeattimeout: heartbeattimeout,
    documentmaxlength: documentmaxlength,
    facebook: facebook,
    twitter: twitter,
    github: github,
    gitlab: gitlab,
    dropbox: dropbox,
    google: google,
    imgur: imgur,
    imageUploadType: imageUploadType,
    s3: s3,
    s3bucket: s3bucket
};
<|endoftext|>


<commit_before>var pub = {},
    TEMPLATE = 'template',
    DEFAULT_WRITE_OPTIONS = {
        force: false,
        override: false
    },
    _, Q, config, template, promises, options;

module.exports = function($inject) {
    $inject = $inject ||  {};
    _ = $inject._;
    Q = $inject.Q;
    config = $inject.config;
    template = $inject.template;

    return pub;
};

pub.create = function(domain, theOptions) {
    var child;
    options = theOptions;

    promises = promises ||  [];
    if (isDomain(domain)) {
        return create(getDomainConfig(domain));
    } else {
        child = config.get('domains.' + domain);
        promises = findDomains(domain, child);
    }
    return Q.all(promises).then(function(result) {
        if (_.chain(result).first().has('value')) {
            return _.first(result).value;
        } else {
            return result;
        }
    });
};

function findDomains(domainName, domain) {
    return _.map(domain, function(element, index) {
        if (isDomain(domainName + '.' + index)) {
            return pub.create(domainName + '.' + index, options);
        }
    });
}

function create(domainConfig) {
    var generatorConfig = getGeneratorConfig(domainConfig.generator, domainConfig),
        generator = getGenerator(domainConfig.generator),
        result = [];

    generator.setConfig(generatorConfig);
    if (options && options.filters) {
        generator.setFilters(options.filters);
    }
    return generator.createData()
        .then(function(data) {
            return _.chain(data)
                .map(function(element) {
                    var sequence = [];
                    sequence[0] = getTemplateFunction(domainConfig.template, element);
                    sequence[1] = getWriteFunction(domainConfig.output, element, result);
                    return sequence;
                })
                .flatten()
                .value()
                .reduce(Q.when, Q());
        });
}

function getTemplateFunction(templateFile, element) {
    return function() {
        return template.templateFromNpm(templateFile, element);
    };
}

function getWriteFunction(output, element, result) {
    return function(fileContent) {
        var writeOptions = _.extend(DEFAULT_WRITE_OPTIONS, options);
        writeOptions.data = element;
        return template.write(output, fileContent, writeOptions)
            .then(function(fileName) {
                result.push(fileName);
                return result;
            });
    };
}

function getDomainConfig(domain) {
    var domainObject;
    if (_.isObject(domain)) {
        domainObject = domain;
        if (!domainObject.output) {
            domainObject.output = config.get('output');
        }
        if (!domainObject.generator) {
            domainObject.generator = config.get('domains.' + domain + '.generator');
        }
    } else {
        domainObject = config.get('domains.' + domain);
        if (!domainObject.output) {
            domainObject.output = config.get('domains.' + domain + '.output');
        }
        if (!domainObject.generator) {
            domainObject.generator = config.get('domains.' + domain + '.generator');
        }
    }
    return domainObject;
}

function getGeneratorConfig(generator, domainConfig) {
    var generatorName = getGeneratorName(generator),
        global = config.get('generators.' + generatorName).config,
        local;
    if (_.isObject(generator)) {
        local = domainConfig.generator.config;
        return _.extend(global, local);
    } else {
        return global;
    }
}

function getGenerator(generator) {
    var generatorName = getGeneratorName(generator),
        Generator = require(generatorName);
    return new Generator();
}

function getGeneratorName(generator) {
    return (_.isObject(generator)) ? generator.name : generator;
}

function isDomain(domain) {
    try {
        config.get('domains.' + domain + '.' + TEMPLATE);
        return true;
    } catch (error) {
        return false;
    }
}
<commit_msg>fixes return of filenames, when toplevel domain is given<commit_after>var pub = {},
    TEMPLATE = 'template',
    DEFAULT_WRITE_OPTIONS = {
        force: false,
        override: false
    },
    _, Q, config, template, promises, options;

module.exports = function($inject) {
    $inject = $inject ||  {};
    _ = $inject._;
    Q = $inject.Q;
    config = $inject.config;
    template = $inject.template;

    return pub;
};

pub.create = function(domain, theOptions) {
    var child;
    options = theOptions;

    promises = promises ||  [];
    if (isDomain(domain)) {
        return create(getDomainConfig(domain));
    } else {
        child = config.get('domains.' + domain);
        promises = findDomains(domain, child);
    }
    return Q.all(promises).then(function(result) {
        var first = _.first(result);
        if (_.isArray(first)) {
            return _.chain(result).flatten().compact().value();
        } else {
            if (first.has('value')) {
                return _.first(result).value;
            } else {
                return _.chain(result).flatten().compact().value();
            }
        }
    });
};

function findDomains(domainName, domain) {
    return _.map(domain, function(element, index) {
        if (isDomain(domainName + '.' + index)) {
            return pub.create(domainName + '.' + index, options);
        }
    });
}

function create(domainConfig) {
    var generatorConfig = getGeneratorConfig(domainConfig.generator, domainConfig),
        generator = getGenerator(domainConfig.generator),
        result = [];

    generator.setConfig(generatorConfig);
    if (options && options.filters) {
        generator.setFilters(options.filters);
    }
    return generator.createData()
        .then(function(data) {
            return _.chain(data)
                .map(function(element) {
                    var sequence = [];
                    sequence[0] = getTemplateFunction(domainConfig.template, element);
                    sequence[1] = getWriteFunction(domainConfig.output, element, result);
                    return sequence;
                })
                .flatten()
                .value()
                .reduce(Q.when, Q());
        });
}

function getTemplateFunction(templateFile, element) {
    return function() {
        return template.templateFromNpm(templateFile, element);
    };
}

function getWriteFunction(output, element, result) {
    return function(fileContent) {
        var writeOptions = _.extend(DEFAULT_WRITE_OPTIONS, options);
        writeOptions.data = element;
        return template.write(output, fileContent, writeOptions)
            .then(function(fileName) {
                result.push(fileName);
                return result;
            });
    };
}

function getDomainConfig(domain) {
    var domainObject;
    if (_.isObject(domain)) {
        domainObject = domain;
        if (!domainObject.output) {
            domainObject.output = config.get('output');
        }
        if (!domainObject.generator) {
            domainObject.generator = config.get('domains.' + domain + '.generator');
        }
    } else {
        domainObject = config.get('domains.' + domain);
        if (!domainObject.output) {
            domainObject.output = config.get('domains.' + domain + '.output');
        }
        if (!domainObject.generator) {
            domainObject.generator = config.get('domains.' + domain + '.generator');
        }
    }
    return domainObject;
}

function getGeneratorConfig(generator, domainConfig) {
    var generatorName = getGeneratorName(generator),
        global = config.get('generators.' + generatorName).config,
        local;
    if (_.isObject(generator)) {
        local = domainConfig.generator.config;
        return _.extend(global, local);
    } else {
        return global;
    }
}

function getGenerator(generator) {
    var generatorName = getGeneratorName(generator),
        Generator = require(generatorName);
    return new Generator();
}

function getGeneratorName(generator) {
    return (_.isObject(generator)) ? generator.name : generator;
}

function isDomain(domain) {
    try {
        config.get('domains.' + domain + '.' + TEMPLATE);
        return true;
    } catch (error) {
        return false;
    }
}
<|endoftext|>


<commit_before>var

  /** async flow lib */
  $q = require('q'),

  /** server utilities / helper fns */
  util = require('../lib/util'),

  /** log helper */
  log = new require('../lib/logger')({ publish: false }),

  /** default plugins before & after helpers */
  plugins = require('../lib/plugins'),

  /** test wrapper */
  Test = require('../lib/test'),

  /** data store */
  Store = require('../lib/store'),

  /** ctrllr interface */
  Interface = require('../lib/interface');

/* ==========================================================================
 CTRLLR - Testing library
 ========================================================================== */

/**
 * testing library
 * @param config
 * @returns {CTRLLR}
 * @constructor
 */
var CTRLLR = function(config) {
  if (!(this instanceof CTRLLR)) {
    return new CTRLLR(config);
  }

  var alias = this;
  alias.init(config || null);

  return alias;
};

/**
 * sets up ctrllr instance config
 * @param config {Object} user-supplied configuration
 * @returns {CTRLLR}
 */
CTRLLR.prototype.init = function(config) {
  var
    alias = this,
    defaults = {
      port: 4040,
      timeout: 5000
    };

  // if `config` is an express server, nest in `config` object
  if (util.isExpressApp(config)) {
    config = { server: config };
  }

  // merge default config w/ user-supplied config
  alias.config = util.extend(defaults, config);

  alias.successes = 0;
  alias.failures = 0;
  alias.tests = [];
  alias.queue = [];
  alias.store = new Store();
  alias.interface = new Interface(this);

  alias._startedServer = false;

  return alias;
};

/**
 * gets the test that's being run
 * @returns {Test}
 */
CTRLLR.prototype.getActiveTest = function() {
  return this.queue[0] || null;
};

/**
 * gets the interface for the ctrllr instance
 * @returns {Interface}
 */
CTRLLR.prototype.getInterface = function() {
  return this.interface;
};

/**
 * gets the data store for the ctrllr instance
 * @returns {Store}
 */
CTRLLR.prototype.getStore = function() {
  return this.store;
};

/**
 * creates a test, adds to queue of tests to be run
 * @param config {Object} configuration for test
 * @returns {CTRLLR}
 */
CTRLLR.prototype.add = function(config) {
  var
    alias = this,
    ctrllrInterface = alias.getInterface();

  // make sure config is an array
  if (!(config instanceof  Array)) {
    config = [config];
  }

  // iterate over config, create test instances and add to array of tests
  config.forEach(function(testConfig) {
    if (!alias.config.filter || alias.config.filter(testConfig)) {
      var test = new Test(testConfig, ctrllrInterface);
      alias.tests.push(test);
    }
  });

  return alias;
};

/**
 * configures a test w/ additional functions, formats for execution
 * @param test {Test} test instance
 * @returns {Test}
 */
CTRLLR.prototype.initTest = function(test) {
  // find all `beforeEach` functions, add to test `before` array
  var
    alias = this,
    beforeEach = alias.config.beforeEach,
    afterEach = alias.config.afterEach,
    queue = [];

  if (!beforeEach) {
    // make sure `beforeEach` is defined
    beforeEach = [];
  } else if (!(beforeEach instanceof Array)) {
    // make sure `beforeEach` is an array
    beforeEach = [beforeEach];
  }

  // iterate over all `beforeEach` functions, add to `queue`
  beforeEach.forEach(function(fn) {
    queue.push(fn);
  });

  if (!test.config.before) {
    // initialize `test.before` as array if not set
    test.config.before = [];
  } else if (!(test.config.before instanceof Array)) {
    // make sure `test.before` is an array
    test.config.before = [test.config.before]
  }

  // iterate over all `before` functions, add to `queue`
  test.config.before.forEach(function(fn) {
    queue.push(fn);
  });

  // iterate over all `test.config` looking for plugins
  Object.keys(test.config).forEach(function(key) {
    // iterate over plugins, check if has `before` function & is the
    plugins.forEach(function(plugin) {
      if (plugin.hasOwnProperty('before') && plugin.name === key) {
        queue.push(function(ctrllr, request) {
          return plugin.before(ctrllr, request, test.config[key]);
        });
      }
    });
  });

  test.config.before = queue;

  ////////////////////
  ////////////////////

  // find all `afterEach` functions, add to test `after` array

  queue = [];

  if (!afterEach) {
    // make sure `afterEach` is defined
    afterEach = [];
  } else if (!(afterEach instanceof Array)) {
    // make sure `afterEach` is an array
    afterEach = [afterEach];
  }

  // iterate over all `afterEach` functions, add to `queue`
  afterEach.forEach(function(fn) {
    queue.push(fn);
  });

  if (!test.config.after) {
    // initialize `test.after` as array if not set
    test.config.after = [];
  } else if (!(test.config.after instanceof Array)) {
    // make sure `test.after` is an array
    test.config.after = [test.config.after]
  }

  // iterate over all `after` functions, add to `queue`
  test.config.after.forEach(function(fn) {
    queue.push(fn);
  });

  // iterate over all `test.config` looking for plugins
  Object.keys(test.config).forEach(function(key) {
    // iterate over plugins, check if has `before` function & is the
    plugins.forEach(function(plugin) {
      if (plugin.hasOwnProperty('after') && plugin.name === key) {
        queue.push(function(ctrllr, response) {
          return plugin.after(ctrllr, response, test.config[key]);
        });
      }
    });
  });

  test.config.after = queue;

  return test;
};

/**
 * runs a test
 * @param test {Object} test to run
 * @returns {$q.promise}
 */
CTRLLR.prototype.run = function(test) {
  log.format('Running test: ' + (test.config.description || ''), 'blue');

  var
    alias = this,
    deferred = $q.defer();

  // configure test
  alias.initTest(test);

  test
    .execute()
    .fin(function() {
      return deferred.resolve(test);
    });

  return deferred.promise;
};

/**
 * executes all the tests, starts and stops server if provided
 * @returns {CTRLLR}
 */
CTRLLR.prototype.start = function() {
  var alias = this;

  $q.fcall(function() {
    var deferred = $q.defer();

    if (!alias.config.server || alias._startedServer) {
      deferred.resolve(false);
      return deferred.promise;
    }

    log.format('CTRLLR starting server...', 'cyan');
    alias.config.server.listen(alias.config.port, function() {
      log.format('CTRLLR running server on port: ' + alias.config.port, 'cyan');
      return deferred.resolve(alias.config.server);
    });

    return deferred.promise;
  }).then(function() {
    // add all tests to `queue`, i.e. the tests that need to be run
    alias.tests.forEach(function(test) {
      alias.queue.push(alias.run);
    });

    var index = 0;
    return util.recurse(alias.queue, function() {
      // get the test at the current index, increment each time
      var test = alias.tests[index];
      index++;

      return [test];
    }, alias);
  }).then(function() {
    alias.stop();
  }).fail(function(err) {
    log.error('Error starting CTRLLR tests.', err);
  });

  return alias;
};

/**
 * stops tests, server if provided; kills process
 * @returns {CTRLLR}
 */
CTRLLR.prototype.stop = function() {
  var alias = this;

  log.format('Completed tests.', 'cyan');
  // print('Completed tests.', 'cyan', 0);
  // print('Tests ran: ' + alias.test.length, 'green', 0);
  // print('Tests failed: ' + alias._failures, 'red', 0);

  process.exit(0);

  return alias;
};

/* ==========================================================================
 Initialization / Exports
 ========================================================================== */

module.exports = CTRLLR;<commit_msg>moved `afterEach` after test `after` functions<commit_after>var

  /** async flow lib */
  $q = require('q'),

  /** server utilities / helper fns */
  util = require('../lib/util'),

  /** log helper */
  log = new require('../lib/logger')({ publish: false }),

  /** default plugins before & after helpers */
  plugins = require('../lib/plugins'),

  /** test wrapper */
  Test = require('../lib/test'),

  /** data store */
  Store = require('../lib/store'),

  /** ctrllr interface */
  Interface = require('../lib/interface');

/* ==========================================================================
 CTRLLR - Testing library
 ========================================================================== */

/**
 * testing library
 * @param config
 * @returns {CTRLLR}
 * @constructor
 */
var CTRLLR = function(config) {
  if (!(this instanceof CTRLLR)) {
    return new CTRLLR(config);
  }

  var alias = this;
  alias.init(config || null);

  return alias;
};

/**
 * sets up ctrllr instance config
 * @param config {Object} user-supplied configuration
 * @returns {CTRLLR}
 */
CTRLLR.prototype.init = function(config) {
  var
    alias = this,
    defaults = {
      port: 4040,
      timeout: 5000
    };

  // if `config` is an express server, nest in `config` object
  if (util.isExpressApp(config)) {
    config = { server: config };
  }

  // merge default config w/ user-supplied config
  alias.config = util.extend(defaults, config);

  alias.successes = 0;
  alias.failures = 0;
  alias.tests = [];
  alias.queue = [];
  alias.store = new Store();
  alias.interface = new Interface(this);

  alias._startedServer = false;

  return alias;
};

/**
 * gets the test that's being run
 * @returns {Test}
 */
CTRLLR.prototype.getActiveTest = function() {
  return this.queue[0] || null;
};

/**
 * gets the interface for the ctrllr instance
 * @returns {Interface}
 */
CTRLLR.prototype.getInterface = function() {
  return this.interface;
};

/**
 * gets the data store for the ctrllr instance
 * @returns {Store}
 */
CTRLLR.prototype.getStore = function() {
  return this.store;
};

/**
 * creates a test, adds to queue of tests to be run
 * @param config {Object} configuration for test
 * @returns {CTRLLR}
 */
CTRLLR.prototype.add = function(config) {
  var
    alias = this,
    ctrllrInterface = alias.getInterface();

  // make sure config is an array
  if (!(config instanceof  Array)) {
    config = [config];
  }

  // iterate over config, create test instances and add to array of tests
  config.forEach(function(testConfig) {
    if (!alias.config.filter || alias.config.filter(testConfig)) {
      var test = new Test(testConfig, ctrllrInterface);
      alias.tests.push(test);
    }
  });

  return alias;
};

/**
 * configures a test w/ additional functions, formats for execution
 * @param test {Test} test instance
 * @returns {Test}
 */
CTRLLR.prototype.initTest = function(test) {
  // find all `beforeEach` functions, add to test `before` array
  var
    alias = this,
    beforeEach = alias.config.beforeEach,
    afterEach = alias.config.afterEach,
    queue = [];

  if (!beforeEach) {
    // make sure `beforeEach` is defined
    beforeEach = [];
  } else if (!(beforeEach instanceof Array)) {
    // make sure `beforeEach` is an array
    beforeEach = [beforeEach];
  }

  // iterate over all `beforeEach` functions, add to `queue`
  beforeEach.forEach(function(fn) {
    queue.push(fn);
  });

  if (!test.config.before) {
    // initialize `test.before` as array if not set
    test.config.before = [];
  } else if (!(test.config.before instanceof Array)) {
    // make sure `test.before` is an array
    test.config.before = [test.config.before]
  }

  // iterate over all `before` functions, add to `queue`
  test.config.before.forEach(function(fn) {
    queue.push(fn);
  });

  // iterate over all `test.config` looking for plugins
  Object.keys(test.config).forEach(function(key) {
    // iterate over plugins, check if has `before` function & is the
    plugins.forEach(function(plugin) {
      if (plugin.hasOwnProperty('before') && plugin.name === key) {
        queue.push(function(ctrllr, request) {
          return plugin.before(ctrllr, request, test.config[key]);
        });
      }
    });
  });

  test.config.before = queue;

  ////////////////////
  ////////////////////

  // find all `afterEach` functions, add to test `after` array

  queue = [];

  if (!test.config.after) {
    // initialize `test.after` as array if not set
    test.config.after = [];
  } else if (!(test.config.after instanceof Array)) {
    // make sure `test.after` is an array
    test.config.after = [test.config.after]
  }

  // iterate over all `after` functions, add to `queue`
  test.config.after.forEach(function(fn) {
    queue.push(fn);
  });

  // iterate over all `test.config` looking for plugins
  Object.keys(test.config).forEach(function(key) {
    // iterate over plugins, check if has `before` function & is the
    plugins.forEach(function(plugin) {
      if (plugin.hasOwnProperty('after') && plugin.name === key) {
        queue.push(function(ctrllr, response) {
          return plugin.after(ctrllr, response, test.config[key]);
        });
      }
    });
  });

  if (!afterEach) {
    // make sure `afterEach` is defined
    afterEach = [];
  } else if (!(afterEach instanceof Array)) {
    // make sure `afterEach` is an array
    afterEach = [afterEach];
  }

  // iterate over all `afterEach` functions, add to `queue`
  afterEach.forEach(function(fn) {
    queue.push(fn);
  });

  test.config.after = queue;

  return test;
};

/**
 * runs a test
 * @param test {Object} test to run
 * @returns {$q.promise}
 */
CTRLLR.prototype.run = function(test) {
  log.format('Running test: ' + (test.config.description || ''), 'blue');

  var
    alias = this,
    deferred = $q.defer();

  // configure test
  alias.initTest(test);

  test
    .execute()
    .fin(function() {
      return deferred.resolve(test);
    });

  return deferred.promise;
};

/**
 * executes all the tests, starts and stops server if provided
 * @returns {CTRLLR}
 */
CTRLLR.prototype.start = function() {
  var alias = this;

  $q.fcall(function() {
    var deferred = $q.defer();

    if (!alias.config.server || alias._startedServer) {
      deferred.resolve(false);
      return deferred.promise;
    }

    log.format('CTRLLR starting server...', 'cyan');
    alias.config.server.listen(alias.config.port, function() {
      log.format('CTRLLR running server on port: ' + alias.config.port, 'cyan');
      return deferred.resolve(alias.config.server);
    });

    return deferred.promise;
  }).then(function() {
    // add all tests to `queue`, i.e. the tests that need to be run
    alias.tests.forEach(function(test) {
      alias.queue.push(alias.run);
    });

    var index = 0;
    return util.recurse(alias.queue, function() {
      // get the test at the current index, increment each time
      var test = alias.tests[index];
      index++;

      return [test];
    }, alias);
  }).then(function() {
    alias.stop();
  }).fail(function(err) {
    log.error('Error starting CTRLLR tests.', err);
  });

  return alias;
};

/**
 * stops tests, server if provided; kills process
 * @returns {CTRLLR}
 */
CTRLLR.prototype.stop = function() {
  var alias = this;

  log.format('Completed tests.', 'cyan');
  // print('Completed tests.', 'cyan', 0);
  // print('Tests ran: ' + alias.test.length, 'green', 0);
  // print('Tests failed: ' + alias._failures, 'red', 0);

  process.exit(0);

  return alias;
};

/* ==========================================================================
 Initialization / Exports
 ========================================================================== */

module.exports = CTRLLR;<|endoftext|>


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

module.exports = {
  construct: function(self, options) {
    // If set to true, the future flag allows us to get posts
    // with a publication date in the future. By default,
    // this is false by default
    self.addFilter('future', {
      def: false,
      finalize: function() {
        var future = self.get('future');
        if (future === null) {
          return;
        }

        var now = moment().format('YYYY-MM-DD');

        if (future) {
          self.and({
            publishedAt: { $gte: now }
          });
        } else {
          self.and({
            publishedAt: { $lte: now }
          });
        }
      },
      safeFor: 'public',
      launder: function(s) {
        return self.apos.launder.booleanOrNull(s);
      }
    });
  }
};
<commit_msg>added built in filters for year, month, day.<commit_after>var _ = require('lodash');
var moment = require('moment');

module.exports = {
  construct: function(self, options) {
    // If set to true, the future flag allows us to get posts
    // with a publication date in the future. By default,
    // this is false by default
    self.addFilter('future', {
      def: false,
      finalize: function() {
        var future = self.get('future');
        if (future === null) {
          return;
        }

        var now = moment().format('YYYY-MM-DD');

        if (future) {
          self.and({
            publishedAt: { $gte: now }
          });
        } else {
          self.and({
            publishedAt: { $lte: now }
          });
        }
      },
      safeFor: 'public',
      launder: function(s) {
        return self.apos.launder.booleanOrNull(s);
      }
    });

    self.addFilter('year', {
      def: null,
      safeFor: 'public',
      finalize: function() {
        var year = self.get('year');

        if (year === null) {
          return;
        }

        self.and({
          publishedAt: { $regex: '^'+ year }
        });
      },
      launder: function(s) {
        return self.apos.launder.string(s);
      },
      choices: function(callback) {
        return self.toDistinct('publishedAt', function(err, results) {
          if (err) {
            return callback(err);
          }

          return callback(null, _.uniq(_.each(results, function(value, key) { results[key] = value.substr(0,4) })).sort());
        });
      }
    });

    self.addFilter('month', {
      def: null,
      safeFor: 'public',
      finalize: function() {
        var month = self.get('month');

        if (month === null) {
          return;
        }

        self.and({
          publishedAt: { $regex: '^'+ month }
        });
      },
      launder: function(s) {
        return self.apos.launder.string(s);
      },
      choices: function(callback) {
        return self.toDistinct('publishedAt', function(err, results) {
          if (err) {
            return callback(err);
          }

          return callback(null, _.uniq(_.each(results, function(value, key) { results[key] = value.substr(0,7) })).sort());
        });
      }
    });

    self.addFilter('day', {
      def: null,
      safeFor: 'public',
      finalize: function() {
        var day = self.get('day');

        if (day === null) {
          return;
        }

        self.and({
          publishedAt: day
        });
      },
      launder: function(s) {
        return self.apos.launder.string(s);
      },
      choices: function(callback) {
        return self.toDistinct('publishedAt', function(err, results) {
          if (err) {
            return callback(err);
          }

          return callback(null, results);
        });
      }
    });
  }
};
<|endoftext|>


<commit_before>var socket = require('socket.io-client');
var config = require('config');
var sonumiLogger = require('sonumi-logger');

function Device(deviceConfig) {
    var logDirectory = config.logging.logDir;

    logger = sonumiLogger.init(logDirectory);
    logger.addLogFile('info', logDirectory + '/sonumi-device-info.log', 'info');
    logger.addLogFile('errors', logDirectory + '/sonumi-device-errors.log', 'error');

    var host = config.server.host + ':' + config.server.port + '/devices';
    logger.log('Connecting to ' + host);
    var client = new socket(host);

    client.on('connect', function () {
        logger.log('connected!');
    });

    client.on('connect_error', function (err) {
        logger.error('connection error!');
        logger.error(err);
    });

    client.on('disconnect', function (data) {
        logger.log('disconnected!');
        logger.log(data);
    });

    var actions = [];

    logger.log('adding action handlers');
    // add action handlers
    deviceConfig.actions.forEach(function(action) {
        logger.log('Adding ' + action.label + ' action');
        actions.push({"label": action.label});

        client.on(action.label, function(actionId) {
            logger.log('Action ' + action.label + ' has been triggered');
            // trigger the action and send response to client
            action.action().then(
                function(message) {
                    if (message && message == 'executing') {
                        logger.log('Action ' + action.label + ' is already executing');
                        client.emit('action_executing', actionId);
                    } else {
                        logger.log('Action ' + action.label + ' has completed');
                        client.emit('action_complete', actionId);
                    }
                },
                function() {
                    logger.log('Action ' + action.label + ' has failed');
                    client.emit('action_failed', actionId);
                }
            );
        });
    });

    client.on('config', function() {
        logger.log('Action config has been triggered');

        client.emit(
            'device-config',
            {
                "id": Math.random(),
                "name": deviceConfig.name,
                "actions": actions
            }
        );
    });
}

module.exports = Device;<commit_msg>Add connect timeout handler for socket client<commit_after>var socket = require('socket.io-client');
var config = require('config');
var sonumiLogger = require('sonumi-logger');

function Device(deviceConfig) {
    var logDirectory = config.logging.logDir;

    logger = sonumiLogger.init(logDirectory);
    logger.addLogFile('info', logDirectory + '/sonumi-device-info.log', 'info');
    logger.addLogFile('errors', logDirectory + '/sonumi-device-errors.log', 'error');

    var host = config.server.host + ':' + config.server.port + '/devices';
    logger.log('Connecting to ' + host);
    var client = new socket(host);

    client.on('connect', function () {
        logger.log('connected!');
    });

    client.on('connect_error', function (err) {
        logger.error('connection error!');
        logger.error(err);
        process.exit(1);
    });

    client.on('connect_timeout', function (err) {
        logger.error('connection timeout!');
        logger.error(err);
        process.exit(1);
    });

    client.on('disconnect', function (data) {
        logger.log('disconnected!');
        logger.log(data);
    });

    var actions = [];

    logger.log('adding action handlers');
    // add action handlers
    deviceConfig.actions.forEach(function(action) {
        logger.log('Adding ' + action.label + ' action');
        actions.push({"label": action.label});

        client.on(action.label, function(actionId) {
            logger.log('Action ' + action.label + ' has been triggered');
            // trigger the action and send response to client
            action.action().then(
                function(message) {
                    if (message && message == 'executing') {
                        logger.log('Action ' + action.label + ' is already executing');
                        client.emit('action_executing', actionId);
                    } else {
                        logger.log('Action ' + action.label + ' has completed');
                        client.emit('action_complete', actionId);
                    }
                },
                function() {
                    logger.log('Action ' + action.label + ' has failed');
                    client.emit('action_failed', actionId);
                }
            );
        });
    });

    client.on('config', function() {
        logger.log('Action config has been triggered');

        client.emit(
            'device-config',
            {
                "id": Math.random(),
                "name": deviceConfig.name,
                "actions": actions
            }
        );
    });
}

module.exports = Device;<|endoftext|>


<commit_before>'use strict';
var fromString = require('./buffer-util').fromString;
var writeType = {};

var encode = module.exports = function (encoder, value) {
	writeType[typeof value](encoder, value);
};

// Fills the writeType hash with functions that each encode values of their
// respective types at the given Paper's offset.
(function (write) {

	var float32Buffer = new Float32Array(1);
	var isFloat32 = function (num) {
		float32Buffer[0] = num;
		return float32Buffer[0] === num;
	};

	writeType.number = function (encoder, value) {
		var ivalue = value | 0;
		var uivalue = value >>> 0;
		if (value !== ivalue && value !== uivalue) {
			isFloat32(value)
				? write.float32(encoder, value)  // float 32 -- 0xca
				: write.float64(encoder, value); // float 64 -- 0xcb
		} else if (ivalue <= 0x7f && ivalue >= -0x20) {
			// positive fixint -- 0x00 - 0x7f
			// negative fixint -- 0xe0 - 0xff
			write.type(encoder, ivalue & 0xff);
		} else if (value === uivalue) {
			// uint 8 -- 0xcc
			// uint 16 -- 0xcd
			// uint 32 -- 0xce
			uivalue <= 0xff ? write.int8(encoder, 0xcc, uivalue) :
			uivalue <= 0xffff ? write.int16(encoder, 0xcd, uivalue) :
			write.int32(encoder, 0xce, uivalue);
		} else {
			// int 8 -- 0xd0
			// int 16 -- 0xd1
			// int 32 -- 0xd2
			ivalue >= -0x80 ? write.int8(encoder, 0xd0, ivalue) :
			ivalue >= -0x8000 ? write.int16(encoder, 0xd1, ivalue) :
			write.int32(encoder, 0xd2, ivalue);
		}
	};

	writeType.string = function (encoder, value) {
		var utf8 = fromString(value);
		var byteLength = utf8.byteLength;

		// fixstr -- 0xa0 - 0xbf
		// str 8 -- 0xd9
		// str 16 -- 0xda
		// str 32 -- 0xdb
		byteLength < 32 ? write.type(encoder, 0xa0 + byteLength) :
		byteLength <= 0xff ? write.int8(encoder, 0xd9, byteLength) :
		byteLength <= 0xffff ? write.int16(encoder, 0xda, byteLength) :
		write.int32(encoder, 0xdb, byteLength);

		encoder.send(utf8);
	};

	writeType.boolean = function (encoder, value) {
		// false -- 0xc2
		// true -- 0xc3
		write.type(encoder, value ? 0xc3 : 0xc2);
	};

	writeType.object = function (encoder, value) {
		var packer;
		if (value === null) return nil(encoder, value);
		if (Array.isArray(value)) return array(encoder, value);
		if (value instanceof Uint8Array) return bin(encoder, value);
		if (encoder.codec && (packer = encoder.codec.getPacker(value))) {
			return ext(encoder, packer(value));
		}
		map(encoder, value);
	};

	writeType.undefined = nil;
	writeType.function = nil;
	writeType.symbol = nil;

	var nil = function (encoder) {
		// nil -- 0xc0
		write.type(encoder, 0xc0);
	};

	var array = function (encoder, value) {
		var length = value.length;

		// fixarray -- 0x90 - 0x9f
		// array 16 -- 0xdc
		// array 32 -- 0xdd
		length < 16 ? write.type(encoder, 0x90 + length) :
		length <= 0xffff ? write.int16(encoder, 0xdc, length) :
		write.int32(encoder, 0xdd, length);

		for (var i=0; i<length; ++i) {
			encode(encoder, value[i]);
		}
	};

	var bin = function (encoder, value) {
		var byteLength = value.byteLength;

		// bin 8 -- 0xc4
		// bin 16 -- 0xc5
		// bin 32 -- 0xc6
		byteLength <= 0xff ? write.int8(encoder, 0xc4, byteLength) :
		byteLength <= 0xffff ? write.int16(encoder, 0xc5, byteLength) :
		write.int32(encoder, 0xc6, byteLength);

		encoder.send(value);
	};

	var ext = function (encoder, value) {
		var byteLength = value.buffer.byteLength;

		// fixext 1 -- 0xd4
		// fixext 2 -- 0xd5
		// fixext 4 -- 0xd6
		// fixext 8 -- 0xd7
		// fixext 16 -- 0xd8
		// ext 8 -- 0xc7
		// ext 16 -- 0xc8
		// ext 32 -- 0xc9
		byteLength === 1 ? write.int8(encoder, 0xd4, value.etype) :
		byteLength === 2 ? write.int8(encoder, 0xd5, value.etype) :
		byteLength === 4 ? write.int8(encoder, 0xd6, value.etype) :
		byteLength === 8 ? write.int8(encoder, 0xd7, value.etype) :
		byteLength === 16 ? write.int8(encoder, 0xd8, value.etype) :
		byteLength <= 0xff ? (write.int8(encoder, 0xc7, byteLength), write.type(value.etype)) :
		byteLength <= 0xffff ? (write.int16(encoder, 0xc8, byteLength), write.type(value.etype)) :
		(write.int32(encoder, 0xc9, byteLength), write.type(value.etype));

		encoder.send(value.buffer);
	};

	var map = function (encoder, value) {
		var keys = Object.keys(value);
		var length = keys.length;

		// fixmap -- 0x80 - 0x8f
		// map 16 -- 0xde
		// map 32 -- 0xdf
		length < 16 ? write.type(encoder, 0x80 + length) :
		length <= 0xffff ? write.type(encoder, 0xde, length) :
		write.type(encoder, 0xdf, length);

		keys.forEach(function (key) {
			encode(encoder, key);
			encode(encoder, value[key]);
		});
	};
}(require('./write-header')));
<commit_msg>tweak<commit_after>'use strict';
var writeType = {};

var encode = module.exports = function (encoder, value) {
	writeType[typeof value](encoder, value);
};

// Fills the writeType hash with functions that each encode values of their
// respective types at the given Paper's offset.
(function (write, fromString) {

	var float32Buffer = new Float32Array(1);
	var isFloat32 = function (num) {
		float32Buffer[0] = num;
		return float32Buffer[0] === num;
	};

	writeType.number = function (encoder, value) {
		var ivalue = value | 0;
		var uivalue = value >>> 0;
		if (value !== ivalue && value !== uivalue) {
			isFloat32(value)
				? write.float32(encoder, value)  // float 32 -- 0xca
				: write.float64(encoder, value); // float 64 -- 0xcb
		} else if (ivalue <= 0x7f && ivalue >= -0x20) {
			// positive fixint -- 0x00 - 0x7f
			// negative fixint -- 0xe0 - 0xff
			write.type(encoder, ivalue & 0xff);
		} else if (value === uivalue) {
			// uint 8 -- 0xcc
			// uint 16 -- 0xcd
			// uint 32 -- 0xce
			uivalue <= 0xff ? write.int8(encoder, 0xcc, uivalue) :
			uivalue <= 0xffff ? write.int16(encoder, 0xcd, uivalue) :
			write.int32(encoder, 0xce, uivalue);
		} else {
			// int 8 -- 0xd0
			// int 16 -- 0xd1
			// int 32 -- 0xd2
			ivalue >= -0x80 ? write.int8(encoder, 0xd0, ivalue) :
			ivalue >= -0x8000 ? write.int16(encoder, 0xd1, ivalue) :
			write.int32(encoder, 0xd2, ivalue);
		}
	};

	writeType.string = function (encoder, value) {
		var utf8 = fromString(value);
		var byteLength = utf8.byteLength;

		// fixstr -- 0xa0 - 0xbf
		// str 8 -- 0xd9
		// str 16 -- 0xda
		// str 32 -- 0xdb
		byteLength < 32 ? write.type(encoder, 0xa0 + byteLength) :
		byteLength <= 0xff ? write.int8(encoder, 0xd9, byteLength) :
		byteLength <= 0xffff ? write.int16(encoder, 0xda, byteLength) :
		write.int32(encoder, 0xdb, byteLength);

		encoder.send(utf8);
	};

	writeType.boolean = function (encoder, value) {
		// false -- 0xc2
		// true -- 0xc3
		write.type(encoder, value ? 0xc3 : 0xc2);
	};

	writeType.object = function (encoder, value) {
		var packer;
		if (value === null) return nil(encoder, value);
		if (Array.isArray(value)) return array(encoder, value);
		if (value instanceof Uint8Array) return bin(encoder, value);
		if (encoder.codec && (packer = encoder.codec.getPacker(value))) {
			return ext(encoder, packer(value));
		}
		map(encoder, value);
	};

	writeType.undefined = nil;
	writeType.function = nil;
	writeType.symbol = nil;

	var nil = function (encoder) {
		// nil -- 0xc0
		write.type(encoder, 0xc0);
	};

	var array = function (encoder, value) {
		var length = value.length;

		// fixarray -- 0x90 - 0x9f
		// array 16 -- 0xdc
		// array 32 -- 0xdd
		length < 16 ? write.type(encoder, 0x90 + length) :
		length <= 0xffff ? write.int16(encoder, 0xdc, length) :
		write.int32(encoder, 0xdd, length);

		for (var i=0; i<length; ++i) {
			encode(encoder, value[i]);
		}
	};

	var bin = function (encoder, value) {
		var byteLength = value.byteLength;

		// bin 8 -- 0xc4
		// bin 16 -- 0xc5
		// bin 32 -- 0xc6
		byteLength <= 0xff ? write.int8(encoder, 0xc4, byteLength) :
		byteLength <= 0xffff ? write.int16(encoder, 0xc5, byteLength) :
		write.int32(encoder, 0xc6, byteLength);

		encoder.send(value);
	};

	var ext = function (encoder, value) {
		var byteLength = value.buffer.byteLength;

		// fixext 1 -- 0xd4
		// fixext 2 -- 0xd5
		// fixext 4 -- 0xd6
		// fixext 8 -- 0xd7
		// fixext 16 -- 0xd8
		// ext 8 -- 0xc7
		// ext 16 -- 0xc8
		// ext 32 -- 0xc9
		byteLength === 1 ? write.int8(encoder, 0xd4, value.etype) :
		byteLength === 2 ? write.int8(encoder, 0xd5, value.etype) :
		byteLength === 4 ? write.int8(encoder, 0xd6, value.etype) :
		byteLength === 8 ? write.int8(encoder, 0xd7, value.etype) :
		byteLength === 16 ? write.int8(encoder, 0xd8, value.etype) :
		byteLength <= 0xff ? (write.int8(encoder, 0xc7, byteLength), write.type(value.etype)) :
		byteLength <= 0xffff ? (write.int16(encoder, 0xc8, byteLength), write.type(value.etype)) :
		(write.int32(encoder, 0xc9, byteLength), write.type(value.etype));

		encoder.send(value.buffer);
	};

	var map = function (encoder, value) {
		var keys = Object.keys(value);
		var length = keys.length;

		// fixmap -- 0x80 - 0x8f
		// map 16 -- 0xde
		// map 32 -- 0xdf
		length < 16 ? write.type(encoder, 0x80 + length) :
		length <= 0xffff ? write.type(encoder, 0xde, length) :
		write.type(encoder, 0xdf, length);

		keys.forEach(function (key) {
			encode(encoder, key);
			encode(encoder, value[key]);
		});
	};
}(require('./write-header'), require('./buffer-util').fromString));
<|endoftext|>


<commit_before>var path = require('path');
var roost = require('roost');

// ---

var logger = require(path.join(__dirname, 'logger.js'));
var helpers = require(path.join(__dirname, 'helpers.js'));
var providers = require(path.join(__dirname, 'providers.js'));

// ---

function shell(opt, manifest, provider, name, node, callback) {
	logger.verbose('call provider.shellSpec for node', helpers.q(name));

	provider.shellSpec(name, node, function (err, spec) {
		if (err) {
			return callback(err);
		}

		logger.debug('shell spec is', spec);

		if (!spec.match(/^ssh:/)) {
			return callback(helpers.e('unsupported shell specification', spec));
		}

		var connection = new roost.ssh.Connection({meta:{location:manifest.meta.location}});

		logger.verbose('connect to node', helpers.q(name));

		connection.connect(spec, function (err) {
			if (err) {
				return callback(err);
			}

			logger.verbose('shell to node', helpers.q(name));

			connection.shell(function (err) {
				if (err) {
					return callback(err);
				}

				logger.verbose('disconnect from node', helpers.q(name));

				connection.disconnect({}, function (err) {
					if (err) {
						return callback(err);
					}

					return callback();
				});
			});
		});
	});
}

function provision(opt, manifest, provider, name, node, callback) {
	if (!node.hasOwnProperty('roost')) {
		return callback(helpers.e('no roost configuration defined'));
	}

	roost.logger.setGlobalLevel(logger.level);
	roost.logger.setGlobalColorization(logger.colorize);

	var roostManifest = node.roost;

	if (typeof(roostManifest) == 'string' || roostManifest instanceof String) {
		try {
			roostManifest = roost.manifest.load(path.resolve(path.dirname(manifest.meta.location), roostManifest));
		} catch (e) {
			return callback(e);
		}
	} else {
		roostManifest.meta = {
			location: manifest.meta.location
		};
	}

	logger.debug('provision with roost manifest', roostManifest);

	var roostPlugins;

	try {
		roostPlugins = roost.plugins.obtain(roostManifest);
	} catch (e) {
		return callback(e);
	}

	if (roostPlugins.length > 0) {
		logger.debug('roost plugins', roostPlugins);
	}

	logger.verbose('call provider.shellSpec for node', helpers.q(name));

	provider.shellSpec(name, node, function (err, spec) {
		if (err) {
			return callback(err);
		}

		logger.debug('shell spec is', spec);

		var roostTarget;

		try {
			roostTarget = roost.targets.instance(spec, roostManifest);
		} catch (e) {
			return callback(e);
		}

		logger.verbose('launch roost for node', helpers.q(name));

		try {
			roost.engine.launch({options:{}, argv:[]}, roostManifest, roostPlugins, roostTarget, callback);
		} catch (e) {
			return callback(e);
		}
	});
}

function status(opt, manifest, provider, name, node, callback) {
	logger.verbose('invoke provider.status for node', helpers.q(name));

	provider.status(name, node, function (err, state) {
		if (err) {
			return callback(err);
		}

		logger.info('node', helpers.q(name), state);

		callback(null);
	});
}

function boot(opt, manifest, provider, name, node, callback) {
	logger.verbose('invoke provider.boot for node', helpers.q(name));

	provider.boot(name, node, function (err, state) {
		if (err) {
			return callback(err);
		}

		logger.verbose('call action provision for node', helpers.q(name));

		exports.provision(opt, manifest, provider, name, node, callback);
	});
}

function halt(opt, manifest, provider, name, node, callback) {
	logger.verbose('invoke provider.halt for node', helpers.q(name));

	provider.halt(name, node, function (err, state) {
		if (err) {
			return callback(err);
		}

		logger.verbose('call action status for node', helpers.q(name));

		exports.status(opt, manifest, provider, name, node, callback);
	});
}

function reload(opt, manifest, provider, name, node, callback) {
	logger.verbose('call action halt for node', helpers.q(name));

	exports.halt(opt, manifest, provider, name, node, function (err) {
		if (err) {
			return callback(err);
		}

		logger.verbose('call action boot for node', helpers.q(name));

		exports.boot(opt, manifest, provider, name, node, callback);
	});
}

// ---

function launch(opt, manifest, plugins, provider, action, callback) {
	if (!(action in exports) || action == 'launch') {
		throw helpers.e('action', helpers.q(action), 'is not recognized');
	}

	plugins.forEach(function (plugin) {
		plugin.vortex(opt, manifest, provider, action);
	});

	if (!manifest.hasOwnProperty('nodes')) {
		logger.debug('no nodes defined');

		return callback(null);
	}

	var nodes = manifest.nodes;
	var names = (opt.argv.length ? opt.argv.slice(1, opt.argv.length) : Object.keys(nodes));
	var map = {};

	names.forEach(function (name) {
		if (!nodes.hasOwnProperty(name)) {
			throw helpers.e('node', helpers.q(name), 'does not exist');
		}

		var node = nodes[name];
		var nodeProvider = provider;

		if (!nodeProvider) {
			nodeProvider = node.hasOwnProperty('default_provider') ? node.default_provider : null;

			if (nodeProvider) {
				nodeProvider = providers.instance(nodeProvider, manifest);
			}
		}

		if (!nodeProvider) {
			nodeProvider = manifest.hasOwnProperty('default_provider') ? manifest.default_provider : null;

			if (nodeProvider) {
				nodeProvider = providers.instance(nodeProvider, manifest);
			}
		}

		if (!nodeProvider) {
			nodeProvider = providers.instance('VirtualBox', manifest);
		}

		map[name] = {
			nodeProvider: nodeProvider,
			node: node
		};
	});

	var notCompleted = 0;

	Object.keys(map).forEach(function (name) {
		notCompleted += 1;

		exports[action](opt, manifest, map[name].nodeProvider, name, map[name].node, function (err) {
			if (err) {
				return callback(err);
			}

			notCompleted -= 1;

			if (notCompleted == 0) {
				return callback();
			}
		});
	});
}

// ---

exports.shell = shell;
exports.provision = provision;
exports.status = status;
exports.boot = boot;
exports.halt = halt;
exports.reload = reload;
exports.launch = launch;
<commit_msg>Fixed logical error.<commit_after>var path = require('path');
var roost = require('roost');

// ---

var logger = require(path.join(__dirname, 'logger.js'));
var helpers = require(path.join(__dirname, 'helpers.js'));
var providers = require(path.join(__dirname, 'providers.js'));

// ---

function shell(opt, manifest, provider, name, node, callback) {
	logger.verbose('call provider.shellSpec for node', helpers.q(name));

	provider.shellSpec(name, node, function (err, spec) {
		if (err) {
			return callback(err);
		}

		logger.debug('shell spec is', spec);

		if (!spec.match(/^ssh:/)) {
			return callback(helpers.e('unsupported shell specification', spec));
		}

		var connection = new roost.ssh.Connection({meta:{location:manifest.meta.location}});

		logger.verbose('connect to node', helpers.q(name));

		connection.connect(spec, function (err) {
			if (err) {
				return callback(err);
			}

			logger.verbose('shell to node', helpers.q(name));

			connection.shell(function (err) {
				if (err) {
					return callback(err);
				}

				logger.verbose('disconnect from node', helpers.q(name));

				connection.disconnect({}, function (err) {
					if (err) {
						return callback(err);
					}

					return callback();
				});
			});
		});
	});
}

function provision(opt, manifest, provider, name, node, callback) {
	if (!node.hasOwnProperty('roost')) {
		return callback(helpers.e('no roost configuration defined'));
	}

	roost.logger.setGlobalLevel(logger.level);
	roost.logger.setGlobalColorization(logger.colorize);

	var roostManifest = node.roost;

	if (typeof(roostManifest) == 'string' || roostManifest instanceof String) {
		try {
			roostManifest = roost.manifest.load(path.resolve(path.dirname(manifest.meta.location), roostManifest));
		} catch (e) {
			return callback(e);
		}
	} else {
		roostManifest.meta = {
			location: manifest.meta.location
		};
	}

	logger.debug('provision with roost manifest', roostManifest);

	var roostPlugins;

	try {
		roostPlugins = roost.plugins.obtain(roostManifest);
	} catch (e) {
		return callback(e);
	}

	if (roostPlugins.length > 0) {
		logger.debug('roost plugins', roostPlugins);
	}

	logger.verbose('call provider.shellSpec for node', helpers.q(name));

	provider.shellSpec(name, node, function (err, spec) {
		if (err) {
			return callback(err);
		}

		logger.debug('shell spec is', spec);

		var roostTarget;

		try {
			roostTarget = roost.targets.instance(spec, roostManifest);
		} catch (e) {
			return callback(e);
		}

		logger.verbose('launch roost for node', helpers.q(name));

		try {
			roost.engine.launch({options:{}, argv:[]}, roostManifest, roostPlugins, roostTarget, callback);
		} catch (e) {
			return callback(e);
		}
	});
}

function status(opt, manifest, provider, name, node, callback) {
	logger.verbose('invoke provider.status for node', helpers.q(name));

	provider.status(name, node, function (err, state) {
		if (err) {
			return callback(err);
		}

		logger.info('node', helpers.q(name), state);

		callback(null);
	});
}

function boot(opt, manifest, provider, name, node, callback) {
	logger.verbose('invoke provider.boot for node', helpers.q(name));

	provider.boot(name, node, function (err, state) {
		if (err) {
			return callback(err);
		}

		logger.verbose('call action provision for node', helpers.q(name));

		exports.provision(opt, manifest, provider, name, node, callback);
	});
}

function halt(opt, manifest, provider, name, node, callback) {
	logger.verbose('invoke provider.halt for node', helpers.q(name));

	provider.halt(name, node, function (err, state) {
		if (err) {
			return callback(err);
		}

		logger.verbose('call action status for node', helpers.q(name));

		exports.status(opt, manifest, provider, name, node, callback);
	});
}

function reload(opt, manifest, provider, name, node, callback) {
	logger.verbose('call action halt for node', helpers.q(name));

	exports.halt(opt, manifest, provider, name, node, function (err) {
		if (err) {
			return callback(err);
		}

		logger.verbose('call action boot for node', helpers.q(name));

		exports.boot(opt, manifest, provider, name, node, callback);
	});
}

// ---

function launch(opt, manifest, plugins, provider, action, callback) {
	if (!(action in exports) || action == 'launch') {
		throw helpers.e('action', helpers.q(action), 'is not recognized');
	}

	plugins.forEach(function (plugin) {
		plugin.vortex(opt, manifest, provider, action);
	});

	if (!manifest.hasOwnProperty('nodes')) {
		logger.debug('no nodes defined');

		return callback(null);
	}

	var nodes = manifest.nodes;
	var names = (opt.argv.length > 1 ? opt.argv.slice(1, opt.argv.length) : Object.keys(nodes));
	var map = {};

	names.forEach(function (name) {
		if (!nodes.hasOwnProperty(name)) {
			throw helpers.e('node', helpers.q(name), 'does not exist');
		}

		var node = nodes[name];
		var nodeProvider = provider;

		if (!nodeProvider) {
			nodeProvider = node.hasOwnProperty('default_provider') ? node.default_provider : null;

			if (nodeProvider) {
				nodeProvider = providers.instance(nodeProvider, manifest);
			}
		}

		if (!nodeProvider) {
			nodeProvider = manifest.hasOwnProperty('default_provider') ? manifest.default_provider : null;

			if (nodeProvider) {
				nodeProvider = providers.instance(nodeProvider, manifest);
			}
		}

		if (!nodeProvider) {
			nodeProvider = providers.instance('VirtualBox', manifest);
		}

		map[name] = {
			nodeProvider: nodeProvider,
			node: node
		};
	});

	var notCompleted = 0;

	Object.keys(map).forEach(function (name) {
		notCompleted += 1;

		exports[action](opt, manifest, map[name].nodeProvider, name, map[name].node, function (err) {
			if (err) {
				return callback(err);
			}

			notCompleted -= 1;

			if (notCompleted == 0) {
				return callback();
			}
		});
	});
}

// ---

exports.shell = shell;
exports.provision = provision;
exports.status = status;
exports.boot = boot;
exports.halt = halt;
exports.reload = reload;
exports.launch = launch;
<|endoftext|>


<commit_before>/**
 * @author mrdoob / http://mrdoob.com/
 *
 * Abstract Base class to block based textures loader (dds, pvr, ...)
 */

THREE.CompressedTextureLoader = function () {
	// override in sub classes
	this._parser = null;
};

THREE.CompressedTextureLoader.prototype = {

	constructor: THREE.CompressedTextureLoader,

	load: function ( url, onLoad, onError ) {

		var scope = this;

		var images = [];

		var texture = new THREE.CompressedTexture();
		texture.image = images;

	var loader = new THREE.XHRLoader();
	loader.setResponseType( 'arraybuffer' );

		if ( url instanceof Array ) {

			var loaded = 0;

			var loadTexture = function ( i ) {

				loader.load( url[ i ], function ( buffer ) {

					var texDatas = scope._parser( buffer, true );

					images[ i ] = {
						width: texDatas.width,
						height: texDatas.height,
						format: texDatas.format,
						mipmaps: texDatas.mipmaps
					};

					loaded += 1;

					if ( loaded === 6 ) {

 						if (texDatas.mipmapCount == 1)
 							texture.minFilter = THREE.LinearFilter;

						texture.format = texDatas.format;
						texture.needsUpdate = true;

						if ( onLoad ) onLoad( texture );

					}

				} );

			};

			for ( var i = 0, il = url.length; i < il; ++ i ) {

				loadTexture( i );

			}

		} else {

			// compressed cubemap texture stored in a single DDS file

			loader.load( url, function ( buffer ) {

				var texDatas = scope._parser( buffer, true );

				if ( texDatas.isCubemap ) {

					var faces = texDatas.mipmaps.length / texDatas.mipmapCount;

					for ( var f = 0; f < faces; f ++ ) {

						images[ f ] = { mipmaps : [] };

						for ( var i = 0; i < texDatas.mipmapCount; i ++ ) {

							images[ f ].mipmaps.push( texDatas.mipmaps[ f * texDatas.mipmapCount + i ] );
							images[ f ].format = texDatas.format;
							images[ f ].width = texDatas.width;
							images[ f ].height = texDatas.height;

						}

					}

				} else {

					texture.image.width = texDatas.width;
					texture.image.height = texDatas.height;
					texture.mipmaps = texDatas.mipmaps;

				}

				if (texDatas.mipmapCount == 1)
	 				texture.minFilter = THREE.LinearFilter;

				texture.format = texDatas.format;
				texture.needsUpdate = true;

				if ( onLoad ) onLoad( texture );

			} );

		}

		return texture;

	}

};
<commit_msg>Minor code clean up.<commit_after>/**
 * @author mrdoob / http://mrdoob.com/
 *
 * Abstract Base class to block based textures loader (dds, pvr, ...)
 */

THREE.CompressedTextureLoader = function () {

	// override in sub classes
	this._parser = null;

};

THREE.CompressedTextureLoader.prototype = {

	constructor: THREE.CompressedTextureLoader,

	load: function ( url, onLoad, onError ) {

		var scope = this;

		var images = [];

		var texture = new THREE.CompressedTexture();
		texture.image = images;

		var loader = new THREE.XHRLoader();
		loader.setResponseType( 'arraybuffer' );

		if ( url instanceof Array ) {

			var loaded = 0;

			var loadTexture = function ( i ) {

				loader.load( url[ i ], function ( buffer ) {

					var texDatas = scope._parser( buffer, true );

					images[ i ] = {
						width: texDatas.width,
						height: texDatas.height,
						format: texDatas.format,
						mipmaps: texDatas.mipmaps
					};

					loaded += 1;

					if ( loaded === 6 ) {

 						if (texDatas.mipmapCount == 1)
 							texture.minFilter = THREE.LinearFilter;

						texture.format = texDatas.format;
						texture.needsUpdate = true;

						if ( onLoad ) onLoad( texture );

					}

				} );

			};

			for ( var i = 0, il = url.length; i < il; ++ i ) {

				loadTexture( i );

			}

		} else {

			// compressed cubemap texture stored in a single DDS file

			loader.load( url, function ( buffer ) {

				var texDatas = scope._parser( buffer, true );

				if ( texDatas.isCubemap ) {

					var faces = texDatas.mipmaps.length / texDatas.mipmapCount;

					for ( var f = 0; f < faces; f ++ ) {

						images[ f ] = { mipmaps : [] };

						for ( var i = 0; i < texDatas.mipmapCount; i ++ ) {

							images[ f ].mipmaps.push( texDatas.mipmaps[ f * texDatas.mipmapCount + i ] );
							images[ f ].format = texDatas.format;
							images[ f ].width = texDatas.width;
							images[ f ].height = texDatas.height;

						}

					}

				} else {

					texture.image.width = texDatas.width;
					texture.image.height = texDatas.height;
					texture.mipmaps = texDatas.mipmaps;

				}

				if ( texDatas.mipmapCount === 1 ) {

					texture.minFilter = THREE.LinearFilter;

				}

				texture.format = texDatas.format;
				texture.needsUpdate = true;

				if ( onLoad ) onLoad( texture );

			} );

		}

		return texture;

	}

};
<|endoftext|>


<commit_before>import {LightningElement, api} from 'lwc';
import { isUndefined } from 'c/utilCommon';
import GeFormElementHelper from './geFormElementHelper.js';

const COLLAPSED_DISPLAY_MODE = 'collapsed';

export default class GeFormSection extends LightningElement {
    @api section;
    @api widgetData;
    @api formState;
    _hasCreditCardWidget = false;

    renderedCallback() {
        this.registerCreditCardWidget();
    }

    /**
     * Get the alternative text that represents the section expand/collapse button
     * @returns {string} containing the section expand alternative text
     */
    get altTextLabel() {
        return 'Toggle ' + this.section.label;
    }

    get isCollapsed() {
        return this.section.defaultDisplayMode === COLLAPSED_DISPLAY_MODE;
    }

    /**
     * Gets value and UI-label for the requestedFields in the section (if any)
     * @param requestedFields - Array of API Field Names to get information
     * @returns {Array} - field value and ui-label using api-field-name as key
     */
    @api
    getFieldValueAndLabel( requestedFields ) {

        const fields = this.template.querySelectorAll('c-ge-form-field');
        let dataImportFieldAndLabels = {};

        if (fields !== null && typeof fields !== 'undefined') {
            fields.forEach( field => {
                if ( requestedFields.indexOf(field.sourceFieldAPIName) !== -1 ){
                    field.clearCustomValidity();
                    dataImportFieldAndLabels = { ...dataImportFieldAndLabels, ...(field.fieldValueAndLabel) };
                }
            });
        }

        return dataImportFieldAndLabels;

    }

    /**
     * Sets custom validity on fields inside fieldsArray
     * @param fieldsArray
     * @param errorMessage
     */
    @api
    setCustomValidityOnFields( fieldsArray, errorMessage ) {

        const fields = this.template.querySelectorAll('c-ge-form-field');
        if (fields !== null && typeof fields !== 'undefined') {
            fields.forEach(f => {
                if ( fieldsArray.indexOf(f.sourceFieldAPIName)!== -1 ) {
                    f.setCustomValidity(errorMessage);
                }
            });
        }

    }

    /**
     * Get a list of fields that are required, but are null/undefined or otherwise blank in the dynamic form
     * @returns {Array} of invalid fields. If all fields are ok, the array is empty.
     */
    @api
    getInvalidFields() {
        const fields = this.template.querySelectorAll('c-ge-form-field');
        let invalidFields = [];

        fields.forEach(f => {
            if(!f.isValid()) {
                invalidFields.push(f.fieldLabel);
            }
        });

        return invalidFields;
    }

    @api
    getAllFieldsByAPIName() {
        const fields = this.template.querySelectorAll('c-ge-form-field');
        let fieldMappedByAPIName = {};

        fields.forEach(f => {
            fieldMappedByAPIName[f.sourceFieldAPIName] = f;
        });

        return fieldMappedByAPIName;
    }

    @api
    reset() {
        const widgetList = this.template.querySelectorAll('c-ge-form-widget');
        widgetList.forEach(widget => {
            widget.reset();
        });
    }

    registerCreditCardWidget() {
        if (!isUndefined(this.section)) {
            this.section.elements.forEach(element => {
                if (element.componentName === 'geFormWidgetTokenizeCard') {
                    this._hasCreditCardWidget = true;
                }
            })
        }
        if (this._hasCreditCardWidget) {
            const registerCreditCardWidgetEvent = new CustomEvent(
                'registercreditcardwidget'
            );
            this.dispatchEvent(registerCreditCardWidgetEvent)
        }

    }

    @api
    get paymentToken() {
        let widgetValues = [];
        const widgets = this.template.querySelectorAll('c-ge-form-widget');
        if (widgets !== null && typeof widgets !== 'undefined') {
            widgets.forEach(widget => {
                if (widget.isElevateTokenizeCard) {
                    widgetValues.push(widget.paymentToken);
                }
            });
        }
        return widgetValues;
    }

    @api
    get isCreditCardWidgetAvailable() {
        return this._hasCreditCardWidget;
    }
    get renderableElements() {
        if (isUndefined(this.section)) {
            return [];
        }
        return this.section.elements.filter(
            element => new GeFormElementHelper(
                element).isRenderable());
    }

    handleFormWidgetChange(event) {
        this.dispatchEvent(new CustomEvent('formwidgetchange', {detail: event.detail}));
    }

    handleFormFieldChange(event) {
        this.dispatchEvent(new CustomEvent('formfieldchange', {detail: event.detail}));
    }

}<commit_msg>Removed unused reset function in geFormSection<commit_after>import {LightningElement, api} from 'lwc';
import { isUndefined } from 'c/utilCommon';
import GeFormElementHelper from './geFormElementHelper.js';

const COLLAPSED_DISPLAY_MODE = 'collapsed';

export default class GeFormSection extends LightningElement {
    @api section;
    @api widgetData;
    @api formState;
    _hasCreditCardWidget = false;

    renderedCallback() {
        this.registerCreditCardWidget();
    }

    /**
     * Get the alternative text that represents the section expand/collapse button
     * @returns {string} containing the section expand alternative text
     */
    get altTextLabel() {
        return 'Toggle ' + this.section.label;
    }

    get isCollapsed() {
        return this.section.defaultDisplayMode === COLLAPSED_DISPLAY_MODE;
    }

    /**
     * Gets value and UI-label for the requestedFields in the section (if any)
     * @param requestedFields - Array of API Field Names to get information
     * @returns {Array} - field value and ui-label using api-field-name as key
     */
    @api
    getFieldValueAndLabel( requestedFields ) {

        const fields = this.template.querySelectorAll('c-ge-form-field');
        let dataImportFieldAndLabels = {};

        if (fields !== null && typeof fields !== 'undefined') {
            fields.forEach( field => {
                if ( requestedFields.indexOf(field.sourceFieldAPIName) !== -1 ){
                    field.clearCustomValidity();
                    dataImportFieldAndLabels = { ...dataImportFieldAndLabels, ...(field.fieldValueAndLabel) };
                }
            });
        }

        return dataImportFieldAndLabels;

    }

    /**
     * Sets custom validity on fields inside fieldsArray
     * @param fieldsArray
     * @param errorMessage
     */
    @api
    setCustomValidityOnFields( fieldsArray, errorMessage ) {

        const fields = this.template.querySelectorAll('c-ge-form-field');
        if (fields !== null && typeof fields !== 'undefined') {
            fields.forEach(f => {
                if ( fieldsArray.indexOf(f.sourceFieldAPIName)!== -1 ) {
                    f.setCustomValidity(errorMessage);
                }
            });
        }

    }

    /**
     * Get a list of fields that are required, but are null/undefined or otherwise blank in the dynamic form
     * @returns {Array} of invalid fields. If all fields are ok, the array is empty.
     */
    @api
    getInvalidFields() {
        const fields = this.template.querySelectorAll('c-ge-form-field');
        let invalidFields = [];

        fields.forEach(f => {
            if(!f.isValid()) {
                invalidFields.push(f.fieldLabel);
            }
        });

        return invalidFields;
    }

    @api
    getAllFieldsByAPIName() {
        const fields = this.template.querySelectorAll('c-ge-form-field');
        let fieldMappedByAPIName = {};

        fields.forEach(f => {
            fieldMappedByAPIName[f.sourceFieldAPIName] = f;
        });

        return fieldMappedByAPIName;
    }

    registerCreditCardWidget() {
        if (!isUndefined(this.section)) {
            this.section.elements.forEach(element => {
                if (element.componentName === 'geFormWidgetTokenizeCard') {
                    this._hasCreditCardWidget = true;
                }
            })
        }
        if (this._hasCreditCardWidget) {
            const registerCreditCardWidgetEvent = new CustomEvent(
                'registercreditcardwidget'
            );
            this.dispatchEvent(registerCreditCardWidgetEvent)
        }

    }

    @api
    get paymentToken() {
        let widgetValues = [];
        const widgets = this.template.querySelectorAll('c-ge-form-widget');
        if (widgets !== null && typeof widgets !== 'undefined') {
            widgets.forEach(widget => {
                if (widget.isElevateTokenizeCard) {
                    widgetValues.push(widget.paymentToken);
                }
            });
        }
        return widgetValues;
    }

    @api
    get isCreditCardWidgetAvailable() {
        return this._hasCreditCardWidget;
    }
    get renderableElements() {
        if (isUndefined(this.section)) {
            return [];
        }
        return this.section.elements.filter(
            element => new GeFormElementHelper(
                element).isRenderable());
    }

    handleFormWidgetChange(event) {
        this.dispatchEvent(new CustomEvent('formwidgetchange', {detail: event.detail}));
    }

    handleFormFieldChange(event) {
        this.dispatchEvent(new CustomEvent('formfieldchange', {detail: event.detail}));
    }

}<|endoftext|>


<commit_before>import {LightningElement, api, track} from 'lwc';
import {getSubsetObject, isUndefined, isNotEmpty} from "c/utilCommon";

export default class GeFormSection extends LightningElement {
    @api section;
    @api widgetData;
    @track collapsed = false;
    @track hasCreditCardWidget = false;

    renderedCallback() {
        this.registerCreditCardWidget();
        this.handleChangeNameOnCardField();
    }

    /**
     * Get the alternative text that represents the section expand/collapse button
     * @returns {string} containing the section expand alternative text
     */
    get altTextLabel() {
        return 'Toggle ' + this.section.label;
    }

    @api
    get values() {
        const fields = this.template.querySelectorAll('c-ge-form-field');
        let dataImportFieldAndValues = {};
        if(fields !== null && typeof fields !== 'undefined') {
            fields.forEach(field => {
                dataImportFieldAndValues = { ...dataImportFieldAndValues, ...(field.fieldAndValue) };
            });
        }
        return dataImportFieldAndValues;
    }

    /**
     * Gets value and UI-label for the requestedFields in the section (if any)
     * @param requestedFields - Array of API Field Names to get information
     * @returns {Array} - field value and ui-label using api-field-name as key
     */
    @api
    getFieldValueAndLabel( requestedFields ) {

        const fields = this.template.querySelectorAll('c-ge-form-field');
        let dataImportFieldAndLabels = {};

        if (fields !== null && typeof fields !== 'undefined') {
            fields.forEach( field => {
                if ( requestedFields.indexOf(field.sourceFieldAPIName) !== -1 ){
                    field.clearCustomValidity();
                    dataImportFieldAndLabels = { ...dataImportFieldAndLabels, ...(field.fieldValueAndLabel) };
                }
            });
        }

        return dataImportFieldAndLabels;

    }

    /**
     * Sets custom validity on fields inside fieldsArray
     * @param {fieldsArray},Array with sourceFieldAPIName field property
     * @param {errorMessage}, String custom error message for fields
     */
    @api
    setCustomValidityOnFields( fieldsArray, errorMessage ) {

        const fields = this.template.querySelectorAll('c-ge-form-field');
        if (fields !== null && typeof fields !== 'undefined') {
            fields.forEach(f => {
                if ( fieldsArray.indexOf(f.sourceFieldAPIName)!== -1 ) {
                    f.setCustomValidity(errorMessage);
                }
            });
        }

    }

    @api
    get widgetValues() {
        const widgets = this.template.querySelectorAll('c-ge-form-widget');
        let widgetValues = {};
        if(widgets !== null && typeof widgets !== 'undefined') {
            widgets.forEach(widget => {
                widgetValues = { ...widgetValues, ...(widget.widgetAndValues) };
            });
        }
        return widgetValues;
    }

    /**
     * Get a list of fields that are required, but are null/undefined or otherwise blank in the dynamic form
     * @returns {Array} of invalid fields. If all fields are ok, the array is empty.
     */
    @api
    getInvalidFields() {
        const fields = this.template.querySelectorAll('c-ge-form-field');
        let invalidFields = [];

        fields.forEach(f => {
            if(!f.isValid()) {
                invalidFields.push(f.fieldLabel);
            }
        });

        return invalidFields;
    }

    @api
    getAllFieldsByAPIName() {
        const fields = this.template.querySelectorAll('c-ge-form-field');
        let fieldMappedByAPIName = {};

        fields.forEach(f => {
            fieldMappedByAPIName[f.sourceFieldAPIName] = f;
        });

        return fieldMappedByAPIName;
    }

    @api
    load(data) {
        const fields = this.template.querySelectorAll('c-ge-form-field');
        fields.forEach(fieldCmp => {
            if (Object.keys(data).includes(fieldCmp.sourceFieldAPIName)) {
                fieldCmp.load(
                    getSubsetObject(
                        data,
                        [fieldCmp.sourceFieldAPIName]));
            }
        });

        const widgetList = this.template.querySelectorAll('c-ge-form-widget');
        widgetList.forEach(widget => {
            widget.load(data);
        });
    }

    @api
    reset(fieldMappingDevNames = null) {
        const fields = this.template.querySelectorAll('c-ge-form-field');
        const widgetList = this.template.querySelectorAll('c-ge-form-widget');

        fields.forEach(field => {
            if (fieldMappingDevNames) {
                // reset the fields elements related to
                // these field mappings
                if (fieldMappingDevNames.includes(
                    field.element.dataImportFieldMappingDevNames[0]
                )) {
                    field.reset();
                }
            } else {
                // reset all field elements in this section
                field.reset();
            }
        });

        widgetList.forEach(widget => {
            widget.reset();
        });
    }

    handleLookupRecordSelect(event) {
        const selectEvent = new CustomEvent(
            'lookuprecordselect',
            { detail: event.detail });
        this.dispatchEvent(selectEvent);
    }

    handleChangeDonationDonor(event) {
        const changeDonationDonorEvent = new CustomEvent(
            'changedonationdonor',
            { detail: event.detail });
        this.dispatchEvent(changeDonationDonorEvent);
    }

    /**
     * @description Inspects all fields and widgets in the section and
     *              returns a list of DataImport__c field api names used as
     *              source fields.  Helps to only send relevant data down from
     *              geFormRenderer to each section during load() flow.
     */
    @api
    get sourceFields() {
        let fields = Object.keys(this.getAllFieldsByAPIName());

        this.template.querySelectorAll('c-ge-form-widget')
            .forEach(widgetCmp => {
                if(isNotEmpty(widgetCmp.allFieldsByAPIName)){
                    fields.push(...widgetCmp.allFieldsByAPIName);
                }
            });

        return fields;
    }

    registerCreditCardWidget() {
        if (!isUndefined(this.section)) {
            this.section.elements.forEach(element => {
                if (element.componentName === 'geFormWidgetTokenizeCard') {
                    this.hasCreditCardWidget = true;
                }
            })
        }
    }

    handleChangeNameOnCardField() {
        const changeNameOnCardFieldEvent = new CustomEvent(
            'changenameoncardfield'
        );
        this.dispatchEvent(changeNameOnCardFieldEvent);
    }

    @api
    setCardHolderName(value) {
        const widgetList = this.template.querySelectorAll('c-ge-form-widget');
        widgetList.forEach(widget => {
            if (widget.isElevateTokenizeCard) {
                widget.setCardHolderName(value);
            }
        });
    }

    @api
    get isCreditCardWidgetAvailable() {
        return this.hasCreditCardWidget;
    }

    @api
    getAllFieldsByFieldAPIName() {
        const fields = this.template.querySelectorAll('c-ge-form-field');
        let fieldData = {};
        if (isNotEmpty(fields)) {
            fields.forEach(field => {
                fieldData = { ...fieldData, ...(field.fieldValueAndFieldApiName) };
            });
        }
        return fieldData;
    }

}<commit_msg>Code Styling changes<commit_after>import {LightningElement, api, track} from 'lwc';
import {getSubsetObject, isUndefined, isNotEmpty} from "c/utilCommon";

export default class GeFormSection extends LightningElement {
    @api section;
    @api widgetData;
    @track collapsed = false;
    @track hasCreditCardWidget = false;

    renderedCallback() {
        this.registerCreditCardWidget();
        this.handleChangeNameOnCardField();
    }

    /**
     * Get the alternative text that represents the section expand/collapse button
     * @returns {string} containing the section expand alternative text
     */
    get altTextLabel() {
        return 'Toggle ' + this.section.label;
    }

    @api
    get values() {
        const fields = this.template.querySelectorAll('c-ge-form-field');
        let dataImportFieldAndValues = {};
        if(fields !== null && typeof fields !== 'undefined') {
            fields.forEach(field => {
                dataImportFieldAndValues = { ...dataImportFieldAndValues, ...(field.fieldAndValue) };
            });
        }
        return dataImportFieldAndValues;
    }

    /**
     * Gets value and UI-label for the requestedFields in the section (if any)
     * @param requestedFields - Array of API Field Names to get information
     * @returns {Array} - field value and ui-label using api-field-name as key
     */
    @api
    getFieldValueAndLabel( requestedFields ) {

        const fields = this.template.querySelectorAll('c-ge-form-field');
        let dataImportFieldAndLabels = {};

        if (fields !== null && typeof fields !== 'undefined') {
            fields.forEach( field => {
                if ( requestedFields.indexOf(field.sourceFieldAPIName) !== -1 ){
                    field.clearCustomValidity();
                    dataImportFieldAndLabels = { ...dataImportFieldAndLabels, ...(field.fieldValueAndLabel) };
                }
            });
        }

        return dataImportFieldAndLabels;

    }

    /**
     * Sets custom validity on fields inside fieldsArray
     * @param {fieldsArray},Array with sourceFieldAPIName field property
     * @param {errorMessage}, String custom error message for fields
     */
    @api
    setCustomValidityOnFields( fieldsArray, errorMessage ) {

        const fields = this.template.querySelectorAll('c-ge-form-field');
        if (fields !== null && typeof fields !== 'undefined') {
            fields.forEach(f => {
                if ( fieldsArray.indexOf(f.sourceFieldAPIName)!== -1 ) {
                    f.setCustomValidity(errorMessage);
                }
            });
        }

    }

    @api
    get widgetValues() {
        const widgets = this.template.querySelectorAll('c-ge-form-widget');
        let widgetValues = {};
        if(widgets !== null && typeof widgets !== 'undefined') {
            widgets.forEach(widget => {
                widgetValues = { ...widgetValues, ...(widget.widgetAndValues) };
            });
        }
        return widgetValues;
    }

    /**
     * Get a list of fields that are required, but are null/undefined or otherwise blank in the dynamic form
     * @returns {Array} of invalid fields. If all fields are ok, the array is empty.
     */
    @api
    getInvalidFields() {
        const fields = this.template.querySelectorAll('c-ge-form-field');
        let invalidFields = [];

        fields.forEach(f => {
            if(!f.isValid()) {
                invalidFields.push(f.fieldLabel);
            }
        });

        return invalidFields;
    }

    @api
    getAllFieldsByAPIName() {
        const fields = this.template.querySelectorAll('c-ge-form-field');
        let fieldMappedByAPIName = {};

        fields.forEach(f => {
            fieldMappedByAPIName[f.sourceFieldAPIName] = f;
        });

        return fieldMappedByAPIName;
    }

    @api
    load(data) {
        const fields = this.template.querySelectorAll('c-ge-form-field');
        fields.forEach(fieldCmp => {
            if (Object.keys(data).includes(fieldCmp.sourceFieldAPIName)) {
                fieldCmp.load(
                    getSubsetObject(
                        data,
                        [fieldCmp.sourceFieldAPIName]));
            }
        });

        const widgetList = this.template.querySelectorAll('c-ge-form-widget');
        widgetList.forEach(widget => {
            widget.load(data);
        });
    }

    @api
    reset(fieldMappingDevNames = null) {
        const fields = this.template.querySelectorAll('c-ge-form-field');
        const widgetList = this.template.querySelectorAll('c-ge-form-widget');

        fields.forEach(field => {
            if (fieldMappingDevNames) {
                // reset the fields elements related to
                // these field mappings
                if (fieldMappingDevNames.includes(
                    field.element.dataImportFieldMappingDevNames[0]
                )) {
                    field.reset();
                }
            } else {
                // reset all field elements in this section
                field.reset();
            }
        });

        widgetList.forEach(widget => {
            widget.reset();
        });
    }

    handleLookupRecordSelect(event) {
        const selectEvent = new CustomEvent(
            'lookuprecordselect',
            { detail: event.detail });
        this.dispatchEvent(selectEvent);
    }

    handleChangeDonationDonor(event) {
        const changeDonationDonorEvent = new CustomEvent(
            'changedonationdonor',
            { detail: event.detail });
        this.dispatchEvent(changeDonationDonorEvent);
    }

    /**
     * @description Inspects all fields and widgets in the section and
     *              returns a list of DataImport__c field api names used as
     *              source fields.  Helps to only send relevant data down from
     *              geFormRenderer to each section during load() flow.
     */
    @api
    get sourceFields() {
        let fields = Object.keys(this.getAllFieldsByAPIName());

        this.template.querySelectorAll('c-ge-form-widget')
            .forEach(widgetCmp => {
                if (isNotEmpty(widgetCmp.allFieldsByAPIName)) {
                    fields.push(...widgetCmp.allFieldsByAPIName);
                }
            });

        return fields;
    }

    registerCreditCardWidget() {
        if (!isUndefined(this.section)) {
            this.section.elements.forEach(element => {
                if (element.componentName === 'geFormWidgetTokenizeCard') {
                    this.hasCreditCardWidget = true;
                }
            })
        }
    }

    handleChangeNameOnCardField() {
        const changeNameOnCardFieldEvent = new CustomEvent(
            'changenameoncardfield'
        );
        this.dispatchEvent(changeNameOnCardFieldEvent);
    }

    @api
    setCardHolderName(value) {
        const widgetList = this.template.querySelectorAll('c-ge-form-widget');
        widgetList.forEach(widget => {
            if (widget.isElevateTokenizeCard) {
                widget.setCardHolderName(value);
            }
        });
    }

    @api
    get isCreditCardWidgetAvailable() {
        return this.hasCreditCardWidget;
    }

    @api
    getAllFieldsByFieldAPIName() {
        const fields = this.template.querySelectorAll('c-ge-form-field');
        let fieldData = {};
        if (isNotEmpty(fields)) {
            fields.forEach(field => {
                fieldData = { ...fieldData, ...(field.fieldValueAndFieldApiName) };
            });
        }
        return fieldData;
    }

}<|endoftext|>