<commit_before>var _ = require('lodash');
var Profile = function Profile() {
    var self = this;
    var _votingHasBegun = false;
    this.candidateMap = {};
    this.dominanceMatrix = [];
    this.data = [];

    function initializeMatrix(arr){
      var matrix = [];

          for(var i = 0; i < arr.length;i++){
              matrix.push(_.range(0,arr.length,0));
          }

        return matrix;
      }

     var updateDominanceMatrix = function updateDominanceMatrix(ordering){
	var unwrittenCandidates = _.difference(self.candidates,ordering);

	var numOrdering = _.map(ordering, function(item){
	    return self.candidateMap[item];
	});
	for(var i=0;i < ordering.length;i++){
	    for(var j=i; j < ordering.length;j++){
	       if(i != j){
	           self.dominanceMatrix[numOrdering[i]][numOrdering[j]]++;
	       }
	    }
	}

	for(var ii=0; ii < unwrittenCandidates.length;ii++){
	    var unwritten = self.candidateMap[unwrittenCandidates[ii]];
	    for(var jj=0; jj < numOrdering.length;jj++){
	        self.dominanceMatrix[numOrdering[jj]][unwritten]++;
	   }
	}

     };

    this.setCandidates = function setCandidates(nominees){
	if (_votingHasBegun) return;
	self.candidates = nominees;
	self.dominanceMatrix = initializeMatrix(nominees);
        self.candidateMap = _.invert(nominees);
    };

    this.find = function find(ordering) {
	var key = ordering.join("_");
	return  _.where(this.data,{"key":key});
    };

    this.vote = function vote(ordering) {

	_votingHasBegun = true;

	var key = ordering.join("_");
	var priorVote = _.where(this.data,{"key":key})[0];

	updateDominanceMatrix(ordering);

   	if (priorVote) {
	    priorVote.numVotes++;
	    return;
	}

	var newVote = {
		    "key":key,
	            "ordering":ordering,
		    "numVotes":1,
		    };

        this.data.push(newVote);
       };

    this.each = function each(visitFunc){
    _.each(this.data,function(ordering){
        _.each(ordering.ordering,function(voteValue,index){
             visitFunc(ordering,voteValue,index);
        });
    });
  };

   this.score = require('./scoring.js').bind(this);
};

module.exports = Profile;

<commit_msg>adds proof of concept for mixin functionality<commit_after>var _ = require('lodash');
var Profile = function Profile() {
    var self = this;

    var _votingHasBegun = false;
    this.candidateMap = {};
    this.data = [];

    this.dominanceMatrix = undefined;
    this.initializeMatrix = _.noop;
    this.updateDominanceMatrix = _.noop;

    this.approvalMatrix = undefined;
    this.approvalData = _.noop;

    this.setCandidates = function setCandidates(nominees){
	if (_votingHasBegun) return;
	self.candidates = nominees;
	self.dominanceMatrix = self.initializeMatrix(nominees);
        self.candidateMap = _.invert(nominees);
    };

    this.find = function find(ordering) {
	var key = ordering.join("_");
	return  _.where(this.data,{"key":key});
    };

    this.vote = function vote(ordering) {

	_votingHasBegun = true;

	var key = ordering.join("_");
	var priorVote = _.where(this.data,{"key":key})[0];

	self.updateDominanceMatrix(ordering);

   	if (priorVote) {
	    priorVote.numVotes++;
	    return;
	}

	var newVote = {
		    "key":key,
	            "ordering":ordering,
		    "numVotes":1,
		    };

        this.data.push(newVote);

       };

    this.each = function each(visitFunc){
    _.each(this.data,function(ordering){
        _.each(ordering.ordering,function(voteValue,index){
             visitFunc(ordering,voteValue,index);
        });
    });
  };

   this.score = require('./scoring.js').bind(this);
};

module.exports = Profile;

var p = new Profile();
p.setCandidates(["a","b"]);
p.vote(["a","b"]);

_.mixin(p,{"initializeMatrix":
    function initializeMatrix(arr){
      var matrix = [];

          for(var i = 0; i < arr.length;i++){
              matrix.push(_.range(0,arr.length,0));
          }

        return matrix;
      }

});
console.log(p);
/*
     var updateDominanceMatrix = function updateDominanceMatrix(ordering){
	var unwrittenCandidates = _.difference(self.candidates,ordering);

	var numOrdering = _.map(ordering, function(item){
	    return self.candidateMap[item];
	});
	for(var i=0;i < ordering.length;i++){
	    for(var j=i; j < ordering.length;j++){
	       if(i != j){
	           self.dominanceMatrix[numOrdering[i]][numOrdering[j]]++;
	       }
	    }
	}

	for(var ii=0; ii < unwrittenCandidates.length;ii++){
	    var unwritten = self.candidateMap[unwrittenCandidates[ii]];
	    for(var jj=0; jj < numOrdering.length;jj++){
	        self.dominanceMatrix[numOrdering[jj]][unwritten]++;
	   }
	}

     };

    function initializeMatrix(arr){
      var matrix = [];

          for(var i = 0; i < arr.length;i++){
              matrix.push(_.range(0,arr.length,0));
          }

        return matrix;
      }

*/
<|endoftext|>


<commit_before>var _ = require('lodash')
var airbnb = require('eslint-config-airbnb')

module.exports = _.merge(airbnb, {
  // "extends": "airbnb",
  "rules": {
    "brace-style": [                      // http://eslint.org/docs/rules/brace-style
      2,
      "stroustrup", {
        "allowSingleLine": true
      }
    ],
    "arrow-body-style": 0,
    "arrow-parens": 0,
    "camelcase": 0,
    "class-methods-use-this": 0,
    "class-methods-use-this": 0,
    "consistent-return": 0,
    "consistent-return": 0,
    "eqeqeq": 0,
    "function-paren-newline": 0,
    "global-require": 0,
    "indent": [2, 2, {"SwitchCase": 1}],
    "max-len": 0,
    "newline-per-chained-call": 0,
    "no-alert": 0,
    "no-restricted-globals": 0,
    "no-await-in-loop": 0,
    "no-case-declarations": 0,
    "no-confusing-arrow": 0,
    "no-confusing-arrow": 0,
    "no-confusing-arrow": 0,
    "no-console": 0,
    "no-empty": 0,
    "no-mixed-operators": 0,
    "no-multi-assign": 0,
    "no-multi-spaces": 0,
    "no-nested-ternary": 0,
    "no-param-reassign": 0,
    "no-plusplus": 0,
    "no-prototype-builtins": 0,
    "no-restricted-syntax": 0,
    "no-return-assign": 0,
    "no-return-assign": 0,
    "no-shadow": 0,
    "no-underscore-dangle": 0,
    "no-unexpected-multiline": 2,
    "no-unneeded-ternary": 0,
    "no-unused-expressions": 0,
    "object-curly-newline": 0,
    "object-curly-spacing": [0],
    "padded-blocks": 0,
    "prefer-destructuring": 0,
    "prefer-spread": 0,
    "prefer-template": 0,
    "quotes": [2, "single", {"allowTemplateLiterals": true}],
    "semi": [2, "never"],
    "space-before-function-paren": 0,
    "space-infix-ops": 0,
    "spaced-comment": 0,

    "import/no-named-as-default": 0,
    "import/no-named-as-default-member": 0,
    "import/no-extraneous-dependencies": 0,
    "import/prefer-default-export": 0,
    "import/newline-after-import": 0,

    "react/forbid-prop-types": 0,
    "react/jsx-filename-extension": 0,
    "react/jsx-first-prop-new-line": 0,
    "react/jsx-max-props-per-line": 0,
    "react/no-mutable-exports": 0,
    "react/no-unescaped-entities": 0,
    "react/prefer-stateless-function": 0,
    "react/require-default-props": 0,
    "react/require-default-props": 0,
    "react/sort-comp": 0,

    "jsx-a11y/accessible-emoji": 0,
    "jsx-a11y/anchor-is-valid": 0,
    "jsx-a11y/click-events-have-key-events": 0,
    "jsx-a11y/label-has-for": 0,
  }
})
<commit_msg>disable guard-for-in<commit_after>var _ = require('lodash')
var airbnb = require('eslint-config-airbnb')

module.exports = _.merge(airbnb, {
  // "extends": "airbnb",
  "rules": {
    "brace-style": [                      // http://eslint.org/docs/rules/brace-style
      2,
      "stroustrup", {
        "allowSingleLine": true
      }
    ],
    "arrow-body-style": 0,
    "arrow-parens": 0,
    "camelcase": 0,
    "class-methods-use-this": 0,
    "class-methods-use-this": 0,
    "consistent-return": 0,
    "consistent-return": 0,
    "eqeqeq": 0,
    "function-paren-newline": 0,
    "global-require": 0,
    "guard-for-in": 0,
    "indent": [2, 2, {"SwitchCase": 1}],
    "max-len": 0,
    "newline-per-chained-call": 0,
    "no-alert": 0,
    "no-await-in-loop": 0,
    "no-case-declarations": 0,
    "no-confusing-arrow": 0,
    "no-confusing-arrow": 0,
    "no-confusing-arrow": 0,
    "no-console": 0,
    "no-empty": 0,
    "no-mixed-operators": 0,
    "no-multi-assign": 0,
    "no-multi-spaces": 0,
    "no-nested-ternary": 0,
    "no-param-reassign": 0,
    "no-plusplus": 0,
    "no-prototype-builtins": 0,
    "no-restricted-globals": 0,
    "no-restricted-syntax": 0,
    "no-return-assign": 0,
    "no-return-assign": 0,
    "no-shadow": 0,
    "no-underscore-dangle": 0,
    "no-unexpected-multiline": 2,
    "no-unneeded-ternary": 0,
    "no-unused-expressions": 0,
    "object-curly-newline": 0,
    "object-curly-spacing": [0],
    "padded-blocks": 0,
    "prefer-destructuring": 0,
    "prefer-spread": 0,
    "prefer-template": 0,
    "quotes": [2, "single", {"allowTemplateLiterals": true}],
    "semi": [2, "never"],
    "space-before-function-paren": 0,
    "space-infix-ops": 0,
    "spaced-comment": 0,

    "import/no-named-as-default": 0,
    "import/no-named-as-default-member": 0,
    "import/no-extraneous-dependencies": 0,
    "import/prefer-default-export": 0,
    "import/newline-after-import": 0,

    "react/forbid-prop-types": 0,
    "react/jsx-filename-extension": 0,
    "react/jsx-first-prop-new-line": 0,
    "react/jsx-max-props-per-line": 0,
    "react/no-mutable-exports": 0,
    "react/no-unescaped-entities": 0,
    "react/prefer-stateless-function": 0,
    "react/require-default-props": 0,
    "react/require-default-props": 0,
    "react/sort-comp": 0,

    "jsx-a11y/accessible-emoji": 0,
    "jsx-a11y/anchor-is-valid": 0,
    "jsx-a11y/click-events-have-key-events": 0,
    "jsx-a11y/label-has-for": 0,
  }
})
<|endoftext|>


<commit_before>'use strict';

var path = require('path');
var util = require('util');
var defaults = require('object.defaults');
var delegate = require('delegate-properties');
var extend = require('extend-shallow');
var pascal = require('pascalcase');
var lazy = require('lazy-cache')(require);

/**
 * Lazily required module dependencies
 */

lazy('through2', 'through');
lazy('template-config', 'config');
lazy('parser-front-matter', 'matter');
lazy('vinyl-fs', 'vfs');
lazy('vinyl', 'Vinyl');
lazy('to-vinyl');
lazy('dest');
lazy('inflection');

/**
 * Extend `Assemble`
 */

// var Boilerplate = lazy('boilerplate');
// var Generate = lazy('generate');
// var Scaffold = lazy('scaffold');
var Composer = require('composer');
var Template = require('template');
// var Snippet = lazy('snippet');

/**
 * Create an instance of `Assemble` with the given `options`.
 *
 * ```js
 * var Assemble = require('assemble');
 * var app = new Assemble();
 * ```
 *
 * @param {Object} `options`
 * @api public
 */

function Assemble(options) {
  if (!(this instanceof Assemble)) {
    return new Assemble(options);
  }
  Template.apply(this, arguments);
  Composer.call(this, 'assemble');
}

Template.extend(Assemble);
extend(Assemble.prototype, Composer.prototype);

/**
 * Default configuration
 */

delegate(Assemble.prototype, {
  constructor: Assemble,

  defaultConfig: function() {
    this.mixin('config', lazy.config(this));

    var exts = ['hbs', 'html', 'md'];
    this.engine(exts, require('engine-handlebars'));

    this.onLoad(/\.(hbs|md|html)$/, function (view, next) {
      lazy.matter.parse(view, next);
    });

    this.preLayout(/./, function (view, next) {
      if (/\.(hbs|md|html)$/.test(view.path)) {
        if (!view.layout) view.layout = view.locals.layout;
        if (!view.layout) view.layout = view.data.layout;
      } else {
        view.layout = null;
      }
      next();
    });

    this.preRender(/\.(hbs|md|html)$/, function (view, next) {
      extend(view.data, view.parsePath())
    });

    this.create('partials', {
      viewType: ['partial'],
      renameKey: function (fp) {
        return path.basename(fp, path.extname(fp));
      }
    });

    this.create('layouts', {
      viewType: ['layout'],
      renameKey: function (fp) {
        return path.basename(fp, path.extname(fp));
      }
    });

    this.create('pages', {
      renameKey: function (fp) {
        return fp;
      }
    });

    this.loaded = true;
  },

  // boilerplate: function (name, config) {
  //   this.boilerplates[name] = new Boilerplate(config);
  //   return this;
  // },

  // scaffold: function (name, config) {
  //   this.scaffolds[name] = new Scaffold(config);
  //   return this;
  // },

  // snippet: function (name, config) {
  //   this.snippets[name] = new Snippet(config);
  //   return this;
  // },

  /**
   * Glob patterns or filepaths to source files.
   *
   * ```js
   * app.src('src/*.hbs', {layout: 'default'});
   * ```
   *
   * @param {String|Array} `glob` Glob patterns or file paths to source files.
   * @param {Object} `options` Options or locals to merge into the context and/or pass to `src` plugins
   * @api public
   */

  src: function (glob, options) {
    if (!this.loaded) this.defaultConfig();
    var name = this.taskName();
    // TODO: should template use camelcase?
    this[name](glob, options);
    var stream = this.toStream(name);
    process.nextTick(function () {
      stream.end();
    });
    return stream;
  },

  /**
   * Specify a destination for processed files.
   *
   * ```js
   * app.dest('dist/');
   * ```
   *
   * @param {String|Function} `dest` File path or rename function.
   * @param {Object} `options` Options and locals to pass to `dest` plugins
   * @api public
   */

  dest: function (/*dest, options*/) {
    return lazy.dest.apply(lazy.dest, arguments);
  },

  task: function (name) {
    var task = Composer.prototype.task;
    if (!this.loaded) this.defaultConfig();
    var key = 'task_' + name;
    this.create(key, {
      renameKey: function (fp) {
        return fp;
      }
    });
    return task.apply(this, arguments);
  },

  /**
   * Copy files with the given glob `patterns` to the specified `destDir`.
   *
   * ```js
   * app.task('assets', function() {
   *   app.copy('assets/**', 'dist/');
   * });
   * ```
   *
   * @param {String|Array} `patterns` Glob patterns of files to copy.
   * @param  {String|Function} `destDir` Desination directory.
   * @return {Stream} Stream, to continue processing if necessary.
   * @api public
   */

  copy: function(patterns, destDir, opts) {
    return lazy.vfs.src(patterns, opts)
      .pipe(lazy.vfs.dest(destDir, opts));
  },

  /**
   * Push a view collection into a vinyl stream.
   *
   * @param {String} `plural`
   * @param {Object} `locals`
   * @return {Stream}
   * @api public
   */

  toStream: function (plural, locals) {
    if (!this.views.hasOwnProperty(plural)) {
      plural = this.inflections[plural];
    }
    var views = this.views[plural] || {};
    return lazy.through.obj(function (file, enc, cb) {
      this.push(file);
      return cb();
    }, function (cb) {
      Object.keys(views).forEach(function (key) {
        var view = views[key];
        var file = lazy.toVinyl(view);
        this.push(file);
      }.bind(this));
      cb();
    });
  },

  taskName: function () {
    var task = this.session.get('task');
    return (task ? 'task_' + task.name : 'file');
  },

  /**
   * Render a vinyl file.
   *
   * @param  {Object} file
   * @param  {Function} cb Callback
   * @return {Object}
   * @api public
   */

  renderFile: function (locals) {
    var name = this.taskName();
    var collection = this.views[name];
    var self = this;

    return lazy.through.obj(function (file, enc, cb) {
      if (typeof locals === 'function') {
        cb = locals;
        locals = {};
      }

      collection.set(file.path, file);
      self.render(collection.get(file.path), locals, function (err, res) {
        if (err) return cb(err);
        res.contents = new Buffer(res.content);
        file = new lazy.Vinyl(res);
        cb(null, file);
      });
    });
  }
});

/**
 * Static method for allowing other classes to inherit
 * both prototype and static methods from `Assemble`.
 *
 * ```js
 * function MyApp(options) {...}
 * Assemble.extend(MyApp);
 * ```
 *
 * @param  {Object} `Ctor` Constructor function to extend with `Assemble`
 * @return {undefined}
 * @api public
 */

Assemble.extend = function(Ctor) {
  util.inherits(Ctor, Assemble);
  delegate(Ctor, Assemble);
};

/**
 * Expose an instance of `Assemble`
 */

module.exports = new Assemble();

/**
 * Allow users to instantiate `Assemble`.
 */

module.exports.Assemble = Assemble;
<commit_msg>simplifying adding a view to a collection<commit_after>'use strict';

var path = require('path');
var util = require('util');
var defaults = require('object.defaults');
var delegate = require('delegate-properties');
var extend = require('extend-shallow');
var pascal = require('pascalcase');
var lazy = require('lazy-cache')(require);

/**
 * Lazily required module dependencies
 */

lazy('through2', 'through');
lazy('template-config', 'config');
lazy('parser-front-matter', 'matter');
lazy('vinyl-fs', 'vfs');
lazy('vinyl', 'Vinyl');
lazy('to-vinyl');
lazy('dest');
lazy('inflection');

/**
 * Extend `Assemble`
 */

// var Boilerplate = lazy('boilerplate');
// var Generate = lazy('generate');
// var Scaffold = lazy('scaffold');
var Composer = require('composer');
var Template = require('template');
// var Snippet = lazy('snippet');

/**
 * Create an instance of `Assemble` with the given `options`.
 *
 * ```js
 * var Assemble = require('assemble');
 * var app = new Assemble();
 * ```
 *
 * @param {Object} `options`
 * @api public
 */

function Assemble(options) {
  if (!(this instanceof Assemble)) {
    return new Assemble(options);
  }
  Template.apply(this, arguments);
  Composer.call(this, 'assemble');
}

Template.extend(Assemble);
extend(Assemble.prototype, Composer.prototype);

/**
 * Default configuration
 */

delegate(Assemble.prototype, {
  constructor: Assemble,

  defaultConfig: function() {
    this.mixin('config', lazy.config(this));

    var exts = ['hbs', 'html', 'md'];
    this.engine(exts, require('engine-handlebars'));

    this.onLoad(/\.(hbs|md|html)$/, function (view, next) {
      lazy.matter.parse(view, next);
    });

    this.preLayout(/./, function (view, next) {
      if (/\.(hbs|md|html)$/.test(view.path)) {
        if (!view.layout) view.layout = view.locals.layout;
        if (!view.layout) view.layout = view.data.layout;
      } else {
        view.layout = null;
      }
      next();
    });

    this.preRender(/\.(hbs|md|html)$/, function (view, next) {
      extend(view.data, view.parsePath())
    });

    this.create('partials', {
      viewType: ['partial'],
      renameKey: function (fp) {
        return path.basename(fp, path.extname(fp));
      }
    });

    this.create('layouts', {
      viewType: ['layout'],
      renameKey: function (fp) {
        return path.basename(fp, path.extname(fp));
      }
    });

    this.create('pages', {
      renameKey: function (fp) {
        return fp;
      }
    });

    this.loaded = true;
  },

  // boilerplate: function (name, config) {
  //   this.boilerplates[name] = new Boilerplate(config);
  //   return this;
  // },

  // scaffold: function (name, config) {
  //   this.scaffolds[name] = new Scaffold(config);
  //   return this;
  // },

  // snippet: function (name, config) {
  //   this.snippets[name] = new Snippet(config);
  //   return this;
  // },

  /**
   * Glob patterns or filepaths to source files.
   *
   * ```js
   * app.src('src/*.hbs', {layout: 'default'});
   * ```
   *
   * @param {String|Array} `glob` Glob patterns or file paths to source files.
   * @param {Object} `options` Options or locals to merge into the context and/or pass to `src` plugins
   * @api public
   */

  src: function (glob, options) {
    if (!this.loaded) this.defaultConfig();
    return lazy.vfs.src.apply(lazy.vfs, arguments);
    // var name = this.taskName();
    // // TODO: should template use camelcase?
    // this[name](glob, options);
    // var stream = this.toStream(name);
    // process.nextTick(function () {
    //   stream.end();
    // });
    // return stream;
  },

  /**
   * Specify a destination for processed files.
   *
   * ```js
   * app.dest('dist/');
   * ```
   *
   * @param {String|Function} `dest` File path or rename function.
   * @param {Object} `options` Options and locals to pass to `dest` plugins
   * @api public
   */

  dest: function (/*dest, options*/) {
    return lazy.dest.apply(lazy.dest, arguments);
  },

  task: function (name) {
    var task = Composer.prototype.task;
    if (!this.loaded) this.defaultConfig();
    var key = 'task_' + name;
    this.create(key, {
      renameKey: function (fp) {
        return fp;
      }
    });
    return task.apply(this, arguments);
  },

  /**
   * Copy files with the given glob `patterns` to the specified `destDir`.
   *
   * ```js
   * app.task('assets', function() {
   *   app.copy('assets/**', 'dist/');
   * });
   * ```
   *
   * @param {String|Array} `patterns` Glob patterns of files to copy.
   * @param  {String|Function} `destDir` Desination directory.
   * @return {Stream} Stream, to continue processing if necessary.
   * @api public
   */

  copy: function(patterns, destDir, opts) {
    return lazy.vfs.src(patterns, opts)
      .pipe(lazy.vfs.dest(destDir, opts));
  },

  /**
   * Push a view collection into a vinyl stream.
   *
   * @param {String} `plural`
   * @param {Object} `locals`
   * @return {Stream}
   * @api public
   */

  toStream: function (plural, locals) {
    if (!this.views.hasOwnProperty(plural)) {
      plural = this.inflections[plural];
    }
    var views = this.views[plural] || {};
    return lazy.through.obj(function (file, enc, cb) {
      this.push(file);
      return cb();
    }, function (cb) {
      Object.keys(views).forEach(function (key) {
        var view = views[key];
        var file = lazy.toVinyl(view);
        this.push(file);
      }.bind(this));
      cb();
    });
  },

  taskName: function () {
    var task = this.session.get('task');
    return (task ? 'task_' + task.name : 'file');
  },

  /**
   * Render a vinyl file.
   *
   * @param  {Object} file
   * @param  {Function} cb Callback
   * @return {Object}
   * @api public
   */

  renderFile: function (locals) {
    var name = this.taskName();
    var self = this;

    return lazy.through.obj(function (file, enc, cb) {
      if (typeof locals === 'function') {
        cb = locals;
        locals = {};
      }
      self[name].addView(file.path, file);
      var view = self[name].get(file.path);
      self.render(view, locals, function (err, res) {
        if (err) return cb(err);
        res.contents = new Buffer(res.content);
        file = new lazy.Vinyl(res);
        cb(null, file);
      });
    });
  }
});

/**
 * Static method for allowing other classes to inherit
 * both prototype and static methods from `Assemble`.
 *
 * ```js
 * function MyApp(options) {...}
 * Assemble.extend(MyApp);
 * ```
 *
 * @param  {Object} `Ctor` Constructor function to extend with `Assemble`
 * @return {undefined}
 * @api public
 */

Assemble.extend = function(Ctor) {
  util.inherits(Ctor, Assemble);
  delegate(Ctor, Assemble);
};

/**
 * Expose an instance of `Assemble`
 */

module.exports = new Assemble();

/**
 * Allow users to instantiate `Assemble`.
 */

module.exports.Assemble = Assemble;
<|endoftext|>


<commit_before>/*

This file contains the main logging logic.
Upon installation of this module, a file named log-err.js is created in the root directory.
API entry points listed there are logged depending upon their enabled logging level.

API logging structure :
trace : 1,
error : 2,
query : 3
req   : 4,
res   : 5

The desired logging level is called from within the function which get logged onto the console if its
logging is enabled.

 */

var fs       = require('fs');

exports.trace       = trace;

exports.error       = error;

exports.request     = request;

exports.response    = response;

exports.query       = query;

function log(level, parameters){

    var _loggerObject    =  parameters[0];

    var _moduleName      =  _loggerObject.moduleInfo;

    var _apiName         =  _loggerObject.apiInfo;

    var _logFile = require('./log-err.js');

    var _logParams  =  parameters;

    var _logObject = _logFile[_moduleName][_apiName];

    var stream = process.stdout;

    if(parseInt(_logObject[level])){

        printer(stream, _moduleName, _apiName, _logParams);

    }

    /*

    if(_logObject.trace){

        printer(stream, _apiName, _logParams);

    }else if(_logObject.error){

        //LOG ERROR HERE

    }else if(_logObject.query){

        //LOG QUERY HERE

    }else if(_logObject.req){

        //LOG REQUESTS HERE

    }else if(_logObject.res){

        //LOG RESPONSE HERE

    }

    */
}

function trace(/* arguments */){

    log('trace', arguments);

}

function error(/* arguments */){

    log('error', arguments);

}

function request(/* arguments */){

    log('request', arguments);

}

function response(/* arguments */){

    log('response', arguments);

}

function query(/* arguments */){

    log('query', arguments);

}

function printer(stream, _moduleName, _apiName, _logParams){

    for(var i = 0; i < _logParams.length; i++){

        stream.write(_moduleName + ' | ' + _apiName + ' | ' + JSON.stringify(_logParams[i]) + '\n');

    }

}

function createFile(){
    var _counter = 0;
    var _path    = './log-err.js';

    return function(){
        if(_counter <= 1){
            _counter++;
            fs.open(_path, 'wx', (err, fd) => {
                if(err){
                    if(err.code == "EEXIST"){
                        return;
                    }
                    console.log(err.message);
                }

                fs.close(fd, (err) => {
                    if(err){
                        console.log(err.message);
                    }
                });
            });
        }
    }
}

var _createOutputFile = createFile();

_createOutputFile();<commit_msg>dynamic reloading basic<commit_after>/*

This file contains the main logging logic.

API logging structure :
trace : 1,
error : 2,
query : 3
req   : 4,
res   : 5

The desired logging level is called from within the function which get logged onto the console if its
logging is enabled.

 */

var fs              = require('fs');

_path               = "";

exports.trace       = trace;

exports.error       = error;

exports.request     = request;

exports.response    = response;

exports.query       = query;

exports.setPath     = setPath;

function log(level, parameters){

    var _loggerObject    =  parameters[0];

    var _moduleName      =  _loggerObject.moduleInfo;

    var _apiName         =  _loggerObject.apiInfo;

    delete require.cache[require.resolve(_path)];

    var _logFile         =  require(_path);

    var _logParams       =  parameters;

    var _logObject       = _logFile[_moduleName][_apiName];

    var stream = process.stdout;

    if(parseInt(_logObject[level])){

        printer(stream, _moduleName, _apiName, _logParams);

    }

    /*

    if(_logObject.trace){

        printer(stream, _apiName, _logParams);

    }else if(_logObject.error){

        //LOG ERROR HERE

    }else if(_logObject.query){

        //LOG QUERY HERE

    }else if(_logObject.req){

        //LOG REQUESTS HERE

    }else if(_logObject.res){

        //LOG RESPONSE HERE

    }

    */
}

function trace(/* arguments */){

    log('trace', arguments);

}

function error(/* arguments */){

    log('error', arguments);

}

function request(/* arguments */){

    log('request', arguments);

}

function response(/* arguments */){

    log('response', arguments);

}

function query(/* arguments */){

    log('query', arguments);

}

function setPath(root, path){

    /*
        SET GLOBAL PATH VARIABLE
    */
    _path = root + '/' + path;

    _createOutputFile();

}

function printer(stream, _moduleName, _apiName, _logParams){

    for(var i = 0; i < _logParams.length; i++){

        stream.write(_moduleName + ' | ' + _apiName + ' | ' + JSON.stringify(_logParams[i]) + '\n');

    }

}

function createFile(){
    var _counter = 0;

    return function(){
        if(_counter <= 1){
            _counter++;
            fs.open(_path, 'wx', (err, fd) => {
                if(err){
                    if(err.code == "EEXIST"){
                        return;
                    }
                    console.log(err.message);
                }

                fs.close(fd, (err) => {
                    if(err){
                        console.log(err.message);
                    }
                });
            });
        }
    }
}

var _createOutputFile = createFile();<|endoftext|>


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

module.exports = {
  name: 'ember-cli-deploy-yapp-pack',
  getConfiguration: function(prefix, appName, deployTarget) {
    var Promise = require('ember-cli/lib/ext/promise');

    var VALID_DEPLOY_TARGETS = [
      'dev',
      'devindex',
      'qa',
      'prod'
    ];
    var ENV = {};
    ENV.build = {};
    ENV.gzip = {};
    ENV.redis = {
      allowOverwrite: true,
      keyPrefix: prefix + ':index'
    };
    ENV.s3 = {
      prefix: prefix,
      region: 'us-east-1'
    };
    ENV.slack = {
      webhookURL: process.env.YAPP_SLACK_TECH_CHANNEL_WEBHOOK,
      didDeploy:function(){},
      didFail:function(){}
    };
    ENV.pipeline = {};

    if (VALID_DEPLOY_TARGETS.indexOf(deployTarget) === -1) {
      throw new Error('Invalid deployTarget ' + deployTarget);
    }

    if (deployTarget === 'dev') {
      ENV.build.environment = 'development';
      ENV.redis.revisionKey = 'dev';
      ENV.redis.url = process.env.YAPP_REDIS_URL_DEVELOPMENT || 'redis://0.0.0.0:6379/';
      ENV.pipeline.disabled = {
        allExcept: ['build', 'redis']
      };
    }

    if (deployTarget === 'devindex') {
      ENV.pipeline.activateOnDeploy = true;
      ENV.build.environment = 'development';
      ENV.redis.distDir = function(context) {
        return context.commandOptions.buildDir || 'dist';
      };
      ENV.redis.revisionKey = 'dev';
      ENV.redis.url = process.env.YAPP_REDIS_URL_DEVELOPMENT || 'redis://0.0.0.0:6379/';
      ENV.pipeline.disabled = { // special case to support postBuild and `npm run dev:index` usage
        allExcept: ['redis']
      };
    }

    var domain;
    var herokuAppName;
    if (deployTarget === 'qa') {
      ENV.s3.bucket = 'yapp-assets';
      ENV.redis.url = process.env.REDISTOGO_URL; // optional, falls back to reading from heroku below
      domain = "www.yappqa.us";
      herokuAppName = 'qa-yapp-cedar';
    }

    if (deployTarget === 'prod') {
      ENV.s3.bucket = 'yapp-assets';
      ENV.redis.url = process.env.REDISTOGO_URL; // optional, falls back to reading from heroku below
      domain = "www.yapp.us";
      herokuAppName = 'yapp-cedar';
    }

    if (deployTarget === 'qa' || deployTarget === 'prod') {
      ENV.build.environment = 'production';
      ENV.s3.accessKeyId = process.env.YAPP_AWS_KEY;
      ENV.s3.secretAccessKey = process.env.YAPP_AWS_SECRET;
      ENV.slack.didDeploy = function(context) {
        return function(slack){
          var message;
          var revisionKey = context.revisionData.revisionKey;
          if (revisionKey && !context.revisionData.activatedRevisionKey) {
            message = "Deployed " + appName + " to " + process.env.DEPLOY_TARGET + " but did not activate it.\n"
                 + "Preview: https://" + domain + "/" + prefix + "/?manifest_id=" + revisionKey + "\n"
                 + "Activate: `ember deploy:activate " + process.env.DEPLOY_TARGET + ' --revision='+ revisionKey + "`\n";
          } else {
            message = 'Deployed and activated ' + appName + ' to ' + process.env.DEPLOY_TARGET + ' (revision ' + revisionKey + ')';
          }
          return slack.notify(message);
        };
      };
      ENV.slack.didActivate = function(context) {
        if (context.commandOptions.revision) {
          return function(slack){
            var message = "Activated " + appName + " revision on " + process.env.DEPLOY_TARGET + ": " + context.revisionData.activatedRevisionKey + "\n";
            return slack.notify(message);
          };
        }
      };
      ENV.redis.didDeployMessage = function(context) {
        if (context.revisionData.revisionKey && !context.revisionData.activatedRevisionKey) {
          var revisionKey = context.revisionData.revisionKey;
          return "Deployed but did not activate revision " + revisionKey + ".\n"
               + "To preview:\n"
               + "https://" + domain + "/" + prefix + "/?manifest_id=" + revisionKey + "\n"
               + "To activate:\n"
               + "ember deploy:activate " + process.env.DEPLOY_TARGET + ' --revision='+ revisionKey + "\n";
        }
      };
    }

    return Promise.resolve().then(function(){
      if (deployTarget === 'qa' || deployTarget === 'prod') {
        if (!ENV.redis.url || ENV.redis.url === '') {
          return new Promise(function(resolve, reject){
            var exec = require('child_process').exec;
            exec('heroku config:get REDISTOGO_URL --app ' + herokuAppName, function (error, stdout, stderr) {
              ENV.redis.url = stdout.replace(/\n/, '').replace(/\/\/redistogo:/, '//:');
              resolve(ENV);
            });
          });
        }
      }
      return ENV;
    });
  }
};
<commit_msg>Tweak slack message for easier scanning<commit_after>/* jshint node: true */
'use strict';

module.exports = {
  name: 'ember-cli-deploy-yapp-pack',
  getConfiguration: function(prefix, appName, deployTarget) {
    var Promise = require('ember-cli/lib/ext/promise');

    var VALID_DEPLOY_TARGETS = [
      'dev',
      'devindex',
      'qa',
      'prod'
    ];
    var ENV = {};
    ENV.build = {};
    ENV.gzip = {};
    ENV.redis = {
      allowOverwrite: true,
      keyPrefix: prefix + ':index'
    };
    ENV.s3 = {
      prefix: prefix,
      region: 'us-east-1'
    };
    ENV.slack = {
      webhookURL: process.env.YAPP_SLACK_TECH_CHANNEL_WEBHOOK,
      didDeploy:function(){},
      didFail:function(){}
    };
    ENV.pipeline = {};

    if (VALID_DEPLOY_TARGETS.indexOf(deployTarget) === -1) {
      throw new Error('Invalid deployTarget ' + deployTarget);
    }

    if (deployTarget === 'dev') {
      ENV.build.environment = 'development';
      ENV.redis.revisionKey = 'dev';
      ENV.redis.url = process.env.YAPP_REDIS_URL_DEVELOPMENT || 'redis://0.0.0.0:6379/';
      ENV.pipeline.disabled = {
        allExcept: ['build', 'redis']
      };
    }

    if (deployTarget === 'devindex') {
      ENV.pipeline.activateOnDeploy = true;
      ENV.build.environment = 'development';
      ENV.redis.distDir = function(context) {
        return context.commandOptions.buildDir || 'dist';
      };
      ENV.redis.revisionKey = 'dev';
      ENV.redis.url = process.env.YAPP_REDIS_URL_DEVELOPMENT || 'redis://0.0.0.0:6379/';
      ENV.pipeline.disabled = { // special case to support postBuild and `npm run dev:index` usage
        allExcept: ['redis']
      };
    }

    var domain;
    var herokuAppName;
    if (deployTarget === 'qa') {
      ENV.s3.bucket = 'yapp-assets';
      ENV.redis.url = process.env.REDISTOGO_URL; // optional, falls back to reading from heroku below
      domain = "www.yappqa.us";
      herokuAppName = 'qa-yapp-cedar';
    }

    if (deployTarget === 'prod') {
      ENV.s3.bucket = 'yapp-assets';
      ENV.redis.url = process.env.REDISTOGO_URL; // optional, falls back to reading from heroku below
      domain = "www.yapp.us";
      herokuAppName = 'yapp-cedar';
    }

    if (deployTarget === 'qa' || deployTarget === 'prod') {
      ENV.build.environment = 'production';
      ENV.s3.accessKeyId = process.env.YAPP_AWS_KEY;
      ENV.s3.secretAccessKey = process.env.YAPP_AWS_SECRET;
      ENV.slack.didDeploy = function(context) {
        return function(slack){
          var message;
          var revisionKey = context.revisionData.revisionKey;
          if (revisionKey && !context.revisionData.activatedRevisionKey) {
            message = "Deployed " + appName + " to " + process.env.DEPLOY_TARGET + " but did not activate it.\n"
                 + "Preview: https://" + domain + "/" + prefix + "/?manifest_id=" + revisionKey + "\n"
                 + "Activate: `ember deploy:activate " + process.env.DEPLOY_TARGET + ' --revision='+ revisionKey + "`\n";
          } else {
            message = '*' + appName + ' > *' + process.env.DEPLOY_TARGET + '* -- _Deployed & activated_ -- (revision: `' + revisionKey + '`)';
          }
          return slack.notify(message);
        };
      };
      ENV.slack.didActivate = function(context) {
        if (context.commandOptions.revision) {
          return function(slack){
            var message = "Activated " + appName + " revision on " + process.env.DEPLOY_TARGET + ": " + context.revisionData.activatedRevisionKey + "\n";
            return slack.notify(message);
          };
        }
      };
      ENV.redis.didDeployMessage = function(context) {
        if (context.revisionData.revisionKey && !context.revisionData.activatedRevisionKey) {
          var revisionKey = context.revisionData.revisionKey;
          return "Deployed but did not activate revision " + revisionKey + ".\n"
               + "To preview:\n"
               + "https://" + domain + "/" + prefix + "/?manifest_id=" + revisionKey + "\n"
               + "To activate:\n"
               + "ember deploy:activate " + process.env.DEPLOY_TARGET + ' --revision='+ revisionKey + "\n";
        }
      };
    }

    return Promise.resolve().then(function(){
      if (deployTarget === 'qa' || deployTarget === 'prod') {
        if (!ENV.redis.url || ENV.redis.url === '') {
          return new Promise(function(resolve, reject){
            var exec = require('child_process').exec;
            exec('heroku config:get REDISTOGO_URL --app ' + herokuAppName, function (error, stdout, stderr) {
              ENV.redis.url = stdout.replace(/\n/, '').replace(/\/\/redistogo:/, '//:');
              resolve(ENV);
            });
          });
        }
      }
      return ENV;
    });
  }
};
<|endoftext|>


<commit_before>// @flow
import { NativeModules, DeviceEventEmitter } from 'react-native';

const { SmartLocation } = NativeModules;

type Coordinates = {
  speed: number,
  heading: number,
  accuracy: number,
  longitude: number,
  altitude: number,
  latitude: number,
};

type Position = {
  timestamp: number,
  timeTaken?: number, // self-added for measuring
  coords: Coordinates,
};

function onLocationUpdate(cb: (pos: Position) => void) {
  DeviceEventEmitter.addListener('smartLocationUpdated', (pos: Position) => {
    cb(pos);
  });
  SmartLocation.onLocationUpdate();
}

const {
  getCurrentLocation,
  getLocationState,
  stopListeningForLocationUpdates,
} = SmartLocation;

module.exports = {
  getCurrentLocation,
  getLocationState,
  stopListeningForLocationUpdates,
  onLocationUpdate,
};
<commit_msg>prevent callback repeated native module<commit_after>// @flow
import { NativeModules, DeviceEventEmitter } from 'react-native';

const { SmartLocation } = NativeModules;

type Coordinates = {
  speed: number,
  heading: number,
  accuracy: number,
  longitude: number,
  altitude: number,
  latitude: number,
};

type Position = {
  timestamp: number,
  timeTaken?: number, // self-added for measuring
  coords: Coordinates,
};

function onLocationUpdate(cb: (pos: Position) => void) {
  DeviceEventEmitter.addListener('smartLocationUpdated', (pos: Position) => {
    cb(pos);
  });
  SmartLocation.onLocationUpdate();
}

function getCurrentLocation(): Promise {
  return SmartLocation.getCurrentLocation();
}

const {
  getLocationState,
  stopListeningForLocationUpdates,
} = SmartLocation;

module.exports = {
  getCurrentLocation,
  getLocationState,
  stopListeningForLocationUpdates,
  onLocationUpdate,
};
<|endoftext|>


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

var merge = require('cli-util').merge;
var types = require('./lib/types');
var clierr = require('cli-error');
var conflict = require('./lib/conflict');
var middlewares = require('./lib/middleware');
var cname = require('./lib/util/name');

var cli = require('cli-define');
var define = cli.define;
var key = cli.key;
var Program = cli.Program;
var Option = cli.Option;

var errors = clierr.errors;
var ErrorDefinition = clierr.ErrorDefinition;
var CliError = clierr.CliError;

var defaults = {
  exit: true,
  stash: null,
  bin: null,
  env: null,
  trace: false,
  middleware: null
}

var all = [
  middlewares.error,
  middlewares.parser,
  middlewares.unparsed,
  middlewares.defaults,
  middlewares.env,
  middlewares.multiple,
  middlewares.merge,
  middlewares.convert,
  middlewares.exec,
  middlewares.action,
  middlewares.emultiple,
  middlewares.erequired,
  middlewares.command,
  middlewares.empty,
  middlewares.run];

var CommandProgram = function() {
  Program.apply(this, arguments);
  // private
  define(this, '_middleware', undefined, true);
  define(this, '_configuration', merge(defaults, {}), false);
  define(this, '__middleware__', [], false);
  define(this, '_exec', {}, false);

  // public
  define(this, 'errors', errors, false);

  // TODO: depreacte this public property
  define(this, 'args', [], true);
}

util.inherits(CommandProgram, Program);

/**
 *  Get a reference to the object that will be assigned
 *  properties corresponding to the argument values.
 *
 *  This will be either the program instance or a stash object
 *  if the program has been configured to use a stash.
 */
function getReceiver() {
  var receiver = this;
  var config = this.configuration();
  if((typeof(config.stash) == 'string') && config.stash.length) {
    receiver = this[config.stash] = this[config.stash] || {};
  }else if(config.stash && (typeof(config.stash) == 'object')) {
    receiver = config.stash;
  }
  return receiver;
}
define(CommandProgram.prototype, 'getReceiver', getReceiver, false);

/**
 *  Generate an error from an error definition or plain error instance.
 *
 *  @param err The error definition.
 *  @param parameters The message replacement parameters.
 *  @param source A source error to wrap.
 */
function wrap(err, parameters, source) {
  var e, code;//, source = data && data.error ? data.error : null;
  if(err instanceof CliError) {
    e = err;
  }else if((err instanceof ErrorDefinition)) {
    e = err.toError(source);
    if(!source) e.shift();
    e.parameters = parameters || [];
    e.key = err.key;
    //e.data = data;
  }else if(err instanceof Error) {
    code = err.code || errors.EUNCAUGHT.code;
    e = new CliError(err, code, parameters);
    e.key = err.key || errors.EUNCAUGHT.key;
  }
  return e;
}
define(CommandProgram.prototype, 'wrap', wrap, false);

/**
 *  Raise an error from an error definition or error
 *  instance.
 *
 *  @param err The error definition.
 *  @param parameters The message replacement parameters.
 *  @param source A source error to wrap.
 */
function raise(err, parameters, source) {
  var e = this.wrap(err, parameters, source);
  this.emit('error', e, errors);
}
define(CommandProgram.prototype, 'raise', raise, false);

/**
 *  Override so we can maintain a list of commands
 *  that should be executed as external child processes.
 *
 *  @param name The command name.
 *  @param description The command description.
 *  @param options The command options.
 */
function command(name, description, options) {
  var cmd = Program.prototype.command.apply(this, arguments);
  if(description) {
    var id = key(name);
    this._exec[id] = cmd;
  }
  return cmd;
}
define(CommandProgram.prototype, 'command', command, false);

/**
 *  Define program middleware.
 */
function use(middleware) {
  var i, nm, args, result, conf = this.configuration();
  if(!arguments.length && this._middleware === undefined) {
    for(i = 0;i < all.length;i++) {
      if(conf && conf.middleware) {
        result = all[i].call(this);
        if(typeof result !== 'function') {
          continue;
        }
        nm = cname(result);
        //console.log('got name %s', nm);
        if(nm && conf.middleware[nm] === false) {
          continue;
        }
      }
      this.use(all[i]);
    }
    return this;
  }
  args = [].slice.call(arguments, 1);
  if(typeof middleware != 'function') {
    throw new Error('Invalid middleware, must be a function');
  }
  result = middleware.apply(this, args);

  if(~this.__middleware__.indexOf(middleware)) {
    throw new Error('Invalid middleware, duplicate detected');
  }

  if(typeof(result) == 'function') {
    if(this._middleware === undefined) this._middleware = [];
    this._middleware.push(result);
  }

  this.__middleware__.push(middleware);

  return this;
}
define(CommandProgram.prototype, 'use', use, false);

/**
 *  Get or set the environment instance.
 */
function env(value) {
  if(!arguments.length) return this._env;
  this._env = value;
  return this;
}
define(CommandProgram.prototype, 'env', env, false);

/**
 *  Default error handler for the error event.
 *
 *  @param e The error instance.
 */
function error(e) {
  var conf = this.configuration();
  if(!(e instanceof CliError)) {
    e = this.wrap(e);
  }
  var trace =
    (e.code === errors.EUNCAUGHT.code || conf.trace) ? true : false;
  e.error(trace);
  if(conf.exit) e.exit();
}
define(CommandProgram.prototype, 'error', error, false);

/**
 *  Assigns configuration information to the program.
 *
 *  @param conf The program configuration.
 */
function configuration(conf) {
  if(!arguments.length) return this._configuration;
  conf = conf || {};
  var stash = conf.stash;
  if((typeof stash == 'string') && (stash in this)) {
    conflict.call(this, stash, new Option(stash));
    return this;
  }
  merge(conf, this._configuration || merge(config, {}));
  return this;
}
define(CommandProgram.prototype, 'configuration', configuration, false);

/**
 *  Adds a version flag to the program.
 *
 *  @param semver A specific version number.
 *  @param name The argument name.
 *  @param description The argument description.
 *  @param action A function to invoke.
 */
function version(semver, name, description, action) {
  if(!arguments.length && this._arguments.versionopt) return this._version;
  return this.use(middlewares.version, semver, name, description, action);
}
define(CommandProgram.prototype, 'version', version, false);

/**
 *  Adds a help flag to the program.
 *
 *  @param name The argument name.
 *  @param description The argument description.
 *  @param action A function to invoke.
 */
function help(name, description, action) {
  return this.use(middlewares.help, name, description, action);
}
define(CommandProgram.prototype, 'help', help, false);

/**
 *  Parse the supplied arguments and execute any commands
 *  found in the arguments, preferring the built in commands
 *  for help and version.
 *
 *  @param args The arguments to parse, default is process.argv.slice(2).
 *  @param options Configuration options.
 */
function parse(args) {
  args = args || process.argv.slice(2);
  conflict.call(this);
  if(this._middleware === undefined) {
    this.use();
  }

  middleware.call(this, args);
  return this;
}
define(CommandProgram.prototype, 'parse', parse, false);

/**
 *  Execute middleware.
 *
 *  @param args The arguments passed to parse.
 */
function middleware(args) {
  var i = 0, list = this._middleware, scope = this;
  var req = {program: this, argv: args};
  function exec() {
    var func = list[i];
    func.call(scope, req, next);
  }
  function next(err, parameters, e) {
    if(err) {
      scope.raise(err, parameters, e);
    }
    i++;
    if(i < list.length) {
      exec();
    }
  }
  if(list.length) exec();
}

module.exports = function(package, name, description, configuration) {
  var locales = path.join(__dirname, 'lib', 'error', 'locales');
  clierr.file({locales: locales});
  var program = cli(package, name, description, CommandProgram);
  program.configuration(configuration || defaults);
  var listeners = process.listeners('uncaughtException');
  if(!listeners.length) {
    process.on('uncaughtException', function(err) {
      err.code = errors.EUNCAUGHT.code;
      program.raise(err);
    })
  }
  // TODO: allow setting error configuration on the program configuration
  clierr({name: program.name()});
  return program;
}

module.exports.middleware = middlewares;
module.exports.help = middlewares.help.action;
module.exports.version = middlewares.version.action;
module.exports.types = types;
module.exports.error = require('./lib/error');
<commit_msg>Run action middleware before exec.<commit_after>var path = require('path');
var util = require('util');

var merge = require('cli-util').merge;
var types = require('./lib/types');
var clierr = require('cli-error');
var conflict = require('./lib/conflict');
var middlewares = require('./lib/middleware');
var cname = require('./lib/util/name');

var cli = require('cli-define');
var define = cli.define;
var key = cli.key;
var Program = cli.Program;
var Option = cli.Option;

var errors = clierr.errors;
var ErrorDefinition = clierr.ErrorDefinition;
var CliError = clierr.CliError;

var defaults = {
  exit: true,
  stash: null,
  bin: null,
  env: null,
  trace: false,
  middleware: null
}

var all = [
  middlewares.error,
  middlewares.parser,
  middlewares.unparsed,
  middlewares.defaults,
  middlewares.env,
  middlewares.multiple,
  middlewares.merge,
  middlewares.convert,
  middlewares.action,
  middlewares.exec,
  middlewares.emultiple,
  middlewares.erequired,
  middlewares.command,
  middlewares.empty,
  middlewares.run];

var CommandProgram = function() {
  Program.apply(this, arguments);
  // private
  define(this, '_middleware', undefined, true);
  define(this, '_configuration', merge(defaults, {}), false);
  define(this, '__middleware__', [], false);
  define(this, '_exec', {}, false);

  // public
  define(this, 'errors', errors, false);

  // TODO: depreacte this public property
  define(this, 'args', [], true);
}

util.inherits(CommandProgram, Program);

/**
 *  Get a reference to the object that will be assigned
 *  properties corresponding to the argument values.
 *
 *  This will be either the program instance or a stash object
 *  if the program has been configured to use a stash.
 */
function getReceiver() {
  var receiver = this;
  var config = this.configuration();
  if((typeof(config.stash) == 'string') && config.stash.length) {
    receiver = this[config.stash] = this[config.stash] || {};
  }else if(config.stash && (typeof(config.stash) == 'object')) {
    receiver = config.stash;
  }
  return receiver;
}
define(CommandProgram.prototype, 'getReceiver', getReceiver, false);

/**
 *  Generate an error from an error definition or plain error instance.
 *
 *  @param err The error definition.
 *  @param parameters The message replacement parameters.
 *  @param source A source error to wrap.
 */
function wrap(err, parameters, source) {
  var e, code;//, source = data && data.error ? data.error : null;
  if(err instanceof CliError) {
    e = err;
  }else if((err instanceof ErrorDefinition)) {
    e = err.toError(source);
    if(!source) e.shift();
    e.parameters = parameters || [];
    e.key = err.key;
    //e.data = data;
  }else if(err instanceof Error) {
    code = err.code || errors.EUNCAUGHT.code;
    e = new CliError(err, code, parameters);
    e.key = err.key || errors.EUNCAUGHT.key;
  }
  return e;
}
define(CommandProgram.prototype, 'wrap', wrap, false);

/**
 *  Raise an error from an error definition or error
 *  instance.
 *
 *  @param err The error definition.
 *  @param parameters The message replacement parameters.
 *  @param source A source error to wrap.
 */
function raise(err, parameters, source) {
  var e = this.wrap(err, parameters, source);
  this.emit('error', e, errors);
}
define(CommandProgram.prototype, 'raise', raise, false);

/**
 *  Override so we can maintain a list of commands
 *  that should be executed as external child processes.
 *
 *  @param name The command name.
 *  @param description The command description.
 *  @param options The command options.
 */
function command(name, description, options) {
  var cmd = Program.prototype.command.apply(this, arguments);
  if(description) {
    var id = key(name);
    this._exec[id] = cmd;
  }
  return cmd;
}
define(CommandProgram.prototype, 'command', command, false);

/**
 *  Define program middleware.
 */
function use(middleware) {
  var i, nm, args, result, conf = this.configuration();
  if(!arguments.length && this._middleware === undefined) {
    for(i = 0;i < all.length;i++) {
      if(conf && conf.middleware) {
        result = all[i].call(this);
        if(typeof result !== 'function') {
          continue;
        }
        nm = cname(result);
        //console.log('got name %s', nm);
        if(nm && conf.middleware[nm] === false) {
          continue;
        }
      }
      this.use(all[i]);
    }
    return this;
  }
  args = [].slice.call(arguments, 1);
  if(typeof middleware != 'function') {
    throw new Error('Invalid middleware, must be a function');
  }
  result = middleware.apply(this, args);

  if(~this.__middleware__.indexOf(middleware)) {
    throw new Error('Invalid middleware, duplicate detected');
  }

  if(typeof(result) == 'function') {
    if(this._middleware === undefined) this._middleware = [];
    this._middleware.push(result);
  }

  this.__middleware__.push(middleware);

  return this;
}
define(CommandProgram.prototype, 'use', use, false);

/**
 *  Get or set the environment instance.
 */
function env(value) {
  if(!arguments.length) return this._env;
  this._env = value;
  return this;
}
define(CommandProgram.prototype, 'env', env, false);

/**
 *  Default error handler for the error event.
 *
 *  @param e The error instance.
 */
function error(e) {
  var conf = this.configuration();
  if(!(e instanceof CliError)) {
    e = this.wrap(e);
  }
  var trace =
    (e.code === errors.EUNCAUGHT.code || conf.trace) ? true : false;
  e.error(trace);
  if(conf.exit) e.exit();
}
define(CommandProgram.prototype, 'error', error, false);

/**
 *  Assigns configuration information to the program.
 *
 *  @param conf The program configuration.
 */
function configuration(conf) {
  if(!arguments.length) return this._configuration;
  conf = conf || {};
  var stash = conf.stash;
  if((typeof stash == 'string') && (stash in this)) {
    conflict.call(this, stash, new Option(stash));
    return this;
  }
  merge(conf, this._configuration || merge(config, {}));
  return this;
}
define(CommandProgram.prototype, 'configuration', configuration, false);

/**
 *  Adds a version flag to the program.
 *
 *  @param semver A specific version number.
 *  @param name The argument name.
 *  @param description The argument description.
 *  @param action A function to invoke.
 */
function version(semver, name, description, action) {
  if(!arguments.length && this._arguments.versionopt) return this._version;
  return this.use(middlewares.version, semver, name, description, action);
}
define(CommandProgram.prototype, 'version', version, false);

/**
 *  Adds a help flag to the program.
 *
 *  @param name The argument name.
 *  @param description The argument description.
 *  @param action A function to invoke.
 */
function help(name, description, action) {
  return this.use(middlewares.help, name, description, action);
}
define(CommandProgram.prototype, 'help', help, false);

/**
 *  Parse the supplied arguments and execute any commands
 *  found in the arguments, preferring the built in commands
 *  for help and version.
 *
 *  @param args The arguments to parse, default is process.argv.slice(2).
 *  @param options Configuration options.
 */
function parse(args) {
  args = args || process.argv.slice(2);
  conflict.call(this);
  if(this._middleware === undefined) {
    this.use();
  }

  middleware.call(this, args);
  return this;
}
define(CommandProgram.prototype, 'parse', parse, false);

/**
 *  Execute middleware.
 *
 *  @param args The arguments passed to parse.
 */
function middleware(args) {
  var i = 0, list = this._middleware, scope = this;
  var req = {program: this, argv: args};
  function exec() {
    var func = list[i];
    func.call(scope, req, next);
  }
  function next(err, parameters, e) {
    if(err) {
      scope.raise(err, parameters, e);
    }
    i++;
    if(i < list.length) {
      exec();
    }
  }
  if(list.length) exec();
}

module.exports = function(package, name, description, configuration) {
  var locales = path.join(__dirname, 'lib', 'error', 'locales');
  clierr.file({locales: locales});
  var program = cli(package, name, description, CommandProgram);
  program.configuration(configuration || defaults);
  var listeners = process.listeners('uncaughtException');
  if(!listeners.length) {
    process.on('uncaughtException', function(err) {
      err.code = errors.EUNCAUGHT.code;
      program.raise(err);
    })
  }
  // TODO: allow setting error configuration on the program configuration
  clierr({name: program.name()});
  return program;
}

module.exports.middleware = middlewares;
module.exports.help = middlewares.help.action;
module.exports.version = middlewares.version.action;
module.exports.types = types;
module.exports.error = require('./lib/error');
<|endoftext|>


<commit_before>const CDP = require('chrome-remote-interface');
const fs = require('fs');

class ChromePageObject {

  constructor() {
    this.path = __dirname + '/binary';
  }

  getCDP() {
    return new Promise((resolve) => {
      if (!this._client) {
        CDP((client) => {
          this._client = client;
          resolve(client);
        }).on('error', (err) => {
          console.error("CDP Error: " + err.stack);
        });
      } else {
        resolve(this._client);
      }
    })
  }

  open(url, cb) {
    this.getCDP().then(async (client) => {
      const { Page } = client;
      try {
        await Page.enable();
        await Page.navigate({url: url});
        await Page.loadEventFired();
        cb(null, url)
      } catch (err) {
        cb(err, null);
        console.error(err);
      }
    });
  }

  async render(filePath) {
    this.getCDP().then(async (client) => {
      const { Page } = client;
      try {
        const { data } = await Page.captureScreenshot();
        fs.writeFileSync(filePath, Buffer.from(data, 'base64'));
      } catch (err) {
        console.error(err);
      }
    });
  }

  evaluate(fn, cb, ...args) {
    this.getCDP().then(async (client) => {
      const { Page, Runtime } = client;
      try {
        let executor = (stringyFunc, args) => {
          let invoke = new Function(
            "return " + stringyFunc
          )();
          return invoke.apply(null, args)
        }
        let executorString = `(${executor})(${fn.toString()}, ${JSON.stringify(args)})`
        await Runtime.enable();
        const { result: { value } } = await Runtime.evaluate({expression: executorString});
        cb (null, value);
      } catch (err) {
        cb(err, null);
        console.error(err);
      }
    });
  }

  goForward() {
    this.getCDP().then(async (client) => {
      const { Page } = client;
      try {
          await Page.enable();
          let {currentIndex, entries} = await Page.getNavigationHistory();
          if (currentIndex === entries.length-1) {
            return;
          } else {
            await Page.navigate({url: entries[currentIndex+1].url});
          }
      } catch (err) {
          console.error(err);
      }
    });
  }

  goBack() {
    this.getCDP().then(async (client) => {
      const { Page } = client;
      try {
        await Page.enable();
        let {currentIndex, entries} = await Page.getNavigationHistory();
        if (currentIndex === 0) {
          return;
        } else {
          await Page.navigate({url: entries[currentIndex-1].url});
        }
      } catch (err) {
        console.error(err);
      }
    });
  }

  injectJs(scriptPath) {
    const js = fs.readFileSync(scriptPath, {encoding: 'utf8'});
    this.getCDP().then(async (client) => {
      const { Page, Runtime } = client;
      try {
        await Runtime.enable();
        await Page.enable();
        await Page.loadEventFired();
        const result = await Runtime.evaluate({ expression: js });
      } catch (err) {
        console.error(err);
      }
    });
  }

  close() {
    this.getCDP().then(async (client) => {
      await client.close();
    });
  }
}

const page = new ChromePageObject();
module.exports = page;
<commit_msg>Proper handling of evaluate arguments<commit_after>const CDP = require('chrome-remote-interface');
const fs = require('fs');

class ChromePageObject {

  constructor() {
    this.path = __dirname + '/binary';
  }

  getCDP() {
    return new Promise((resolve) => {
      if (!this._client) {
        CDP((client) => {
          this._client = client;
          resolve(client);
        }).on('error', (err) => {
          console.error("CDP Error: " + err.stack);
        });
      } else {
        resolve(this._client);
      }
    })
  }

  open(url, cb) {
    this.getCDP().then(async (client) => {
      const { Page } = client;
      try {
        await Page.enable();
        await Page.navigate({url: url});
        await Page.loadEventFired();
        cb(null, url)
      } catch (err) {
        cb(err, null);
        console.error(err);
      }
    });
  }

  async render(filePath) {
    this.getCDP().then(async (client) => {
      const { Page } = client;
      try {
        const { data } = await Page.captureScreenshot();
        fs.writeFileSync(filePath, Buffer.from(data, 'base64'));
      } catch (err) {
        console.error(err);
      }
    });
  }

  evaluate(fn, ...args) {
    this.getCDP().then(async (client) => {
      const { Page, Runtime } = client;
      try {
        const cb = args.pop();
        let executor = (stringyFunc, args) => {
          let invoke = new Function(
            "return " + stringyFunc
          )();
          return invoke.apply(null, args)
        }
        let executorString = `(${executor})(${fn.toString()}, ${JSON.stringify(args)})`
        await Runtime.enable();
        const { result: { value } } = await Runtime.evaluate({expression: executorString});
        cb (null, value);
      } catch (err) {
        cb(err, null);
        console.error(err);
      }
    });
  }

  goForward() {
    this.getCDP().then(async (client) => {
      const { Page } = client;
      try {
          await Page.enable();
          let {currentIndex, entries} = await Page.getNavigationHistory();
          if (currentIndex === entries.length-1) {
            return;
          } else {
            await Page.navigate({url: entries[currentIndex+1].url});
          }
      } catch (err) {
          console.error(err);
      }
    });
  }

  goBack() {
    this.getCDP().then(async (client) => {
      const { Page } = client;
      try {
        await Page.enable();
        let {currentIndex, entries} = await Page.getNavigationHistory();
        if (currentIndex === 0) {
          return;
        } else {
          await Page.navigate({url: entries[currentIndex-1].url});
        }
      } catch (err) {
        console.error(err);
      }
    });
  }

  injectJs(scriptPath) {
    const js = fs.readFileSync(scriptPath, {encoding: 'utf8'});
    this.getCDP().then(async (client) => {
      const { Page, Runtime } = client;
      try {
        await Runtime.enable();
        await Page.enable();
        await Page.loadEventFired();
        const result = await Runtime.evaluate({ expression: js });
      } catch (err) {
        console.error(err);
      }
    });
  }

  close() {
    this.getCDP().then(async (client) => {
      await client.close();
    });
  }
}

const page = new ChromePageObject();
module.exports = page;
<|endoftext|>


<commit_before>var Rocky = require('./lib/rocky')

module.exports = rocky

function rocky(opts) {
  return new Rocky(opts)
}

rocky.httpProxy  = require('http-proxy')
rocky.middleware = require('./lib/middleware')
rocky.VERSION    = require('./package.json').version
<commit_msg>refactor<commit_after>var Rocky = require('./lib/rocky')

module.exports = rocky

function rocky(opts) {
  return new Rocky(opts)
}

rocky.Rocky      = Rocky
rocky.httpProxy  = require('http-proxy')
rocky.middleware = require('./lib/middleware')
rocky.VERSION    = require('./package.json').version
<|endoftext|>


<commit_before>var sprom = require('sprom')
var Promise = require('bluebird')

/**
 * Gets the most recent data for a key.
 *
 * @param {ForkDB} db A ForkDB connection
 * @param {String} key The uri that is used as key
 * @returns {Promise} A promise which evaluates to the result value.
 */
module.exports.get = function (db, key) {
  return new Promise(function (resolve, reject) {
    if (db === 'undefined') {
      reject('A fork db handle must be supplied!')
    }
    if (key === 'undefined') {
      reject('A key must be supplied!')
    }
    sprom.arr(db.forks(key)).then(function (headsArr) {
      if (headsArr.length === 0) {
        return reject('No data for the given key!')
      }
      var readStream = db.createReadStream(headsArr[0].hash)
      sprom.buf(readStream).then(function (data) {
        resolve(JSON.parse(data.toString()))
      })
    })
  })
}

/**
 * Appends new data to a key. If previous data is found, it is linked
 * correspondingly.
 *
 * @param {ForkDB} db A ForkDB connection
 * @param {Object} doc The document that should be stored
 * @param {String} key The uri that should be used as key
 * @returns {Promise} A promise which evaluates to the insert hash.
 */
module.exports.put = function (db, doc, key) {
  return new Promise(function (resolve, reject) {
    if (db === 'undefined') {
      reject('A fork db handle must be supplied!')
    }
    if (key === 'undefined') {
      reject('A key must be supplied!')
    }
    if (doc === 'undefined') {
      reject('A document must be supplied!')
    }
    var meta = { key: key }
    sprom.arr(db.forks(key)).then(function (headsArr) {
      if (headsArr.length > 0) {
        meta.prev = headsArr[0]
      }
      var writeStream = db.createWriteStream(meta, function (err, id) {
        if (err) reject(err)
        else resolve(id)
      })
      writeStream.end(JSON.stringify(doc))
    })
  })
}
<commit_msg>doc as string not object & changed order of params in put<commit_after>var sprom = require('sprom')
var Promise = require('bluebird')

/**
 * Gets the most recent data for a key.
 *
 * @param {ForkDB} db A ForkDB connection
 * @param {String} key The uri that is used as key
 * @returns {Promise} A promise which evaluates to the document as string
 */
module.exports.get = function (db, key) {
  return new Promise(function (resolve, reject) {
    if (db === 'undefined') {
      reject('A fork db handle must be supplied!')
    }
    if (key === 'undefined') {
      reject('A key must be supplied!')
    }
    sprom.arr(db.forks(key)).then(function (headsArr) {
      if (headsArr.length === 0) {
        return reject('No data for the given key!')
      }
      var readStream = db.createReadStream(headsArr[0].hash)
      sprom.buf(readStream).then(function (data) {
        resolve(data.toString())
      })
    })
  })
}

/**
 * Appends new data to a key. If previous data is found, it is linked
 * correspondingly.
 *
 * @param {ForkDB} db A ForkDB connection
 * @param {String} key The uri that should be used as key
 * @param {String} doc The document that should be stored
 * @returns {Promise} A promise which evaluates to the insert hash.
 */
module.exports.put = function (db, key, doc) {
  return new Promise(function (resolve, reject) {
    if (db === 'undefined') {
      reject('A fork db handle must be supplied!')
    }
    if (key === 'undefined') {
      reject('A key must be supplied!')
    }
    if (doc === 'undefined') {
      reject('A document must be supplied!')
    }
    var meta = { key: key }
    sprom.arr(db.forks(key)).then(function (headsArr) {
      if (headsArr.length > 0) {
        meta.prev = headsArr[0]
      }
      var writeStream = db.createWriteStream(meta, function (err, hash) {
        if (err) reject(err)
        else resolve(hash)
      })
      writeStream.end(doc)
    })
  })
}
<|endoftext|>


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

module.exports = postcss.plugin('postcss-lowvision', function (opts) {
    opts = opts || {};

    return function (css, result) {
      css.walkRules('html', function (rule) {
        /*root.first.append({ prop: 'color', value: 'transparent' });
        root.first.append({ prop: 'text-shadow', value: '0 0 5px rgba(0,0,0,1)' });*/
        postcss.parse('html { color: transparent; text-shadow: 0 0 5px rgba(0,0,0,1);}');
      });
    }
});
<commit_msg>Use cloneBefore<commit_after>var postcss = require('postcss');

module.exports = postcss.plugin('postcss-lowvision', function (opts) {
    opts = opts || {};

    return function (css, result) {
      css.walkRules('html', function (rule) {
        decl.cloneBefore({ prop: 'color',  decl.value: 'transparent' });
        decl.cloneBefore({ prop: 'text-shadow',  decl.value: '0 0 5px rgba(0,0,0,1)' });
      });
    }
});
<|endoftext|>


<commit_before>/**
 * Copyright 2015 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

'use strict';

var filesLoadedBeforeTrace = Object.keys(require.cache);

// Load continuation-local-storage first to ensure the core async APIs get
// patched before any user-land modules get loaded.
require('continuation-local-storage');

var SpanData = require('./lib/span-data.js');
var common = require('@google/cloud-diagnostics-common');
var semver = require('semver');
var constants = require('./lib/constants.js');
var path = require('path');

var modulesLoadedBeforeTrace = [];
var moduleRegex =
  new RegExp('.*?node_modules\\' + path.sep + '([^\\' + path.sep + ']*).*');
for (var i = 0; i < filesLoadedBeforeTrace.length; i++) {
  var matches = moduleRegex.exec(filesLoadedBeforeTrace[i]);
  if (matches && matches.length > 1 &&
      modulesLoadedBeforeTrace.indexOf(matches[1]) === -1) {
    modulesLoadedBeforeTrace.push(matches[1]);
  }
}

/**
 * Phantom implementation of the trace agent. This allows API users to decouple
 * the enable/disable logic from the calls to the tracing API. The phantom API
 * has a lower overhead than isEnabled checks inside the API functions.
 * @private
 */
var phantomTraceAgent = {
  startSpan: function() { return SpanData.nullSpan; },
  endSpan: function(spanData) { spanData.close(); },
  runInSpan: function(name, labels, fn) {
    if (typeof(labels) === 'function') {
      fn = labels;
    }
    fn(function() {});
  },
  setTransactionName: function() {},
  addTransactionLabel: function() {}
};

/** @private */
var agent = phantomTraceAgent;

var initConfig = function(projectConfig) {
  var util = require('util');
  var config = {};
  util._extend(config, require('./config.js').trace);
  util._extend(config, projectConfig);
  if (process.env.hasOwnProperty('GCLOUD_DIAGNOSTICS_CONFIG')) {
    var c = require(path.resolve(process.env.GCLOUD_DIAGNOSTICS_CONFIG));
    if (c) {
      util._extend(config, c.trace);
    }
  }
  if (process.env.hasOwnProperty('GCLOUD_TRACE_LOGLEVEL')) {
    config.logLevel = process.env.GCLOUD_TRACE_LOGLEVEL;
  }
  if (process.env.hasOwnProperty('GCLOUD_TRACE_DISABLE')) {
    config.enabled = false;
  }
  if (process.env.hasOwnProperty('GCLOUD_PROJECT_NUM')) {
    config.projectId = process.env.GCLOUD_PROJECT_NUM;
  }
  return config;
};

/**
 * The singleton public agent. This is the public API of the module.
 */
var publicAgent = {
  isActive: function() {
    return agent !== phantomTraceAgent;
  },

  startSpan: function(name, labels) {
    return agent.startSpan(name, labels);
  },

  endSpan: function(spanData, labels) {
    return agent.endSpan(spanData, labels);
  },

  runInSpan: function(name, labels, fn) {
    return agent.runInSpan(name, labels, fn);
  },

  setTransactionName: function(name) {
    return agent.setTransactionName(name);
  },

  addTransactionLabel: function(key, value) {
    return agent.addTransactionLabel(key, value);
  },

  start: function(projectConfig) {
    if (this.isActive()) { // already started.
      return this;
    }

    var config = initConfig(projectConfig);
    if (!config.enabled) {
      return this;
    }
    var logger = common.logger.create(config.logLevel, '@google/cloud-trace');
    if (!semver.satisfies(process.versions.node, '>=0.12')) {
      logger.error('Tracing is only supported on Node versions >=0.12');
      return this;
    }

    if (config.projectId) {
      logger.info('Locally provided ProjectId: ' + config.projectId);
    }

    var headers = {};
    headers[constants.TRACE_AGENT_REQUEST_HEADER] = 1;

    if (modulesLoadedBeforeTrace.length > 0) {
      logger.warn('Tracing might not work as the following modules ' +
        ' were loaded before the trace agent was initialized: ' +
        JSON.stringify(modulesLoadedBeforeTrace));
    }

    if (typeof config.projectId === 'undefined') {
      // Queue the work to acquire the projectNumber (potentially from the
      // network.)
      common.utils.getProjectNumber(headers, function(err, project) {
        if (err) {
          // Fatal error. Disable the agent.
          logger.error('Unable to acquire the project number from metadata ' +
            'service. Please provide a valid project number as an env. ' +
            'variable, or through config.projectId passed to start().' +
            err);
          publicAgent.stop();
          return;
        }
        config.projectId = project;
      });
    } else if (typeof config.projectId === 'number') {
      config.projectId = config.projectId.toString();
    } else if (typeof config.projectId !== 'string') {
      logger.error('config.projectId, if provided, must be' +
        ' a string or number. Disabling trace agent.');
      return this;
    }

    agent = require('./lib/trace-agent.js').get(config, logger);
    return this; // for chaining
  },

  get: function() {
    if (this.isActive()) {
      return this;
    }
    throw new Error('The agent must be initialized by calling start.');
  },

  stop: function() {
    if (this.isActive()) {
      agent.stop();
      agent = phantomTraceAgent;
    }
  },

  /**
   * For use in tests only.
   * @private
   */
  private_: function() { return agent; }
};

module.exports = global._google_trace_agent = publicAgent;

// If the module was --require'd from the command line, start the agent.
if (module.parent && module.parent.id === 'internal/preload') {
  module.exports.start();
}
<commit_msg>Warn when calling start multiple times<commit_after>/**
 * Copyright 2015 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

'use strict';

var filesLoadedBeforeTrace = Object.keys(require.cache);

// Load continuation-local-storage first to ensure the core async APIs get
// patched before any user-land modules get loaded.
require('continuation-local-storage');

var SpanData = require('./lib/span-data.js');
var common = require('@google/cloud-diagnostics-common');
var semver = require('semver');
var constants = require('./lib/constants.js');
var path = require('path');

var modulesLoadedBeforeTrace = [];
var moduleRegex =
  new RegExp('.*?node_modules\\' + path.sep + '([^\\' + path.sep + ']*).*');
for (var i = 0; i < filesLoadedBeforeTrace.length; i++) {
  var matches = moduleRegex.exec(filesLoadedBeforeTrace[i]);
  if (matches && matches.length > 1 &&
      modulesLoadedBeforeTrace.indexOf(matches[1]) === -1) {
    modulesLoadedBeforeTrace.push(matches[1]);
  }
}

/**
 * Phantom implementation of the trace agent. This allows API users to decouple
 * the enable/disable logic from the calls to the tracing API. The phantom API
 * has a lower overhead than isEnabled checks inside the API functions.
 * @private
 */
var phantomTraceAgent = {
  startSpan: function() { return SpanData.nullSpan; },
  endSpan: function(spanData) { spanData.close(); },
  runInSpan: function(name, labels, fn) {
    if (typeof(labels) === 'function') {
      fn = labels;
    }
    fn(function() {});
  },
  setTransactionName: function() {},
  addTransactionLabel: function() {}
};

/** @private */
var agent = phantomTraceAgent;

var initConfig = function(projectConfig) {
  var util = require('util');
  var config = {};
  util._extend(config, require('./config.js').trace);
  util._extend(config, projectConfig);
  if (process.env.hasOwnProperty('GCLOUD_DIAGNOSTICS_CONFIG')) {
    var c = require(path.resolve(process.env.GCLOUD_DIAGNOSTICS_CONFIG));
    if (c) {
      util._extend(config, c.trace);
    }
  }
  if (process.env.hasOwnProperty('GCLOUD_TRACE_LOGLEVEL')) {
    config.logLevel = process.env.GCLOUD_TRACE_LOGLEVEL;
  }
  if (process.env.hasOwnProperty('GCLOUD_TRACE_DISABLE')) {
    config.enabled = false;
  }
  if (process.env.hasOwnProperty('GCLOUD_PROJECT_NUM')) {
    config.projectId = process.env.GCLOUD_PROJECT_NUM;
  }
  return config;
};

/**
 * The singleton public agent. This is the public API of the module.
 */
var publicAgent = {
  isActive: function() {
    return agent !== phantomTraceAgent;
  },

  startSpan: function(name, labels) {
    return agent.startSpan(name, labels);
  },

  endSpan: function(spanData, labels) {
    return agent.endSpan(spanData, labels);
  },

  runInSpan: function(name, labels, fn) {
    return agent.runInSpan(name, labels, fn);
  },

  setTransactionName: function(name) {
    return agent.setTransactionName(name);
  },

  addTransactionLabel: function(key, value) {
    return agent.addTransactionLabel(key, value);
  },

  start: function(projectConfig) {
    if (this.isActive()) { // already started.
      agent.logger.warn('Calling start on already started agent.' +
        'New configuration will be ignored.');
      return this;
    }

    var config = initConfig(projectConfig);
    if (!config.enabled) {
      return this;
    }
    var logger = common.logger.create(config.logLevel, '@google/cloud-trace');
    if (!semver.satisfies(process.versions.node, '>=0.12')) {
      logger.error('Tracing is only supported on Node versions >=0.12');
      return this;
    }

    if (config.projectId) {
      logger.info('Locally provided ProjectId: ' + config.projectId);
    }

    var headers = {};
    headers[constants.TRACE_AGENT_REQUEST_HEADER] = 1;

    if (modulesLoadedBeforeTrace.length > 0) {
      logger.warn('Tracing might not work as the following modules ' +
        ' were loaded before the trace agent was initialized: ' +
        JSON.stringify(modulesLoadedBeforeTrace));
    }

    if (typeof config.projectId === 'undefined') {
      // Queue the work to acquire the projectNumber (potentially from the
      // network.)
      common.utils.getProjectNumber(headers, function(err, project) {
        if (err) {
          // Fatal error. Disable the agent.
          logger.error('Unable to acquire the project number from metadata ' +
            'service. Please provide a valid project number as an env. ' +
            'variable, or through config.projectId passed to start().' +
            err);
          publicAgent.stop();
          return;
        }
        config.projectId = project;
      });
    } else if (typeof config.projectId === 'number') {
      config.projectId = config.projectId.toString();
    } else if (typeof config.projectId !== 'string') {
      logger.error('config.projectId, if provided, must be' +
        ' a string or number. Disabling trace agent.');
      return this;
    }

    agent = require('./lib/trace-agent.js').get(config, logger);
    return this; // for chaining
  },

  get: function() {
    if (this.isActive()) {
      return this;
    }
    throw new Error('The agent must be initialized by calling start.');
  },

  stop: function() {
    if (this.isActive()) {
      agent.stop();
      agent = phantomTraceAgent;
    }
  },

  /**
   * For use in tests only.
   * @private
   */
  private_: function() { return agent; }
};

module.exports = global._google_trace_agent = publicAgent;

// If the module was --require'd from the command line, start the agent.
if (module.parent && module.parent.id === 'internal/preload') {
  module.exports.start();
}
<|endoftext|>


<commit_before>module.exports = {
  "rules": {
    "at-rule-name-case": "lower",
    "at-rule-name-space-after": "always-single-line",
    "at-rule-no-vendor-prefix": true,
    "at-rule-semicolon-newline-after": "always",
    "block-closing-brace-empty-line-before": "never",
    "block-closing-brace-newline-after": "always",
    "block-closing-brace-newline-before": "always-multi-line",
    "block-closing-brace-space-before": "always-single-line",
    "block-no-empty": true,
    "block-opening-brace-newline-after": "always-multi-line",
    "block-opening-brace-space-after": "always-single-line",
    "block-opening-brace-space-before": "always",
    "color-hex-case": "lower",
    "color-hex-length": "short",
    "color-no-invalid-hex": true,
    "comment-empty-line-before": ["always", {
      except: ["first-nested"],
      ignore: ["stylelint-commands"],
    }],
    "comment-no-empty": true,
    "comment-whitespace-inside": "always",
    "custom-property-empty-line-before": ["always", {
      except: [
        "after-custom-property",
        "first-nested",
      ],
      ignore:[
        "after-comment",
        "inside-single-line-block",
      ],
    }],
    "declaration-bang-space-after": "never",
    "declaration-bang-space-before": "always",
    "declaration-block-no-duplicate-properties": [true, {
      ignore: ["consecutive-duplicates-with-different-values"]
    }],
    "declaration-block-no-redundant-longhand-properties": true,
    "declaration-block-no-shorthand-property-overrides": true,
    "declaration-block-semicolon-newline-after": "always-multi-line",
    "declaration-block-semicolon-newline-before": "never-multi-line",
    "declaration-block-semicolon-space-after": "always-single-line",
    "declaration-block-semicolon-space-before": "never",
    "declaration-block-single-line-max-declarations": 1,
    "declaration-block-trailing-semicolon": "always",
    "declaration-colon-newline-after": "always-multi-line",
    "declaration-colon-space-after": "always-single-line",
    "declaration-colon-space-before": "never",
    "declaration-empty-line-before": ["always", {
      except: [
        "first-nested",
      ],
      ignore: [
        "after-comment",
        "after-declaration",
        "inside-single-line-block",
      ]
    }],
    "declaration-no-important": true,
    "font-family-no-duplicate-names": true,
    "function-calc-no-unspaced-operator": true,
    "function-comma-newline-after": "always-multi-line",
    "function-comma-space-after": "always-single-line",
    "function-comma-space-before": "never",
    "function-linear-gradient-no-nonstandard-direction": true,
    "function-max-empty-lines": 0,
    "function-name-case": "lower",
    "function-parentheses-newline-inside": "always-multi-line",
    "function-parentheses-space-inside": "never-single-line",
    "function-whitespace-after": "always",
    "indentation": 2,
    "keyframe-declaration-no-important": true,
    "length-zero-no-unit": true,
    "max-empty-lines": 1,
    "media-feature-colon-space-after": "always",
    "media-feature-colon-space-before": "never",
    "media-feature-name-case": "lower",
    "media-feature-name-no-unknown": true,
    "media-feature-name-no-vendor-prefix": true,
    "media-feature-parentheses-space-inside": "never",
    "media-feature-range-operator-space-after": "always",
    "media-feature-range-operator-space-before": "always",
    "media-query-list-comma-newline-after": "always-multi-line",
    "media-query-list-comma-newline-before": "never-multi-line",
    "media-query-list-comma-space-after": "always-single-line",
    "media-query-list-comma-space-before": "never",
    "no-descending-specificity": true,
    "no-duplicate-selectors": true,
    "no-empty-source": true,
    "no-eol-whitespace": true,
    "no-extra-semicolons": true,
    "no-invalid-double-slash-comments": true,
    "no-missing-end-of-source-newline": true,
    "no-unknown-animations": true,
    "number-leading-zero": "always"|"never",
    "number-max-precision": int,
    "number-no-trailing-zeros": true,
    "property-blacklist": string|[],
    "property-case": "lower"|"upper",
    "property-no-unknown": true,
    "property-no-vendor-prefix": true,
    "property-whitelist": string|[],
    "rule-empty-line-before": "always"|"never"|"always-multi-line"|"never-multi-line",
    "selector-attribute-brackets-space-inside": "always"|"never",
    "selector-attribute-operator-blacklist": string|[],
    "selector-attribute-operator-space-after": "always"|"never",
    "selector-attribute-operator-space-before": "always"|"never",
    "selector-attribute-operator-whitelist": string|[],
    "selector-attribute-quotes": "always"|"never",
    "selector-class-pattern": string,
    "selector-combinator-space-after": "always"|"never",
    "selector-combinator-space-before": "always"|"never",
    "selector-descendant-combinator-no-non-space": true,
    "selector-id-pattern": string,
    "selector-list-comma-newline-after": "always"|"always-multi-line"|"never-multi-line",
    "selector-list-comma-newline-before": "always"|"always-multi-line"|"never-multi-line",
    "selector-list-comma-space-after": "always"|"never"|"always-single-line"|"never-single-line",
    "selector-list-comma-space-before": "always"|"never"|"always-single-line"|"never-single-line",
    "selector-max-empty-lines": int,
    "selector-max-compound-selectors": int,
    "selector-max-specificity": string,
    "selector-nested-pattern": string,
    "selector-no-attribute": true,
    "selector-no-combinator": true,
    "selector-no-id": true,
    "selector-no-qualifying-type": true,
    "selector-no-type": true,
    "selector-no-universal": true,
    "selector-no-vendor-prefix": true,
    "selector-pseudo-class-blacklist": string|[],
    "selector-pseudo-class-case": "lower"|"upper",
    "selector-pseudo-class-no-unknown": true,
    "selector-pseudo-class-parentheses-space-inside": "always"|"never",
    "selector-pseudo-class-whitelist": string|[],
    "selector-pseudo-element-case": "lower"|"upper",
    "selector-pseudo-element-colon-notation": "single"|"double",
    "selector-pseudo-element-no-unknown": true,
    "selector-type-case": "lower"|"upper",
    "selector-type-no-unknown": true,
    "shorthand-property-no-redundant-values": true,
    "string-no-newline": true,
    "string-quotes": "single"|"double",
    "time-min-milliseconds": int,
    "unit-blacklist": string|[],
    "unit-case": "lower"|"upper",
    "unit-no-unknown": true,
    "unit-whitelist": string|[],
    "value-keyword-case": "lower"|"upper",
    "value-list-comma-newline-after": "always"|"always-multi-line"|"never-multi-line",
    "value-list-comma-newline-before": "always"|"always-multi-line"|"never-multi-line",
    "value-list-comma-space-after": "always"|"never"|"always-single-line"|"never-single-line",
    "value-list-comma-space-before": "always"|"never"|"always-single-line"|"never-single-line",
    "value-list-max-empty-lines": int,
    "value-no-vendor-prefix": true
  }
}
<commit_msg>:wrench: property-whitelist まで設定。<commit_after>module.exports = {
  "rules": {
    "at-rule-name-case": "lower",
    "at-rule-name-space-after": "always-single-line",
    "at-rule-no-vendor-prefix": true,
    "at-rule-semicolon-newline-after": "always",
    "block-closing-brace-empty-line-before": "never",
    "block-closing-brace-newline-after": "always",
    "block-closing-brace-newline-before": "always-multi-line",
    "block-closing-brace-space-before": "always-single-line",
    "block-no-empty": true,
    "block-opening-brace-newline-after": "always-multi-line",
    "block-opening-brace-space-after": "always-single-line",
    "block-opening-brace-space-before": "always",
    "color-hex-case": "lower",
    "color-hex-length": "short",
    "color-no-invalid-hex": true,
    "comment-empty-line-before": ["always", {
      except: ["first-nested"],
      ignore: ["stylelint-commands"],
    }],
    "comment-no-empty": true,
    "comment-whitespace-inside": "always",
    "custom-property-empty-line-before": ["always", {
      except: [
        "after-custom-property",
        "first-nested",
      ],
      ignore:[
        "after-comment",
        "inside-single-line-block",
      ],
    }],
    "declaration-bang-space-after": "never",
    "declaration-bang-space-before": "always",
    "declaration-block-no-duplicate-properties": [true, {
      ignore: ["consecutive-duplicates-with-different-values"]
    }],
    "declaration-block-no-redundant-longhand-properties": true,
    "declaration-block-no-shorthand-property-overrides": true,
    "declaration-block-semicolon-newline-after": "always-multi-line",
    "declaration-block-semicolon-newline-before": "never-multi-line",
    "declaration-block-semicolon-space-after": "always-single-line",
    "declaration-block-semicolon-space-before": "never",
    "declaration-block-single-line-max-declarations": 1,
    "declaration-block-trailing-semicolon": "always",
    "declaration-colon-newline-after": "always-multi-line",
    "declaration-colon-space-after": "always-single-line",
    "declaration-colon-space-before": "never",
    "declaration-empty-line-before": ["always", {
      except: [
        "first-nested",
      ],
      ignore: [
        "after-comment",
        "after-declaration",
        "inside-single-line-block",
      ]
    }],
    "declaration-no-important": true,
    "font-family-no-duplicate-names": true,
    "function-calc-no-unspaced-operator": true,
    "function-comma-newline-after": "always-multi-line",
    "function-comma-space-after": "always-single-line",
    "function-comma-space-before": "never",
    "function-linear-gradient-no-nonstandard-direction": true,
    "function-max-empty-lines": 0,
    "function-name-case": "lower",
    "function-parentheses-newline-inside": "always-multi-line",
    "function-parentheses-space-inside": "never-single-line",
    "function-whitespace-after": "always",
    "indentation": 2,
    "keyframe-declaration-no-important": true,
    "length-zero-no-unit": true,
    "max-empty-lines": 1,
    "media-feature-colon-space-after": "always",
    "media-feature-colon-space-before": "never",
    "media-feature-name-case": "lower",
    "media-feature-name-no-unknown": true,
    "media-feature-name-no-vendor-prefix": true,
    "media-feature-parentheses-space-inside": "never",
    "media-feature-range-operator-space-after": "always",
    "media-feature-range-operator-space-before": "always",
    "media-query-list-comma-newline-after": "always-multi-line",
    "media-query-list-comma-newline-before": "never-multi-line",
    "media-query-list-comma-space-after": "always-single-line",
    "media-query-list-comma-space-before": "never",
    "no-descending-specificity": true,
    "no-duplicate-selectors": true,
    "no-empty-source": true,
    "no-eol-whitespace": true,
    "no-extra-semicolons": true,
    "no-invalid-double-slash-comments": true,
    "no-missing-end-of-source-newline": true,
    "no-unknown-animations": true,
    "number-leading-zero": "always",
    "number-no-trailing-zeros": true,
    "property-case": "lower",
    "property-no-unknown": true,
    "property-no-vendor-prefix": true,
    "rule-empty-line-before": "always"|"never"|"always-multi-line"|"never-multi-line",
    "selector-attribute-brackets-space-inside": "always"|"never",
    "selector-attribute-operator-blacklist": string|[],
    "selector-attribute-operator-space-after": "always"|"never",
    "selector-attribute-operator-space-before": "always"|"never",
    "selector-attribute-operator-whitelist": string|[],
    "selector-attribute-quotes": "always"|"never",
    "selector-class-pattern": string,
    "selector-combinator-space-after": "always"|"never",
    "selector-combinator-space-before": "always"|"never",
    "selector-descendant-combinator-no-non-space": true,
    "selector-id-pattern": string,
    "selector-list-comma-newline-after": "always"|"always-multi-line"|"never-multi-line",
    "selector-list-comma-newline-before": "always"|"always-multi-line"|"never-multi-line",
    "selector-list-comma-space-after": "always"|"never"|"always-single-line"|"never-single-line",
    "selector-list-comma-space-before": "always"|"never"|"always-single-line"|"never-single-line",
    "selector-max-empty-lines": int,
    "selector-max-compound-selectors": int,
    "selector-max-specificity": string,
    "selector-nested-pattern": string,
    "selector-no-attribute": true,
    "selector-no-combinator": true,
    "selector-no-id": true,
    "selector-no-qualifying-type": true,
    "selector-no-type": true,
    "selector-no-universal": true,
    "selector-no-vendor-prefix": true,
    "selector-pseudo-class-blacklist": string|[],
    "selector-pseudo-class-case": "lower"|"upper",
    "selector-pseudo-class-no-unknown": true,
    "selector-pseudo-class-parentheses-space-inside": "always"|"never",
    "selector-pseudo-class-whitelist": string|[],
    "selector-pseudo-element-case": "lower"|"upper",
    "selector-pseudo-element-colon-notation": "single"|"double",
    "selector-pseudo-element-no-unknown": true,
    "selector-type-case": "lower"|"upper",
    "selector-type-no-unknown": true,
    "shorthand-property-no-redundant-values": true,
    "string-no-newline": true,
    "string-quotes": "single"|"double",
    "time-min-milliseconds": int,
    "unit-blacklist": string|[],
    "unit-case": "lower"|"upper",
    "unit-no-unknown": true,
    "unit-whitelist": string|[],
    "value-keyword-case": "lower"|"upper",
    "value-list-comma-newline-after": "always"|"always-multi-line"|"never-multi-line",
    "value-list-comma-newline-before": "always"|"always-multi-line"|"never-multi-line",
    "value-list-comma-space-after": "always"|"never"|"always-single-line"|"never-single-line",
    "value-list-comma-space-before": "always"|"never"|"always-single-line"|"never-single-line",
    "value-list-max-empty-lines": int,
    "value-no-vendor-prefix": true
  }
}
<|endoftext|>