<commit_before>'use strict';

var isArray        = Array.isArray
  , join           = Array.prototype.join
  , map            = Array.prototype.map
  , push           = Array.prototype.push
  , slice          = Array.prototype.slice
  , apply          = Function.prototype.apply
  , create         = Object.create
  , defineProperty = Object.defineProperty
  , global         = require('es5-ext/lib/global')
  , toArray        = require('es5-ext/lib/Array/from')
  , indexOf        = require('es5-ext/lib/Array/prototype/e-index-of')
  , callable       = require('es5-ext/lib/Object/valid-callable')
  , isString       = require('es5-ext/lib/String/is-string')

  , resolve, memoize, id = 0;

resolve = function (args) {
	return this.map(function (r, i) {
		return r ? r(args[i]) : args[i];
	}).concat(slice.call(args, this.length));
};

// Implementation details:
//
// Results are saved internally within array matrix:
// cache[0] -> Result of calling function with no arguments
// cache[1] -> Matrix that keeps results for one argument function calls
// cache[1][0] -> Array of different arguments with which
//                function have been called
// cache[1][1] -> Array of results that matches cache[1][0] arguments array
// cache[2] -> Matrix that keeps results for two argument function calls
// cache[2][0] -> Array of different first (of two) arguments with which
//                function have been called
// cache[2][1] -> Matrixes that keeps results for two arguments function calls
//                Each matrix matches first argument found in cache[2][0]
// cache[2][1][x][0] -> Array of different second arguments with which
//                      function have been called.
// cache[2][1][x][1] -> Array of results that matches cache[2][1][x][0]
//                      arguments array
// ...and so on

memoize = module.exports = function (fn) {
	var mfn, options, length, resolver, method, cache, find, save, clear
	  , value, primitive, getPrimitiveId, profile, gc, ongcclear;

	callable(fn);
	if (fn.memoized) {
		// Prevent memoization of already memoized function
		return fn;
	}

	options = Object(arguments[1]);

	if (isNaN(options.length)) {
		length = fn.length;
	} else if (options.length === false) {
		length = options.length;
	} else {
		length = Number(options.length);
	}
	if (options.resolvers) {
		resolver = toArray(options.resolvers);
		resolver.forEach(function (r) {
			(r == null) || callable(r);
		});
		resolver = resolve.bind(resolver);
	}
	if (options.method) {
		if (isString(options.method)) {
			method = { name: String(options.method),
				descriptor: { configurable: true, writable: true } }
		} else {
			method = options.method;
			method.name = String(method.name);
			method.descriptor = (method.descriptor == null) ?
				{ configurable: true, writable: true } : Object(method.descriptor);
		}
		options = create(options);
		options.method = undefined;
	}
	primitive = Boolean(options.primitive);
	gc = Boolean(options.gc);
	if (options.ongcclear != null) {
		ongcclear = callable(options.ongcclear);
	}

	cache = primitive ? {} : [];

	if (memoize._profile) {
		profile = memoize._profile();
	}

	find =  function (length, args) {
		var index = 0, rset = cache, i;

		if (length === 0) {
			value = rset[length];
			return rset.hasOwnProperty(length);
		} else if ((rset = rset[length])) {
			while (index < (length - 1)) {
				i = indexOf.call(rset[0], args[index]);
				if (i === -1) {
					return false;
				}
				rset = rset[1][i];
				++index;
			}
			i = indexOf.call(rset[0], args[index]);
			if (i === -1) {
				return false;
			}
			value = rset[1][i];
			return true;
		}
		return false;
	};

	save = function (length, args, value) {
		var index = 0, rset = cache, i;

		if (gc) {
			value = { value: value, count: 1 };
		}
		if (length === 0) {
			rset[length] = value;
		} else {
			if (!rset[length]) {
				rset[length] = [[], []];
			}
			rset = rset[length];
			while (index < (length - 1)) {
				i = indexOf.call(rset[0], args[index]);
				if (i === -1) {
					i = rset[0].push(args[index]) - 1;
					rset[1].push([[], []]);
				}
				rset = rset[1][i];
				++index;
			}
			i = indexOf.call(rset[0], args[index]);
			if (i === -1) {
				i = rset[0].push(args[index]) - 1;
			}
			rset[1][i] = value;
		}
	};

	clear = function (length, args) {
		var index = 0, rset = cache, i, path = [], value;

		if (length === 0) {
			delete rset[length];
		} else if ((rset = rset[length])) {
			while (index < (length - 1)) {
				i = indexOf.call(rset[0], args[index]);
				if (i === -1) {
					return;
				}
				path.push(rset, i);
				rset = rset[1][i];
				++index;
			}
			i = indexOf.call(rset[0], args[index]);
			if (i === -1) {
				return;
			}
			rset[0].splice(i, 1);
			rset[1].splice(i, 1);
			while (!rset[0].length && path.length) {
				i = path.pop();
				rset = path.pop();
				rset[0].splice(i, 1);
				rset[1].splice(i, 1);
			}
		}
	};

	getPrimitiveId = function (length, args) {
		var argsLength;
		if (length) {
			argsLength = args.length;
			if (length < argsLength) {
				args = slice.call(args, 0, length);
			} else if (length > argsLength) {
				args = toArray(args);
				push.apply(args, Array(length - argsLength));
			}
			return (length > 1) ? join.call(args, '\u0001') :
				(args[0] + '\u0002');
		} else {
			return '';
		}
	};

	mfn = function () {
		var args, alength, id;
		if (method && this && (this !== global)) {
			method.descriptor.value = memoize(fn.bind(this), options);
			defineProperty(this, method.name, method.descriptor);
			return method.descriptor.value.apply(this, arguments);
		}
		args = resolver ? resolver(arguments) : arguments;
		alength = (length === false) ? args.length : length;

		if (primitive) {
			id = getPrimitiveId(alength, args);
			if (cache.hasOwnProperty(id)) {
				profile && ++profile.cached;
				if (gc) {
					++cache[id].count;
					return cache[id].value;
				}
				return cache[id];
			} else {
				profile && ++profile.initial;
				mfn.args = arguments;
				mfn.preventCache = false;
				value = apply.call(fn, this, args);
				if (!mfn.preventCache) {
					cache[id] = gc ? { value: value, count: 1 } : value;
				}
				delete mfn.args;
				return value;
			}
		}
		if (find(alength, args)) {
			profile && ++profile.cached;
			if (gc) {
				++value.count;
				return value.value;
			}
			return value;
		} else {
			profile && ++profile.initial;
			mfn.args = arguments;
			mfn.preventCache = false;
			value = apply.call(fn, this, args);
			if (!mfn.preventCache) {
				save(alength, args, value);
			}
			delete mfn.args;
			return value;
		}
	};
	mfn.memoized = true;

	mfn.clear = function () {
		var args, alength, id;
		args = resolver ? resolver(arguments) : arguments;
		alength = (length === false) ? args.length : length;

		if (primitive) {
			id = getPrimitiveId(alength, args);
			delete cache[id];
		} else {
			clear(alength, args);
		}
	};

	mfn.clearAll = function () {
		cache = primitive ? {} : [];
	};

	if (gc) {
		mfn.clearRef = function () {
			var args, alength;
			args = resolver ? resolver(arguments) : arguments;
			alength = (length === false) ? args.length : length;

			if (primitive) {
				if (!(value = cache[getPrimitiveId(alength, args)])) {
					return;
				}
			} else if (!find(alength, args)) {
				return;
			}
			if (!--value.count) {
				mfn.clear.apply(null, arguments);
				if (ongcclear) {
					ongcclear(value.value, args, arguments);
				}
			}
		};
	}

	return mfn;
};
<commit_msg>Return true if clearRef cleared all references<commit_after>'use strict';

var isArray        = Array.isArray
  , join           = Array.prototype.join
  , map            = Array.prototype.map
  , push           = Array.prototype.push
  , slice          = Array.prototype.slice
  , apply          = Function.prototype.apply
  , create         = Object.create
  , defineProperty = Object.defineProperty
  , global         = require('es5-ext/lib/global')
  , toArray        = require('es5-ext/lib/Array/from')
  , indexOf        = require('es5-ext/lib/Array/prototype/e-index-of')
  , callable       = require('es5-ext/lib/Object/valid-callable')
  , isString       = require('es5-ext/lib/String/is-string')

  , resolve, memoize, id = 0;

resolve = function (args) {
	return this.map(function (r, i) {
		return r ? r(args[i]) : args[i];
	}).concat(slice.call(args, this.length));
};

// Implementation details:
//
// Results are saved internally within array matrix:
// cache[0] -> Result of calling function with no arguments
// cache[1] -> Matrix that keeps results for one argument function calls
// cache[1][0] -> Array of different arguments with which
//                function have been called
// cache[1][1] -> Array of results that matches cache[1][0] arguments array
// cache[2] -> Matrix that keeps results for two argument function calls
// cache[2][0] -> Array of different first (of two) arguments with which
//                function have been called
// cache[2][1] -> Matrixes that keeps results for two arguments function calls
//                Each matrix matches first argument found in cache[2][0]
// cache[2][1][x][0] -> Array of different second arguments with which
//                      function have been called.
// cache[2][1][x][1] -> Array of results that matches cache[2][1][x][0]
//                      arguments array
// ...and so on

memoize = module.exports = function (fn) {
	var mfn, options, length, resolver, method, cache, find, save, clear
	  , value, primitive, getPrimitiveId, profile, gc, ongcclear;

	callable(fn);
	if (fn.memoized) {
		// Prevent memoization of already memoized function
		return fn;
	}

	options = Object(arguments[1]);

	if (isNaN(options.length)) {
		length = fn.length;
	} else if (options.length === false) {
		length = options.length;
	} else {
		length = Number(options.length);
	}
	if (options.resolvers) {
		resolver = toArray(options.resolvers);
		resolver.forEach(function (r) {
			(r == null) || callable(r);
		});
		resolver = resolve.bind(resolver);
	}
	if (options.method) {
		if (isString(options.method)) {
			method = { name: String(options.method),
				descriptor: { configurable: true, writable: true } }
		} else {
			method = options.method;
			method.name = String(method.name);
			method.descriptor = (method.descriptor == null) ?
				{ configurable: true, writable: true } : Object(method.descriptor);
		}
		options = create(options);
		options.method = undefined;
	}
	primitive = Boolean(options.primitive);
	gc = Boolean(options.gc);
	if (options.ongcclear != null) {
		ongcclear = callable(options.ongcclear);
	}

	cache = primitive ? {} : [];

	if (memoize._profile) {
		profile = memoize._profile();
	}

	find =  function (length, args) {
		var index = 0, rset = cache, i;

		if (length === 0) {
			value = rset[length];
			return rset.hasOwnProperty(length);
		} else if ((rset = rset[length])) {
			while (index < (length - 1)) {
				i = indexOf.call(rset[0], args[index]);
				if (i === -1) {
					return false;
				}
				rset = rset[1][i];
				++index;
			}
			i = indexOf.call(rset[0], args[index]);
			if (i === -1) {
				return false;
			}
			value = rset[1][i];
			return true;
		}
		return false;
	};

	save = function (length, args, value) {
		var index = 0, rset = cache, i;

		if (gc) {
			value = { value: value, count: 1 };
		}
		if (length === 0) {
			rset[length] = value;
		} else {
			if (!rset[length]) {
				rset[length] = [[], []];
			}
			rset = rset[length];
			while (index < (length - 1)) {
				i = indexOf.call(rset[0], args[index]);
				if (i === -1) {
					i = rset[0].push(args[index]) - 1;
					rset[1].push([[], []]);
				}
				rset = rset[1][i];
				++index;
			}
			i = indexOf.call(rset[0], args[index]);
			if (i === -1) {
				i = rset[0].push(args[index]) - 1;
			}
			rset[1][i] = value;
		}
	};

	clear = function (length, args) {
		var index = 0, rset = cache, i, path = [], value;

		if (length === 0) {
			delete rset[length];
		} else if ((rset = rset[length])) {
			while (index < (length - 1)) {
				i = indexOf.call(rset[0], args[index]);
				if (i === -1) {
					return;
				}
				path.push(rset, i);
				rset = rset[1][i];
				++index;
			}
			i = indexOf.call(rset[0], args[index]);
			if (i === -1) {
				return;
			}
			rset[0].splice(i, 1);
			rset[1].splice(i, 1);
			while (!rset[0].length && path.length) {
				i = path.pop();
				rset = path.pop();
				rset[0].splice(i, 1);
				rset[1].splice(i, 1);
			}
		}
	};

	getPrimitiveId = function (length, args) {
		var argsLength;
		if (length) {
			argsLength = args.length;
			if (length < argsLength) {
				args = slice.call(args, 0, length);
			} else if (length > argsLength) {
				args = toArray(args);
				push.apply(args, Array(length - argsLength));
			}
			return (length > 1) ? join.call(args, '\u0001') :
				(args[0] + '\u0002');
		} else {
			return '';
		}
	};

	mfn = function () {
		var args, alength, id;
		if (method && this && (this !== global)) {
			method.descriptor.value = memoize(fn.bind(this), options);
			defineProperty(this, method.name, method.descriptor);
			return method.descriptor.value.apply(this, arguments);
		}
		args = resolver ? resolver(arguments) : arguments;
		alength = (length === false) ? args.length : length;

		if (primitive) {
			id = getPrimitiveId(alength, args);
			if (cache.hasOwnProperty(id)) {
				profile && ++profile.cached;
				if (gc) {
					++cache[id].count;
					return cache[id].value;
				}
				return cache[id];
			} else {
				profile && ++profile.initial;
				mfn.args = arguments;
				mfn.preventCache = false;
				value = apply.call(fn, this, args);
				if (!mfn.preventCache) {
					cache[id] = gc ? { value: value, count: 1 } : value;
				}
				delete mfn.args;
				return value;
			}
		}
		if (find(alength, args)) {
			profile && ++profile.cached;
			if (gc) {
				++value.count;
				return value.value;
			}
			return value;
		} else {
			profile && ++profile.initial;
			mfn.args = arguments;
			mfn.preventCache = false;
			value = apply.call(fn, this, args);
			if (!mfn.preventCache) {
				save(alength, args, value);
			}
			delete mfn.args;
			return value;
		}
	};
	mfn.memoized = true;

	mfn.clear = function () {
		var args, alength, id;
		args = resolver ? resolver(arguments) : arguments;
		alength = (length === false) ? args.length : length;

		if (primitive) {
			id = getPrimitiveId(alength, args);
			delete cache[id];
		} else {
			clear(alength, args);
		}
	};

	mfn.clearAll = function () {
		cache = primitive ? {} : [];
	};

	if (gc) {
		mfn.clearRef = function () {
			var args, alength;
			args = resolver ? resolver(arguments) : arguments;
			alength = (length === false) ? args.length : length;

			if (primitive) {
				if (!(value = cache[getPrimitiveId(alength, args)])) {
					return null;
				}
			} else if (!find(alength, args)) {
				return null;
			}
			if (!--value.count) {
				mfn.clear.apply(null, arguments);
				if (ongcclear) {
					ongcclear(value.value, args, arguments);
				}
				return true;
			}
			return false;
		};
	}

	return mfn;
};
<|endoftext|>


<commit_before>import React, { PropTypes } from 'react';
import ImmutablePropTypes from 'react-immutable-proptypes';

const CreateCategories = ({ categories, category }) => {
    const categoriesArr = categories.toJS();

    return (

            <select className={category.error && category.touched ?
                'create-category__select create-category__select_error' :
                'create-category__select' } {...category}
            >

                <option value="-1">Challange category</option>
                { categoriesArr.map((cat, index) => (
                    <option value={JSON.stringify(cat)} key={index}>{cat.name}</option>
                )) }
            </select>

    );
};

CreateCategories.propTypes = {
    categories: ImmutablePropTypes.list.isRequired,
    category: PropTypes.object
};

export default CreateCategories;
<commit_msg>category field refactoring<commit_after>import React, { PropTypes } from 'react';
import ImmutablePropTypes from 'react-immutable-proptypes';

const CreateCategories = ({ categories, category }) => {
    const categoriesArr = categories.toJS();
    const placeholder = 'Challange category';

    return (

                {(category.value !== '') ? JSON.parse(category.value).name : placeholder}

            <select className={category.error && category.touched ?
                'create-category__select create-category__select_error' :
                'create-category__select' } {...category}
            >

                <option value="-1">{placeholder}</option>
                { categoriesArr.map((cat, index) => (
                    <option value={JSON.stringify(cat)} key={index}>{cat.name}</option>
                )) }
            </select>

    );
};

CreateCategories.propTypes = {
    categories: ImmutablePropTypes.list.isRequired,
    category: PropTypes.object
};

export default CreateCategories;
<|endoftext|>


<commit_before>'use strict';

var pg = require('pg');
var Promise = require('bluebird');
var pgConnect = Promise.promisify(pg.connect, pg);

var IDENTITY = function (x) { return x; };

function connect(connectionParams) {
  var done;
  return pgConnect(connectionParams)
    .spread(function(client, _done) {
      done = _done;

      function queryOne(text, values) {
        return Promise.fromNode(function (callback) {
          return client.query(text, values, callback);
        });
      }

      function queryRaw(text, values, mapFn) {
        mapFn = mapFn || IDENTITY;
        if (Array.isArray(text)) {
          return Promise.map(text, queryOne).map(mapFn);
        } else {
          return queryOne(text, values).then(mapFn);
        }
      }

      function query(text, values) {
        return queryRaw(text, values, function (result) {
          return result.rows;
        });
      }

      query.single = function (text, values) {
        return queryRaw(text, values, function (result) {
          return result.rows && result.rows[0] || null;
        });
      };

      query.raw = queryRaw;

      return query;
    })
    .disposer(function() {
      if (done) {
        done();
      }
    });
}

function queryDefault(text, values) {
  return Promise.using(connect(), function (query) {
    return query(text, values);
  });
}

queryDefault.single = function (text, values) {
  return Promise.using(connect(), function (query) {
    return query.single(text, values);
  });
};

queryDefault.raw = function (text, values) {
  return Promise.using(connect(), function (query) {
    return query.raw(text, values);
  });
};

queryDefault.connect = connect;

module.exports = queryDefault;
<commit_msg>Add default connection parameter<commit_after>'use strict';

var pg = require('pg');
var Promise = require('bluebird');
var pgConnect = Promise.promisify(pg.connect, pg);

var IDENTITY = function (x) { return x; };

function connect(connectionParams) {
  var done;
  return pgConnect(connectionParams)
    .spread(function(client, _done) {
      done = _done;

      function queryOne(text, values) {
        return Promise.fromNode(function (callback) {
          return client.query(text, values, callback);
        });
      }

      function queryRaw(text, values, mapFn) {
        mapFn = mapFn || IDENTITY;
        if (Array.isArray(text)) {
          return Promise.map(text, queryOne).map(mapFn);
        } else {
          return queryOne(text, values).then(mapFn);
        }
      }

      function query(text, values) {
        return queryRaw(text, values, function (result) {
          return result.rows;
        });
      }

      query.single = function (text, values) {
        return queryRaw(text, values, function (result) {
          return result.rows && result.rows[0] || null;
        });
      };

      query.raw = queryRaw;

      return query;
    })
    .disposer(function() {
      if (done) {
        done();
      }
    });
}

function queryDefault(text, values) {
  return Promise.using(connect(queryDefault.connectionParams), function (query) {
    return query(text, values);
  });
}

queryDefault.single = function (text, values) {
  return Promise.using(connect(queryDefault.connectionParams), function (query) {
    return query.single(text, values);
  });
};

queryDefault.raw = function (text, values) {
  return Promise.using(connect(queryDefault.connectionParams), function (query) {
    return query.raw(text, values);
  });
};

queryDefault.connect = connect;

module.exports = queryDefault;
<|endoftext|>


<commit_before>/*!
 * hemera
 * Copyright(c) 2016 Dustin Deus (deusdustin@gmail.com)
 * MIT Licensed
 */

/* jslint node: true */
'use strict';

/**
 * Module Dependencies
 */

const
  Bloomrun = require('bloomrun'),
  Debug = require('debug')('hemera'),
  SafeStringify = require('fast-safe-stringify'),
  Parse = require('fast-json-parse');

/**
 * Constants
 */

// Errors
var
  JSON_PARSE_ERROR = 'Invalid JSON payload',
  ACT_TIMEOUT_ERROR = 'Timeout',
  NO_TOPIC_TO_SUBSCRIBE = 'No topic to subscribe',
  NO_TOPIC_TO_REQUEST = 'No topic to request',
  PATTERN_ALREADY_IN_USE = 'Pattern is already in use';

/**
 *
 *
 * @class Hemera
 */
class Hemera {

  constructor(params) {

      this.catalog = Bloomrun();
      this.nats = params.nats;
      this.timeout = params.timeout || 2000;
      this.subjects = {};
    }
    /**
     *
     *
     * @param {any} cb
     *
     * @memberOf Hemera
     */
  ready(cb) {

      this.nats.on('connect', () => {
        cb();
      });

    }
    /**
     *
     *
     * @param {any} cb
     *
     * @memberOf Hemera
     */
  error(cb) {

      this.nats.on('error', (err) => {
        cb(err);
      });

    }
    /**
     *
     *
     * @param {any} topic
     * @returns
     *
     * @memberOf Hemera
     */
  subscribe(topic) {

      var self = this;

      //Avoid duplicate subsribers of the emit stream
      if (self.subjects[topic]) {
        return self.subjects[topic];
      }

      //Add subscriber
      self.nats.subscribe(topic, {
        'queue': 'queue.' + topic
      }, (request, replyTo) => {

        //Parse response as JSON
        let result = Parse(request);

        if (result.error) {
          return Debug(result.error);
        }

        let handler = this.catalog.lookup(result.value.pattern);

        if (handler) {

          handler(result.value.pattern, (resp) => {

            //Parse msg as JSON
            let msg = SafeStringify(resp);

            this.nats.publish(replyTo, msg);
          });
        } else {

          //@TODO return error back to callee
          Debug(`No handler found for signature: %s`, result.pattern);
        }

      });

      self.subjects[topic] = true;

    }
    /**
     *
     *
     * @param {any} pattern
     * @param {any} cb
     *
     * @memberOf Hemera
     */
  add(pattern, cb) {

      if (!pattern.topic) {
        throw (new Error(NO_TOPIC_TO_SUBSCRIBE));
      }

      let handler = this.catalog.lookup(pattern);

      if (handler) {
        throw (new Error(PATTERN_ALREADY_IN_USE));
      }

      //Add to bloomrun
      this.catalog.add(pattern, cb);

      //Subscribe on topic
      this.subscribe(pattern.topic);

    }
    /**
     *
     *
     * @param {any} pattern
     * @param {any} cb
     *
     * @memberOf Hemera
     */
  act(pattern, cb) {

      if (!pattern.topic) {
        throw (new Error(NO_TOPIC_TO_REQUEST));
      }

      //Parse msg as JSON
      let msg = SafeStringify({
        pattern
      });

      //Request to topic
      let sid = this.nats.request(pattern.topic, msg, (response) => {

        //Parse response as JSON
        let result = Parse(response);

        if (result.error) {

          if (typeof cb === 'function') {
            return cb(result.error);
          }

          Debug(error);
        }

        if (typeof cb === 'function') {
          cb(null, result.value);
        }
      });

      //Handle timeout
      this.nats.timeout(sid, pattern.$timeout || this.timeout, 1, () => {

        cb(new Error(ACT_TIMEOUT_ERROR));
      });

    }
    /**
     *
     *
     * @returns
     *
     * @memberOf Hemera
     */
  close() {

    return this.nats.close();

  }

}

module.exports = Hemera;<commit_msg>comment<commit_after>/*!
 * hemera
 * Copyright(c) 2016 Dustin Deus (deusdustin@gmail.com)
 * MIT Licensed
 */

/* jslint node: true */
'use strict';

/**
 * Module Dependencies
 */

const
  Bloomrun = require('bloomrun'),
  Debug = require('debug')('hemera'),
  SafeStringify = require('fast-safe-stringify'),
  Parse = require('fast-json-parse');

/**
 * Constants
 */

// Errors
var
  JSON_PARSE_ERROR = 'Invalid JSON payload',
  ACT_TIMEOUT_ERROR = 'Timeout',
  NO_TOPIC_TO_SUBSCRIBE = 'No topic to subscribe',
  NO_TOPIC_TO_REQUEST = 'No topic to request',
  PATTERN_ALREADY_IN_USE = 'Pattern is already in use';

/**
 *
 *
 * @class Hemera
 */
class Hemera {

  constructor(params) {

      this.catalog = Bloomrun();
      this.nats = params.nats;
      this.timeout = params.timeout || 2000;
      this.subjects = {};
    }
    /**
     *
     *
     * @param {any} cb
     *
     * @memberOf Hemera
     */
  ready(cb) {

      this.nats.on('connect', () => {
        cb();
      });

    }
    /**
     *
     *
     * @param {any} cb
     *
     * @memberOf Hemera
     */
  error(cb) {

      this.nats.on('error', (err) => {
        cb(err);
      });

    }
    /**
     *
     *
     * @param {any} topic
     * @returns
     *
     * @memberOf Hemera
     */
  subscribe(topic) {

      var self = this;

      //Avoid duplicate subsribers of the emit stream
      if (self.subjects[topic]) {
        return self.subjects[topic];
      }

      //Add subscriber
      self.nats.subscribe(topic, {
        'queue': 'queue.' + topic
      }, (request, replyTo) => {

        //Parse response as JSON
        let result = Parse(request);

        //@TODO error return to callee
        if (result.error) {
          return Debug(result.error);
        }

        let handler = this.catalog.lookup(result.value.pattern);

        if (handler) {

          handler(result.value.pattern, (resp) => {

            //Parse msg as JSON
            let msg = SafeStringify(resp);

            this.nats.publish(replyTo, msg);
          });
        } else {

          //@TODO return error back to callee
          Debug(`No handler found for signature: %s`, result.pattern);
        }

      });

      self.subjects[topic] = true;

    }
    /**
     *
     *
     * @param {any} pattern
     * @param {any} cb
     *
     * @memberOf Hemera
     */
  add(pattern, cb) {

      if (!pattern.topic) {
        throw (new Error(NO_TOPIC_TO_SUBSCRIBE));
      }

      let handler = this.catalog.lookup(pattern);

      if (handler) {
        throw (new Error(PATTERN_ALREADY_IN_USE));
      }

      //Add to bloomrun
      this.catalog.add(pattern, cb);

      //Subscribe on topic
      this.subscribe(pattern.topic);

    }
    /**
     *
     *
     * @param {any} pattern
     * @param {any} cb
     *
     * @memberOf Hemera
     */
  act(pattern, cb) {

      if (!pattern.topic) {
        throw (new Error(NO_TOPIC_TO_REQUEST));
      }

      //Parse msg as JSON
      let msg = SafeStringify({
        pattern
      });

      //Request to topic
      let sid = this.nats.request(pattern.topic, msg, (response) => {

        //Parse response as JSON
        let result = Parse(response);

        if (result.error) {

          if (typeof cb === 'function') {
            return cb(result.error);
          }

          Debug(error);
        }

        if (typeof cb === 'function') {
          cb(null, result.value);
        }
      });

      //Handle timeout
      this.nats.timeout(sid, pattern.$timeout || this.timeout, 1, () => {

        cb(new Error(ACT_TIMEOUT_ERROR));
      });

    }
    /**
     *
     *
     * @returns
     *
     * @memberOf Hemera
     */
  close() {

    return this.nats.close();

  }

}

module.exports = Hemera;<|endoftext|>


<commit_before>;(function () {

  xt.port.on('buffer_details', function (details) {
    var temp = document.createElement('div');
    temp.setAttribute('id', 'page-scraper');
    temp.setAttribute('data-details', escape(JSON.stringify(details)));
    document.body.appendChild(temp);
  });

  xt.port.emit("buffer_details_request");

}());<commit_msg>I hate git.<commit_after>;(function () {

  // Only allow this to run in the Buffer iframe
  if( window !== window.top && document.location.host.match(/bufferapp.com/i) ) {

    // Listen for information
    xt.port.on('buffer_details', function (details) {

      console.log("Overlay has details", details);

      // Create an element in the overlay page with the
      // details scraped externally
      var temp = document.createElement('div');
      temp.setAttribute('id', 'page-scraper');
      temp.setAttribute('data-details', escape(JSON.stringify(details)));
      document.body.appendChild(temp);

    });

    // Ask for the details
    xt.port.emit("buffer_details_request");

  }

}());<|endoftext|>


<commit_before>import { inject as service } from '@ember/service';
import Component from '@ember/component';
import $ from 'jquery';
import ol from 'openlayers';
import { tag } from 'ember-awesome-macros';
import { htmlSafe } from 'ember-awesome-macros/string';

import config from '../config/environment';
import parseQueryString from '../utils/parse-query-string';

export default Component.extend({
  cookies: service(),

  attributeBindings: ['style'],

  width: '100%',
  height: '100%',
  baseLayer: null,

  style: htmlSafe(tag`width: ${'width'}; height: ${'height'}; position: relative`),

  init() {
    this._super(...arguments);

    window.flightMap = this;

    let interactions = ol.interaction.defaults({
      altShiftDragRotate: false,
      pinchRotate: false,
    });

    let map = new ol.Map({
      view: new ol.View({
        center: ol.proj.transform([10, 50], 'EPSG:4326', 'EPSG:3857'),
        maxZoom: 17,
        zoom: 5,
      }),
      controls: ol.control.defaults().extend([
        new ol.control.ScaleLine(),
      ]),
      interactions,
      ol3Logo: false,
    });
    this.set('map', map);

    map.getViewport().setAttribute('tabindex', '0');
    $(map.getViewport()).click(function() {
      $(this).focus();
    });

    let osm_layer = new ol.layer.Tile({
      source: new ol.source.OSM(),
      zIndex: 1,
    });

    osm_layer.setProperties({
      'name': 'OpenStreetMap',
      'id': 'OpenStreetMap',
      'base_layer': true,
      'display_in_layer_switcher': true,
    });

    map.addLayer(osm_layer);

    this.addReliefLayer();
    this.addAirspaceLayers();
    this.addMWPLayers();
    this.addBingLayers();
    this.addMapboxLayer();
    this.addEmptyLayer();

    let query = parseQueryString(window.location.search);
    this.set('baseLayer', query.baselayer);
    this.set('overlayLayers', query.overlays);

    let cookies = this.get('cookies');
    this.setBaseLayer(this.get('baseLayer') || cookies.read('base_layer') || 'OpenStreetMap');
    this.setOverlayLayers(this.get('overlayLayers') || cookies.read('overlay_layers') || 'Airspace');
  },

  didInsertElement() {
    this._super(...arguments);
    let map = this.get('map');
    if (map) {
      map.setTarget(this.elementId);
    }
  },

  setBaseLayer(base_layer) {
    if (!base_layer) {
      return;
    }

    let fallback = false;
    let map = this.get('map');

    map.getLayers().forEach(layer => {
      if (layer.get('base_layer')) {
        layer.setVisible(layer.get('name') === base_layer);
        fallback = fallback || layer.get('name') === base_layer;
      }
    });

    if (!fallback) {
      map.getLayers().getArray().filter(function(e) {
        return e.get('name') === 'OpenStreetMap';
      })[0].setVisible(true);
    }
  },

  setOverlayLayers(overlay_layers) {
    if (!overlay_layers) {
      return;
    }

    overlay_layers = overlay_layers.split(';');

    // Cycle through the overlay layers to find a match
    this.get('map').getLayers().forEach(layer => {
      if (layer.get('base_layer') || !layer.get('display_in_layer_switcher')) {
        return;
      }

      layer.setVisible($.inArray(layer.get('name'), overlay_layers) !== -1);
    });
  },

  addMWPLayers() {
    let tile_url = this.getWithDefault('mapTileURL', '');

    let mwp_layer = new ol.layer.Tile({
      source: new ol.source.XYZ({
        attributions: [
          new ol.Attribution({
            html: 'Mountain Wave Data © ' +
                '' +
                'Mountain Wave Project' +
                '.',
          }),
        ],
        url: `${tile_url}/tiles/1.0.0/mwp/{z}/{x}/{y}.png`,
      }),
      zIndex: 11,
    });

    mwp_layer.setProperties({
      'name': 'Mountain Wave Project',
      'id': 'MountainWaveProject',
      'base_layer': false,
      'display_in_layer_switcher': true,
    });

    this.get('map').addLayer(mwp_layer);
  },

  addAirspaceLayers() {
    let airspace_layer = new ol.layer.Tile({
      source: new ol.source.XYZ({
        url: `${config.SKYLINES_TILE_BASEURL || ''}/tiles/1.0.0/airspace+airports/{z}/{x}/{y}.png`,
      }),
      zIndex: 10,
    });

    airspace_layer.setProperties({
      'name': 'Airspace',
      'id': 'Airspace',
      'base_layer': false,
      'display_in_layer_switcher': true,
    });

    this.get('map').addLayer(airspace_layer);
  },

  addReliefLayer() {
    let url = 'http://maps-for-free.com/layer/relief/z{z}/row{y}/{z}_{x}-{y}.jpg';

    let relief_layer = new ol.layer.Tile({
      source: new ol.source.XYZ({
        attributions: [
          new ol.Attribution({
            html: 'SRTM relief maps from maps-for-free.com',
          }),
        ],
        url,
      }),
      zIndex: 2,
    });

    relief_layer.setProperties({
      'name': 'Shaded Relief',
      'id': 'ShadedRelief',
      'base_layer': true,
      'display_in_layer_switcher': true,
    });

    this.get('map').addLayer(relief_layer);
  },

  addMapboxLayer() {
    let tile_url = config.MAPBOX_TILE_URL;
    if (!tile_url) { return; }

    let mapbox_layer = new ol.layer.Tile({
      source: new ol.source.XYZ({
        attributions: [
          new ol.Attribution({
            html: '' +
                '© Mapbox © OpenStreetMap Improve this map',
          }),
        ],
        url: tile_url,
      }),
      zIndex: 5,
    });

    mapbox_layer.setProperties({
      'name': 'Terrain',
      'id': 'Terrain',
      'base_layer': true,
      'display_in_layer_switcher': true,
    });

    this.get('map').addLayer(mapbox_layer);
  },

  addBingLayers() {
    let api_key = config.BING_API_KEY;
    if (!api_key) { return; }

    // Bing's Road imagerySet
    let road = new ol.layer.Tile({
      source: new ol.source.BingMaps({
        key: api_key,
        imagerySet: 'Road',
      }),
      zIndex: 3,
    });

    road.setProperties({
      'name': 'Bing Road',
      'id': 'BingRoad',
      'base_layer': true,
      'display_in_layer_switcher': true,
    });

    // Bing's AerialWithLabels imagerySet
    let hybrid = new ol.layer.Tile({
      source: new ol.source.BingMaps({
        key: api_key,
        imagerySet: 'AerialWithLabels',
      }),
      zIndex: 4,
    });

    hybrid.setProperties({
      'name': 'Bing Satellite',
      'id': 'BingSatellite',
      'base_layer': true,
      'display_in_layer_switcher': true,
    });

    let map = this.get('map');
    map.addLayer(road);
    map.addLayer(hybrid);
  },

  addEmptyLayer() {
    let empty_layer = new ol.layer.Tile({
    });
    empty_layer.setProperties({
      'name': 'Empty',
      'id': 'Empty',
      'base_layer': true,
      'display_in_layer_switcher': true,
    });

    this.get('map').addLayer(empty_layer);
  },

});
<commit_msg>components/base-map: Use `map-settings` service<commit_after>import { inject as service } from '@ember/service';
import Component from '@ember/component';
import $ from 'jquery';
import ol from 'openlayers';
import { tag } from 'ember-awesome-macros';
import { htmlSafe } from 'ember-awesome-macros/string';

import config from '../config/environment';

export default Component.extend({
  mapSettings: service(),

  attributeBindings: ['style'],

  width: '100%',
  height: '100%',

  style: htmlSafe(tag`width: ${'width'}; height: ${'height'}; position: relative`),

  init() {
    this._super(...arguments);

    window.flightMap = this;

    let interactions = ol.interaction.defaults({
      altShiftDragRotate: false,
      pinchRotate: false,
    });

    let map = new ol.Map({
      view: new ol.View({
        center: ol.proj.transform([10, 50], 'EPSG:4326', 'EPSG:3857'),
        maxZoom: 17,
        zoom: 5,
      }),
      controls: ol.control.defaults().extend([
        new ol.control.ScaleLine(),
      ]),
      interactions,
      ol3Logo: false,
    });
    this.set('map', map);

    map.getViewport().setAttribute('tabindex', '0');
    $(map.getViewport()).click(function() {
      $(this).focus();
    });

    let osm_layer = new ol.layer.Tile({
      source: new ol.source.OSM(),
      zIndex: 1,
    });

    osm_layer.setProperties({
      'name': 'OpenStreetMap',
      'id': 'OpenStreetMap',
      'base_layer': true,
      'display_in_layer_switcher': true,
    });

    map.addLayer(osm_layer);

    this.addReliefLayer();
    this.addAirspaceLayers();
    this.addMWPLayers();
    this.addBingLayers();
    this.addMapboxLayer();
    this.addEmptyLayer();

    let mapSettings = this.get('mapSettings');
    this.setBaseLayer(mapSettings.get('baseLayer'));
    this.setOverlayLayers(mapSettings.get('overlayLayers'));
  },

  didInsertElement() {
    this._super(...arguments);
    let map = this.get('map');
    if (map) {
      map.setTarget(this.elementId);
    }
  },

  setBaseLayer(base_layer) {
    if (!base_layer) {
      return;
    }

    let fallback = false;
    let map = this.get('map');

    map.getLayers().forEach(layer => {
      if (layer.get('base_layer')) {
        layer.setVisible(layer.get('name') === base_layer);
        fallback = fallback || layer.get('name') === base_layer;
      }
    });

    if (!fallback) {
      map.getLayers().getArray().filter(function(e) {
        return e.get('name') === 'OpenStreetMap';
      })[0].setVisible(true);
    }
  },

  setOverlayLayers(overlay_layers) {
    // Cycle through the overlay layers to find a match
    this.get('map').getLayers().forEach(layer => {
      if (layer.get('base_layer') || !layer.get('display_in_layer_switcher')) {
        return;
      }

      layer.setVisible($.inArray(layer.get('name'), overlay_layers) !== -1);
    });
  },

  addMWPLayers() {
    let tile_url = this.getWithDefault('mapTileURL', '');

    let mwp_layer = new ol.layer.Tile({
      source: new ol.source.XYZ({
        attributions: [
          new ol.Attribution({
            html: 'Mountain Wave Data © ' +
                '' +
                'Mountain Wave Project' +
                '.',
          }),
        ],
        url: `${tile_url}/tiles/1.0.0/mwp/{z}/{x}/{y}.png`,
      }),
      zIndex: 11,
    });

    mwp_layer.setProperties({
      'name': 'Mountain Wave Project',
      'id': 'MountainWaveProject',
      'base_layer': false,
      'display_in_layer_switcher': true,
    });

    this.get('map').addLayer(mwp_layer);
  },

  addAirspaceLayers() {
    let airspace_layer = new ol.layer.Tile({
      source: new ol.source.XYZ({
        url: `${config.SKYLINES_TILE_BASEURL || ''}/tiles/1.0.0/airspace+airports/{z}/{x}/{y}.png`,
      }),
      zIndex: 10,
    });

    airspace_layer.setProperties({
      'name': 'Airspace',
      'id': 'Airspace',
      'base_layer': false,
      'display_in_layer_switcher': true,
    });

    this.get('map').addLayer(airspace_layer);
  },

  addReliefLayer() {
    let url = 'http://maps-for-free.com/layer/relief/z{z}/row{y}/{z}_{x}-{y}.jpg';

    let relief_layer = new ol.layer.Tile({
      source: new ol.source.XYZ({
        attributions: [
          new ol.Attribution({
            html: 'SRTM relief maps from maps-for-free.com',
          }),
        ],
        url,
      }),
      zIndex: 2,
    });

    relief_layer.setProperties({
      'name': 'Shaded Relief',
      'id': 'ShadedRelief',
      'base_layer': true,
      'display_in_layer_switcher': true,
    });

    this.get('map').addLayer(relief_layer);
  },

  addMapboxLayer() {
    let tile_url = config.MAPBOX_TILE_URL;
    if (!tile_url) { return; }

    let mapbox_layer = new ol.layer.Tile({
      source: new ol.source.XYZ({
        attributions: [
          new ol.Attribution({
            html: '' +
                '© Mapbox © OpenStreetMap Improve this map',
          }),
        ],
        url: tile_url,
      }),
      zIndex: 5,
    });

    mapbox_layer.setProperties({
      'name': 'Terrain',
      'id': 'Terrain',
      'base_layer': true,
      'display_in_layer_switcher': true,
    });

    this.get('map').addLayer(mapbox_layer);
  },

  addBingLayers() {
    let api_key = config.BING_API_KEY;
    if (!api_key) { return; }

    // Bing's Road imagerySet
    let road = new ol.layer.Tile({
      source: new ol.source.BingMaps({
        key: api_key,
        imagerySet: 'Road',
      }),
      zIndex: 3,
    });

    road.setProperties({
      'name': 'Bing Road',
      'id': 'BingRoad',
      'base_layer': true,
      'display_in_layer_switcher': true,
    });

    // Bing's AerialWithLabels imagerySet
    let hybrid = new ol.layer.Tile({
      source: new ol.source.BingMaps({
        key: api_key,
        imagerySet: 'AerialWithLabels',
      }),
      zIndex: 4,
    });

    hybrid.setProperties({
      'name': 'Bing Satellite',
      'id': 'BingSatellite',
      'base_layer': true,
      'display_in_layer_switcher': true,
    });

    let map = this.get('map');
    map.addLayer(road);
    map.addLayer(hybrid);
  },

  addEmptyLayer() {
    let empty_layer = new ol.layer.Tile({
    });
    empty_layer.setProperties({
      'name': 'Empty',
      'id': 'Empty',
      'base_layer': true,
      'display_in_layer_switcher': true,
    });

    this.get('map').addLayer(empty_layer);
  },

});
<|endoftext|>


<commit_before>'use babel';

// eslint-disable-next-line import/extensions, import/no-extraneous-dependencies
import { CompositeDisposable } from 'atom';
import FS from 'fs';
import { dirname } from 'path';
import YAML from 'js-yaml';

const makeEngineString = engineNames => (
  engineNames.map(language => (`-e ${language}`))
).join(' ');

const getEnabledEngines = (configFilePath) => {
  const configYaml = YAML.safeLoad(FS.readFileSync(configFilePath, 'utf8'));
  const result = new Set();
  Object.keys(configYaml.engines).forEach((engineKey) => {
    const engine = configYaml.engines[engineKey];
    if (engine.enabled === true) {
      result.add(engineKey);
    }
  });
  return result;
};

const badPaths = new Set();

const startMeasure = (baseName) => {
  performance.mark(`${baseName}-start`);
};

const endMeasure = (baseName) => {
  if (atom.inDevMode()) {
    performance.mark(`${baseName}-end`);
    performance.measure(baseName, `${baseName}-start`, `${baseName}-end`);
    // eslint-disable-next-line no-console
    console.log(`${baseName} took: `, performance.getEntriesByName(baseName)[0].duration);
    performance.clearMarks(`${baseName}-end`);
    performance.clearMeasures(baseName);
  }
  performance.clearMarks(`${baseName}-start`);
};

export default {
  activate() {
    this.subscriptions = new CompositeDisposable();
    this.subscriptions.add(atom.config.observe(
      'linter-codeclimate.executablePath', (value) => {
        this.executablePath = value;
      },
    ));
  },

  deactivate() {
    this.subscriptions.dispose();
  },

  provideLinter() {
    const Helpers = require('atom-linter');
    const configurationFile = '.codeclimate.yml';
    const linterMap = {
      '*': ['fixme'],
      Ruby: ['rubocop', 'reek'],
      'Ruby on Rails': ['rubocop', 'reek'],
      'Ruby on Rails (RJS)': ['rubocop', 'reek'],
      JavaScript: ['eslint'],
      CoffeeScript: ['coffeelint'],
      'CoffeeScript (Literate)': ['coffeelint'],
      Python: ['pep8', 'radon'],
      PHP: ['phpcodesniffer', 'phpmd'],
      Go: ['gofmt', 'golint', 'govet'],
      'GitHub Markdown': ['markdownlint'],
    };
    return {
      name: 'Code Climate',
      grammarScopes: ['*'],
      scope: 'file',
      lint: async (textEditor) => {
        // Make sure executable path exists
        if (!FS.existsSync(this.executablePath)) {
          if (!badPaths.has(this.executablePath)) {
            const msg = 'codeclimate binary not found! Installation ' +
            'instructions at http://github.com/codeclimate/codeclimate';
            atom.notifications.addError(msg);
            // Only notify once per path
            badPaths.add(this.executablePath);
          }
          return [];
        }

        const filePath = textEditor.getPath();
        const fileDir = dirname(filePath);
        const grammarName = textEditor.getGrammar().name;
        const linterNames = new Set();
        // Add the generic 'fixme' linter
        linterNames.add(linterMap['*'][0]);

        // Search for a .codeclimate.yml in the project tree. If one isn't found,
        // use the presence of a .git directory as the assumed project root,
        // and offer to create a .codeclimate.yml file there. If the user doesn't
        // want one, and says no, we won't bug them again.
        const configurationFilePath = await Helpers.findAsync(fileDir, configurationFile);
        if (configurationFilePath === null) {
          const gitDir = dirname(await Helpers.findAsync(fileDir, '.git'));

          if (atom.config.get('linter-codeclimate.init') !== false) {
            const message = 'No .codeclimate.yml file found. Should I ' +
              `initialize one for you in ${gitDir}?`;
            // eslint-disable-next-line no-alert
            const initRepo = confirm(message);
            if (initRepo) {
              try {
                await Helpers.exec(
                  '/bin/bash',
                  [`-lc '${this.executablePath} init'`],
                  { cwd: gitDir },
                );
                atom.notifications.addSuccess('init complete. Save your code ' +
                  'again to run Code Climate analysis.');
              } catch (error) {
                atom.notifications.addError('Unable to initialize ' +
                  `.codeclimate.yml file in ${gitDir}`);
              }
            } else {
              atom.config.set('linter-codeclimate.init', false);
            }
          }
          return [];
        }

        // Construct the list of linters to be passed to the CLI by looking at
        // the linters made available for our language grammar by the LinterMap,
        // and whether or not the engines are enabled in a user's config file.
        if (Object.prototype.hasOwnProperty.call(linterMap, grammarName) === true) {
          // for (const linter of linterMap[grammarName]) {
          linterMap[grammarName].forEach((linter) => {
            linterNames.add(linter);
          });
        }
        const configEnabledEngines = getEnabledEngines(configurationFilePath);
        const linterEnabledEngines = Array.from(linterNames).filter(
          linterName => configEnabledEngines.has(linterName));

        // Construct the command line invocation which runs the Code Climate CLI
        const cmd = [this.executablePath, 'analyze',
          '-f json',
          makeEngineString(linterEnabledEngines),
          `'${atom.project.relativize(filePath)}'`,
          '< /dev/null'].join(' ');

        // Debug the command executed to run the Code Climate CLI to the console
        if (atom.inDevMode()) {
          // eslint-disable-next-line no-console
          console.log(`linter-codeclimate:: Command: \`${cmd}\``);
        }

        // Start measure for how long the analysis took.
        startMeasure('linter-codeclimate: Analysis');

        // Execute the Code Climate CLI, parse the results, and emit them to the
        // Linter package as warnings. The Linter package handles the styling.
        const execArgs = ['-lc', cmd];
        const execOpts = {
          cwd: dirname(configurationFilePath),
        };
        const result = await Helpers.exec('/bin/bash', execArgs, execOpts);
        const messages = JSON.parse(result);
        const linterResults = [];
        let range;
        Object.keys(messages).forEach((issueKey) => {
          const issue = messages[issueKey];
          if (Object.prototype.hasOwnProperty.call(issue.location, 'positions')) {
            const line = issue.location.positions.begin.line - 1;
            let colStart;
            let colEnd;
            if (issue.location.positions.begin.column !== undefined) {
              colStart = (issue.location.positions.begin.column - 1) || 0;
              if (issue.location.positions.end.column !== undefined) {
                // Valid end column, attempt to generate full range
                colEnd = issue.location.positions.begin.column - 1;
              }
              if (colEnd !== undefined && colStart !== colEnd) {
                // Valid end column, and it isn't the same as the start
                range = [[line, colStart], [line, colEnd]];
              } else {
                // No valid end column, let generateRange highlight a word
                range = Helpers.generateRange(textEditor, line, colStart);
              }
            } else {
              // No valid starting column, just treat it as a line number
              range = Helpers.generateRange(textEditor, line);
            }
          } else {
            // Issue only has a line number
            const line = issue.location.lines.begin - 1;
            range = Helpers.generateRange(textEditor, line);
          }

          linterResults.push({
            type: 'Warning',
            text: issue.description,
            filePath,
            range,
          });
        });

        // Log the length of time it took to run analysis
        endMeasure('linter-codeclimate: Analysis');
        return linterResults;
      },
    };
  },
};
<commit_msg>Handle invalid JSON from codeclimate<commit_after>'use babel';

// eslint-disable-next-line import/extensions, import/no-extraneous-dependencies
import { CompositeDisposable } from 'atom';
import FS from 'fs';
import { dirname } from 'path';
import YAML from 'js-yaml';

const makeEngineString = engineNames => (
  engineNames.map(language => (`-e ${language}`))
).join(' ');

const getEnabledEngines = (configFilePath) => {
  const configYaml = YAML.safeLoad(FS.readFileSync(configFilePath, 'utf8'));
  const result = new Set();
  Object.keys(configYaml.engines).forEach((engineKey) => {
    const engine = configYaml.engines[engineKey];
    if (engine.enabled === true) {
      result.add(engineKey);
    }
  });
  return result;
};

const badPaths = new Set();

const startMeasure = (baseName) => {
  performance.mark(`${baseName}-start`);
};

const endMeasure = (baseName) => {
  if (atom.inDevMode()) {
    performance.mark(`${baseName}-end`);
    performance.measure(baseName, `${baseName}-start`, `${baseName}-end`);
    // eslint-disable-next-line no-console
    console.log(`${baseName} took: `, performance.getEntriesByName(baseName)[0].duration);
    performance.clearMarks(`${baseName}-end`);
    performance.clearMeasures(baseName);
  }
  performance.clearMarks(`${baseName}-start`);
};

export default {
  activate() {
    this.subscriptions = new CompositeDisposable();
    this.subscriptions.add(atom.config.observe(
      'linter-codeclimate.executablePath', (value) => {
        this.executablePath = value;
      },
    ));
  },

  deactivate() {
    this.subscriptions.dispose();
  },

  provideLinter() {
    const Helpers = require('atom-linter');
    const configurationFile = '.codeclimate.yml';
    const linterMap = {
      '*': ['fixme'],
      Ruby: ['rubocop', 'reek'],
      'Ruby on Rails': ['rubocop', 'reek'],
      'Ruby on Rails (RJS)': ['rubocop', 'reek'],
      JavaScript: ['eslint'],
      CoffeeScript: ['coffeelint'],
      'CoffeeScript (Literate)': ['coffeelint'],
      Python: ['pep8', 'radon'],
      PHP: ['phpcodesniffer', 'phpmd'],
      Go: ['gofmt', 'golint', 'govet'],
      'GitHub Markdown': ['markdownlint'],
    };
    return {
      name: 'Code Climate',
      grammarScopes: ['*'],
      scope: 'file',
      lint: async (textEditor) => {
        // Make sure executable path exists
        if (!FS.existsSync(this.executablePath)) {
          if (!badPaths.has(this.executablePath)) {
            const msg = 'codeclimate binary not found! Installation ' +
            'instructions at http://github.com/codeclimate/codeclimate';
            atom.notifications.addError(msg);
            // Only notify once per path
            badPaths.add(this.executablePath);
          }
          return [];
        }

        const filePath = textEditor.getPath();
        const fileDir = dirname(filePath);
        const grammarName = textEditor.getGrammar().name;
        const linterNames = new Set();
        // Add the generic 'fixme' linter
        linterNames.add(linterMap['*'][0]);

        // Search for a .codeclimate.yml in the project tree. If one isn't found,
        // use the presence of a .git directory as the assumed project root,
        // and offer to create a .codeclimate.yml file there. If the user doesn't
        // want one, and says no, we won't bug them again.
        const configurationFilePath = await Helpers.findAsync(fileDir, configurationFile);
        if (configurationFilePath === null) {
          const gitDir = dirname(await Helpers.findAsync(fileDir, '.git'));

          if (atom.config.get('linter-codeclimate.init') !== false) {
            const message = 'No .codeclimate.yml file found. Should I ' +
              `initialize one for you in ${gitDir}?`;
            // eslint-disable-next-line no-alert
            const initRepo = confirm(message);
            if (initRepo) {
              try {
                await Helpers.exec(
                  '/bin/bash',
                  [`-lc '${this.executablePath} init'`],
                  { cwd: gitDir },
                );
                atom.notifications.addSuccess('init complete. Save your code ' +
                  'again to run Code Climate analysis.');
              } catch (error) {
                atom.notifications.addError('Unable to initialize ' +
                  `.codeclimate.yml file in ${gitDir}`);
              }
            } else {
              atom.config.set('linter-codeclimate.init', false);
            }
          }
          return [];
        }

        // Construct the list of linters to be passed to the CLI by looking at
        // the linters made available for our language grammar by the LinterMap,
        // and whether or not the engines are enabled in a user's config file.
        if (Object.prototype.hasOwnProperty.call(linterMap, grammarName) === true) {
          // for (const linter of linterMap[grammarName]) {
          linterMap[grammarName].forEach((linter) => {
            linterNames.add(linter);
          });
        }
        const configEnabledEngines = getEnabledEngines(configurationFilePath);
        const linterEnabledEngines = Array.from(linterNames).filter(
          linterName => configEnabledEngines.has(linterName));

        // Construct the command line invocation which runs the Code Climate CLI
        const cmd = [this.executablePath, 'analyze',
          '-f json',
          makeEngineString(linterEnabledEngines),
          `'${atom.project.relativize(filePath)}'`,
          '< /dev/null'].join(' ');

        // Debug the command executed to run the Code Climate CLI to the console
        if (atom.inDevMode()) {
          // eslint-disable-next-line no-console
          console.log(`linter-codeclimate:: Command: \`${cmd}\``);
        }

        // Start measure for how long the analysis took.
        startMeasure('linter-codeclimate: Analysis');

        // Execute the Code Climate CLI, parse the results, and emit them to the
        // Linter package as warnings. The Linter package handles the styling.
        const execArgs = ['-lc', cmd];
        const execOpts = {
          cwd: dirname(configurationFilePath),
        };
        const result = await Helpers.exec('/bin/bash', execArgs, execOpts);
        let messages;
        try {
          messages = JSON.parse(result);
        } catch (e) {
          // eslint-disable-next-line no-console
          console.error(
            'Invalid JSON returned from codeclimate, error and output attached.',
            e, result);
          return [];
        }
        const linterResults = [];
        let range;
        Object.keys(messages).forEach((issueKey) => {
          const issue = messages[issueKey];
          if (Object.prototype.hasOwnProperty.call(issue.location, 'positions')) {
            const line = issue.location.positions.begin.line - 1;
            let colStart;
            let colEnd;
            if (issue.location.positions.begin.column !== undefined) {
              colStart = (issue.location.positions.begin.column - 1) || 0;
              if (issue.location.positions.end.column !== undefined) {
                // Valid end column, attempt to generate full range
                colEnd = issue.location.positions.begin.column - 1;
              }
              if (colEnd !== undefined && colStart !== colEnd) {
                // Valid end column, and it isn't the same as the start
                range = [[line, colStart], [line, colEnd]];
              } else {
                // No valid end column, let generateRange highlight a word
                range = Helpers.generateRange(textEditor, line, colStart);
              }
            } else {
              // No valid starting column, just treat it as a line number
              range = Helpers.generateRange(textEditor, line);
            }
          } else {
            // Issue only has a line number
            const line = issue.location.lines.begin - 1;
            range = Helpers.generateRange(textEditor, line);
          }

          linterResults.push({
            type: 'Warning',
            text: issue.description,
            filePath,
            range,
          });
        });

        // Log the length of time it took to run analysis
        endMeasure('linter-codeclimate: Analysis');
        return linterResults;
      },
    };
  },
};
<|endoftext|>


<commit_before>/*
 * excel-regression
 * Copyright(c) Leonardo Fachetti
 * MIT Licensed
 */

var validation = require('./utils/validation');
var math = require('./utils/math');
var Regression = require('./bean/regression');

var exports = module.exports = {};

exports.calculate = function (values) {
    validation.validate(values);
    var excelRegression = new Regression();

    var regression = math.linearRegression(values);

    excelRegression.getResidual().setObservation(math.residual.observation(values));
    excelRegression.getResidual().setPredictedY(math.residual.predictedY(values));
    excelRegression.getResidual().setResiduals(math.residual.residuals(values));

    excelRegression.getAnova().getIntercept().setCoefficient(math.anova.intercept.coefficient(values));
    excelRegression.getAnova().getVarX1().setCoefficient(math.anova.varX1.coefficient(values));
    excelRegression.getAnova().getRegression().setDf(math.anova.regression.df(values));
    excelRegression.getAnova().getRegression().setSs(math.anova.regression.ss(values));
    excelRegression.getAnova().getRegression().setMs(math.anova.regression.ms(values));
    excelRegression.getAnova().getRegression().setF(math.anova.regression.f(values));
    excelRegression.getAnova().getResidual().setDf(math.anova.residual.df(values));
    excelRegression.getAnova().getResidual().setSs(math.anova.residual.ss(values));
    excelRegression.getAnova().getResidual().setMs(math.anova.residual.ms(values));
    excelRegression.getAnova().getTotal().setDf(math.anova.total.df(values));
    excelRegression.getAnova().getTotal().setSs(math.anova.total.ss(values));

    excelRegression.getSummary().setRSquare(math.summary.rSquare(values));
    excelRegression.getSummary().setMultipleR(math.summary.multipleR(values));
    excelRegression.getSummary().setAdjustedRSquare(math.summary.adjustedRSquare(values));
    excelRegression.getSummary().setStandardError(math.summary.standardError(values));
    excelRegression.getSummary().setObservations(math.summary.observations(values));

    return excelRegression;
};
<commit_msg>Change indent from 4 to 2<commit_after>/*
 * excel-regression
 * Copyright(c) Leonardo Fachetti
 * MIT Licensed
 */

var validation = require('./utils/validation');
var math = require('./utils/math');
var Regression = require('./bean/regression');

var exports = module.exports = {};

exports.calculate = function (values) {
  validation.validate(values);
  var excelRegression = new Regression();

  var regression = math.linearRegression(values);

  excelRegression.getResidual().setObservation(math.residual.observation(values));
  excelRegression.getResidual().setPredictedY(math.residual.predictedY(values));
  excelRegression.getResidual().setResiduals(math.residual.residuals(values));

  excelRegression.getAnova().getIntercept().setCoefficient(math.anova.intercept.coefficient(values));
  excelRegression.getAnova().getVarX1().setCoefficient(math.anova.varX1.coefficient(values));
  excelRegression.getAnova().getRegression().setDf(math.anova.regression.df(values));
  excelRegression.getAnova().getRegression().setSs(math.anova.regression.ss(values));
  excelRegression.getAnova().getRegression().setMs(math.anova.regression.ms(values));
  excelRegression.getAnova().getRegression().setF(math.anova.regression.f(values));
  excelRegression.getAnova().getResidual().setDf(math.anova.residual.df(values));
  excelRegression.getAnova().getResidual().setSs(math.anova.residual.ss(values));
  excelRegression.getAnova().getResidual().setMs(math.anova.residual.ms(values));
  excelRegression.getAnova().getTotal().setDf(math.anova.total.df(values));
  excelRegression.getAnova().getTotal().setSs(math.anova.total.ss(values));

  excelRegression.getSummary().setRSquare(math.summary.rSquare(values));
  excelRegression.getSummary().setMultipleR(math.summary.multipleR(values));
  excelRegression.getSummary().setAdjustedRSquare(math.summary.adjustedRSquare(values));
  excelRegression.getSummary().setStandardError(math.summary.standardError(values));
  excelRegression.getSummary().setObservations(math.summary.observations(values));

  return excelRegression;
};
<|endoftext|>


<commit_before>exports.hello = 'world';
<commit_msg>Respond with HTML.<commit_after>// 127.0.0.1:8080/oauth2/authorize?response_type=code&redirect_uri=http%3A%2F%2Flocalhost%3A3000%2Freturn&client_id=1&response_mode=web_message

var html =
'<!DOCTYPE html>' +
'' +
'' +
  '<title>Authorization Response</title>' +
'' +
'' +
  '' +
'' +
'';

exports = module.exports = function (txn, res, params) {
  console.log('TODO: RESPOND USING WMRM...');

  res.setHeader('Content-Type', 'text/html;charset=UTF-8');
  res.setHeader('Cache-Control', 'no-cache, no-store');
  res.setHeader('Pragma', 'no-cache');

  return res.end(html);
}
<|endoftext|>


<commit_before>"use strict"

const converters = require("./converters")
    , indento = require("indento")

/**
 * json2md
 * Converts a JSON input to markdown.
 *
 * **Supported elements**
 *
 * | Type         | Element            | Data                                                                                | Example                                                                                |
 * |--------------|--------------------|--------------------------------------------------------------------------------------------------------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------|
 * | `h1`         | Heading 1          | The heading text as string.                                                                                | `{ h1: "heading 1" }`                                                                                |
 * | `h2`         | Heading 2          | The heading text as string.                                                                                | `{ h2: "heading 2" }`                                                                                |
 * | `h3`         | Heading 3          | The heading text as string.                                                                                | `{ h3: "heading 3" }`                                                                                |
 * | `h4`         | Heading 4          | The heading text as string.                                                                                | `{ h4: "heading 4" }`                                                                                |
 * | `h5`         | Heading 5          | The heading text as string.                                                                                | `{ h5: "heading 5" }`                                                                                |
 * | `h6`         | Heading 6          | The heading text as string.                                                                                | `{ h6: "heading 6" }`                                                                                |
 * | `p`          | Paragraphs         | The paragraph text as string or array (multiple paragraphs).                                                             | `{ p: "Hello World"}` or multiple paragraphs: `{ p: ["Hello", "World"] }`                                                                        |
 * | `blockquote` | Blockquote         | The blockquote as string or array (multiple blockquotes)                                                                 | `{ blockquote: "Hello World"}` or multiple blockquotes: `{ blockquote: ["Hello", "World"] }`                                                     |
 * | `img`        | Image              | An object or an array of objects containing the `title` and `source` fields.                                             | `{ img: { title: "My image title", source: "http://example.com/image.png" } }`                                                                   |
 * | `ul`         | Unordered list     | An array of strings representing the items.                                                                              | `{ ul: ["item 1", "item 2"] }`                                                                                |
 * | `ol`         | Ordered list       | An array of strings representing the items.                                                                              | `{ ol: ["item 1", "item 2"] }`                                                                                |
 * | `code`       | Code block element | An object containing the `language` (`String`) and `content` (`Array` or `String`)  fields.                              | `{ code: { "language": "html", "content": "<script src='dummy.js'></script>" } }`                                                                |
 * | `table`      | Table              | An object containing the `headers` (`Array` of `String`s) and `rows` (`Array` of `Array`s or `Object`s).                 | `{ table: { headers: ["a", "b"], rows: [{ a: "col1", b: "col2" }] } }` or `{ table: { headers: ["a", "b"], rows: [["col1", "col2"]] } }`         |
 *
 *
 * You can extend the `json2md.converters` object to support your custom types.
 *
 * ```js
 * json2md.converters.sayHello = function (input, json2md) {
 *    return "Hello " + input + "!"
 * }
 * ```
 *
 * Then you can use it:
 *
 * ```js
 * json2md({ sayHello: "World" })
 * // => "Hello World!"
 * ```
 *
 * @name json2md
 * @function
 * @param {Array|Object|String} data The input JSON data.
 * @param {String} prefix A snippet to add before each line.
 * @return {String} The generated markdown result.
 */
function json2md(data, prefix, _type) {
    prefix = prefix || ""
    if (typeof data === "string" || typeof data === "number") {
        return indento(data, 1, prefix)
    }

    let content = []

    // Handle arrays
    if (Array.isArray(data)) {
        for (let i = 0; i < data.length; ++i) {
            content.push(indento(json2md(data[i], "", _type), 1, prefix))
        }
        return content.join("\n")
    } else {
        let type = Object.keys(data)[0]
          , func = converters[_type || type]

        if (typeof func === "function") {
            return indento(func(_type ? data : data[type], json2md), 1, prefix) + "\n"
        }
        throw new Error("There is no such converter: " + type)
    }
}

json2md.converters = converters

module.exports = json2md
<commit_msg>feat: add json2md.async method for async converters<commit_after>"use strict"

const converters = require("./converters")
    , indento = require("indento")

/**
 * json2md
 * Converts a JSON input to markdown.
 *
 * **Supported elements**
 *
 * | Type         | Element            | Data                                                                                | Example                                                                                |
 * |--------------|--------------------|--------------------------------------------------------------------------------------------------------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------|
 * | `h1`         | Heading 1          | The heading text as string.                                                                                | `{ h1: "heading 1" }`                                                                                |
 * | `h2`         | Heading 2          | The heading text as string.                                                                                | `{ h2: "heading 2" }`                                                                                |
 * | `h3`         | Heading 3          | The heading text as string.                                                                                | `{ h3: "heading 3" }`                                                                                |
 * | `h4`         | Heading 4          | The heading text as string.                                                                                | `{ h4: "heading 4" }`                                                                                |
 * | `h5`         | Heading 5          | The heading text as string.                                                                                | `{ h5: "heading 5" }`                                                                                |
 * | `h6`         | Heading 6          | The heading text as string.                                                                                | `{ h6: "heading 6" }`                                                                                |
 * | `p`          | Paragraphs         | The paragraph text as string or array (multiple paragraphs).                                                             | `{ p: "Hello World"}` or multiple paragraphs: `{ p: ["Hello", "World"] }`                                                                        |
 * | `blockquote` | Blockquote         | The blockquote as string or array (multiple blockquotes)                                                                 | `{ blockquote: "Hello World"}` or multiple blockquotes: `{ blockquote: ["Hello", "World"] }`                                                     |
 * | `img`        | Image              | An object or an array of objects containing the `title` and `source` fields.                                             | `{ img: { title: "My image title", source: "http://example.com/image.png" } }`                                                                   |
 * | `ul`         | Unordered list     | An array of strings representing the items.                                                                              | `{ ul: ["item 1", "item 2"] }`                                                                                |
 * | `ol`         | Ordered list       | An array of strings representing the items.                                                                              | `{ ol: ["item 1", "item 2"] }`                                                                                |
 * | `code`       | Code block element | An object containing the `language` (`String`) and `content` (`Array` or `String`)  fields.                              | `{ code: { "language": "html", "content": "<script src='dummy.js'></script>" } }`                                                                |
 * | `table`      | Table              | An object containing the `headers` (`Array` of `String`s) and `rows` (`Array` of `Array`s or `Object`s).                 | `{ table: { headers: ["a", "b"], rows: [{ a: "col1", b: "col2" }] } }` or `{ table: { headers: ["a", "b"], rows: [["col1", "col2"]] } }`         |
 *
 *
 * You can extend the `json2md.converters` object to support your custom types.
 *
 * ```js
 * json2md.converters.sayHello = function (input, json2md) {
 *    return "Hello " + input + "!"
 * }
 * ```
 *
 * Then you can use it:
 *
 * ```js
 * json2md({ sayHello: "World" })
 * // => "Hello World!"
 * ```
 *
 * @name json2md
 * @function
 * @param {Array|Object|String} data The input JSON data.
 * @param {String} prefix A snippet to add before each line.
 * @return {String} The generated markdown result.
 */
function json2md(data, prefix, _type) {
    prefix = prefix || ""
    if (typeof data === "string" || typeof data === "number") {
        return indento(data, 1, prefix)
    }

    let content = []

    // Handle arrays
    if (Array.isArray(data)) {
        for (let i = 0; i < data.length; ++i) {
            content.push(indento(json2md(data[i], "", _type), 1, prefix))
        }
        return content.join("\n")
    } else {
        let type = Object.keys(data)[0]
          , func = converters[_type || type]

        if (typeof func === "function") {
            return indento(func(_type ? data : data[type], json2md), 1, prefix) + "\n"
        }
        throw new Error("There is no such converter: " + type)
    }
}

/**
 * @param {Array|Object|String} data The input JSON data.
 * @param {String} prefix A snippet to add before each line.
 * @return {Promise.<String, Error>} The generated markdown result.
 */
json2md.async = (data, prefix, _type) => Promise.resolve().then(() => {
    prefix = prefix || ""
    if (typeof data === "string" || typeof data === "number") {
        return indento(data, 1, prefix)
    }

    let content = []

    // Handle arrays
    if (Array.isArray(data)) {
        const promises = data.map((d, index) => Promise.resolve()
            .then(() => json2md.async(d, "", _type))
            .then((result) => indento(result, 1, prefix))
            .then((result) => {
                content[index] = result;
            })
        )
        return Promise.all(promises)
            .then(() => content.join("\n"))
    } else {
        let type = Object.keys(data)[0]
          , func = converters[_type || type]

        if (typeof func === "function") {
            return Promise.resolve()
                .then(() => func(_type ? data : data[type], json2md))
                .then((result) => indento(result, 1, prefix) + "\n")
        }
        throw new Error("There is no such converter: " + type)
    }
})

json2md.converters = converters

module.exports = json2md
<|endoftext|>


<commit_before>/**
 * Poetry library
 * Facade to the lib exports
 * @name Poetry
 * @exports
 */

module.exports = new Proxy( {

    //// Enpoint registration ////
    route: require( './methods/endpoint' ),
    endpoint: require( './methods/endpoint' ),

    //// Waterline ORM ////
    save: require( './methods/save' ),
    // find: require( './methods/find' ),
    // findOne: require( './methods/findOne' ),
    // update: require( './methods/find' ),
    // delete: require( './methods/delete' ),

    //// Event-based communication ////
    // emit: require( './methods/emit' ),
    // on: require( './methods/on' )

}, {

    get( target, property ) {

        if ( target[ property ] )
            return target[ property ];

        // Compatibility with Babel __esModule, etc
        if ( property.slice( 0, 2 ) == '__' )
            return undefined;

        //TODO: Handle onXXX generic methods
        throw new Error( `Poetry does not export "${property}".` );
    },

    // Avoid lib replacement
    set() {}

} );
<commit_msg>Add logging system<commit_after>/**
 * Poetry library
 * Facade to the lib exports
 * @name Poetry
 * @exports
 */

module.exports = new Proxy( {

    //// Enpoint registration ////
    route: require( './methods/endpoint' ),
    endpoint: require( './methods/endpoint' ),

    //// Waterline ORM ////
    save: require( './methods/save' ),
    // find: require( './methods/find' ),
    // findOne: require( './methods/findOne' ),
    // update: require( './methods/find' ),
    // delete: require( './methods/delete' ),

    //// Event-based communication ////
    // emit: require( './methods/emit' ),
    // on: require( './methods/on' )

    //// Logging ////
    log: require('./methods/log');

}, {

    get( target, property ) {

        if ( target[ property ] )
            return target[ property ];

        // Compatibility with Babel __esModule, etc
        if ( property.slice( 0, 2 ) == '__' )
            return undefined;

        //TODO: Handle onXXX generic methods
        throw new Error( `Poetry does not export "${property}".` );
    },

    // Avoid lib replacement
    set() {}

} );
<|endoftext|>


<commit_before>'use strict';

require( './config' );  // this will load the configuration from vandium.json

require( './prevent' ); // prevent calls to unwanted functions

const validation = require( './validation' );

const protect = require( './protect' );

const jwt = require( './jwt' );

const utils = require( './utils' );

const STAGE_JWT = 10;

const STAGE_INPUT = 20;

const STAGE_EXEC = 30;

var postHandler = function( done ) { done(); };

var logUncaughtExceptions = true;

function validateJWT( event ) {

	jwt.validate( event );
}

function validateInput( event ) {

	validation.verify( event );

	protect.scan( event );
}

function isPromise( value ) {

    return ( value && utils.isFunction( value.then ) && utils.isFunction( value.catch ) );
}

function logPostHandlerError( err ) {

    if( err ) {

        console.log( '*** vandium - error running afterHandler function', err );
    }
}

function wrapCallback( callback ) {

    return function( error, result ) {

        try {

            let retValue = postHandler( function( err ) {

                logPostHandlerError( err );

                return callback( error, result );
            });

            if( isPromise( retValue ) ) {

                retValue
                    .catch( logPostHandlerError )
                    .then( function() {

                        callback( error, result );
                    });
            }
            else if( postHandler.length === 0 ) {

                // synchronous
                callback( error, result );
            }
        }
        catch( err ) {

            logPostHandlerError( err );

            callback( error, result );
        }
    }
}

function wrapHandler( userFunc ) {

	return function( event, context, callback ) {

        let stage = 0;

		try {

            stage = STAGE_JWT;
			validateJWT( event );

            stage = STAGE_INPUT;
			validateInput( event );

            stage = STAGE_EXEC;

            callback = wrapCallback( callback );

			let retValue = userFunc( event, context, callback );

            if( isPromise( retValue ) ) {

				retValue
					.then( function( value ) {

                        callback( null, value );
					})
					.catch( function( err ) {

                        callback( err );
					});
			}
			else {

                return retValue;
			}
		}
		catch( err ) {

            if( logUncaughtExceptions && (stage === STAGE_EXEC) ) {

                console.log( '*** vandium - uncaught exception:', err );
            }

            callback( err );
		}
	};
}

function Vandium( userFunc ) {

	return wrapHandler( userFunc )
}

Vandium.after = function( afterHandlerFunction ) {

    if( utils.isFunction( afterHandlerFunction ) ) {

        postHandler = afterHandlerFunction;
    }
}

Vandium.validation = function( schema ) {

	if( schema ) {

		validation.configure( schema );
	}

	return validation;
}

// allow jwt to be used as a member variable or method
Vandium.jwt = function() {

    return jwt;
}

Vandium.jwt.configure = jwt.configure;

Vandium.jwt.enable = jwt.enable;

Vandium.protect = protect;

Vandium.logUncaughtExceptions = function( enable ) {

    logUncaughtExceptions = (enable === true);
}

Object.defineProperty( Vandium, 'types', {

	get: function() {

		return validation.types();
	}
});

Object.defineProperty( Vandium, 'validator', {

    get: function() {

        return validation.validator;
    }
});

module.exports = Vandium;
<commit_msg>Changed internals to use Promises for wrapping the callback function<commit_after>'use strict';

require( './config' );  // this will load the configuration from vandium.json

require( './prevent' ); // prevent calls to unwanted functions

const validation = require( './validation' );

const protect = require( './protect' );

const jwt = require( './jwt' );

const utils = require( './utils' );

const STAGE_JWT = 10;

const STAGE_INPUT = 20;

const STAGE_EXEC = 30;

var postHandler = function( done ) { done(); };

var logUncaughtExceptions = true;

function validateJWT( event ) {

	jwt.validate( event );
}

function validateInput( event ) {

	validation.verify( event );

	protect.scan( event );
}

function isPromise( value ) {

    return ( value && utils.isFunction( value.then ) && utils.isFunction( value.catch ) );
}

/**
 * @Promise
 */
function executePostHandler() {

    // call post handler
    return new Promise( function( resolve, reject ) {

        try {

            if( postHandler.length === 1 ) {

                // need to tell handler when finished
                postHandler( function( err ) {

                    if( err ) {

                        return reject( err );
                    }

                    resolve();
                });
            }
            else {

                resolve( postHandler() );
            }
        }
        catch( err ) {

            reject( err );
        }
    });
}

function wrapCallback( callback ) {

    return function( error, result ) {

        executePostHandler()
            .catch( function( err ) {

                console.log( '*** vandium - error running afterHandler function', err );
            })
            .then( function() {

                callback( error, result );
            });
    }
}

function wrapHandler( userFunc ) {

	return function( event, context, callback ) {

        let stage = 0;

		try {

            stage = STAGE_JWT;
			validateJWT( event );

            stage = STAGE_INPUT;
			validateInput( event );

            stage = STAGE_EXEC;

            callback = wrapCallback( callback );

			let retValue = userFunc( event, context, callback );

            if( isPromise( retValue ) ) {

				retValue
					.then( function( value ) {

                        callback( null, value );
					})
					.catch( function( err ) {

                        callback( err );
					});
			}
			else {

                return retValue;
			}
		}
		catch( err ) {

            if( logUncaughtExceptions && (stage === STAGE_EXEC) ) {

                console.log( '*** vandium - uncaught exception:', err );
            }

            callback( err );
		}
	};
}

function Vandium( userFunc ) {

	return wrapHandler( userFunc )
}

Vandium.after = function( afterHandlerFunction ) {

    if( utils.isFunction( afterHandlerFunction ) ) {

        postHandler = afterHandlerFunction;
    }
}

Vandium.validation = function( schema ) {

	if( schema ) {

		validation.configure( schema );
	}

	return validation;
}

// allow jwt to be used as a member variable or method
Vandium.jwt = function() {

    return jwt;
}

Vandium.jwt.configure = jwt.configure;

Vandium.jwt.enable = jwt.enable;

Vandium.protect = protect;

Vandium.logUncaughtExceptions = function( enable ) {

    logUncaughtExceptions = (enable === true);
}

Object.defineProperty( Vandium, 'types', {

	get: function() {

		return validation.types();
	}
});

Object.defineProperty( Vandium, 'validator', {

    get: function() {

        return validation.validator;
    }
});

module.exports = Vandium;
<|endoftext|>


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

var store = {};

var lookupPackageData = function(attrs) {
  try {
    var parentRootDir = path.join(__dirname, '../../..');
    var bldr = require(path.join(parentRootDir, 'package')).bldr;
    if (bldr && bldr.appDir) attrs.appDir = path.resolve(parentRootDir, bldr.appDir);
    if (bldr && bldr.global) attrs.appGlobal = bldr.global;
  } catch (e) {
  }
};

var fetchData = function(key) {
  var attrs = store[key];
  if (!attrs) {
    attrs = store[key] = {
      key: key,
      appDir: null,   // Root of the application source tree
      appGlobal: key, // Global variable as string for defining the app.
      appList: [],    // List of files that make up the app
      buildList: {},  // List of files used to build up the app
      exported: {},
      usedDefine: false,
    };
    lookupPackageData(attrs);
  }
  return attrs;
};

var bldr = function(key, filename, options) {
  var data = fetchData(key);

  // Dir we are requiring things from.
  var baseDir = path.dirname(filename);

  options = options || {};
  if (options.appDir) data.appDir = path.resolve(baseDir, options.appDir);
  if (!data.appDir) data.appDir = baseDir;

  data.buildList[filename] = true;

  // Takes module and a fullpath (without extension), and adds it to the app root.
  // extendApp(mod, '/src/app/models/User')
  // eg: app.models.User = mod;
  var extendApp = function(mod, fullPath) {
    var relativeToAppDir = path.relative(data.appDir, fullPath);
    var segments = relativeToAppDir.split('/');
    if (options.global || data.appGlobal) segments = [options.global || data.appGlobal].concat(segments);

    var root = global;
    segments.slice(0, segments.length - 1).forEach(function(seg) {
      root[seg] = root[seg] || {};
      root = root[seg];
    });
    var last = segments[segments.length - 1];
    root[path.basename(last, path.extname(last))] = mod;

    return segments
  };

  var requireAndAdd = function(requirePath, opts) {
    var fullPath = path.join(baseDir, requirePath);
    var mod = require(fullPath);
    var segments = opts.define && extendApp(mod, fullPath);
    addToApp(fullPath, segments, opts.ext);
    return mod;
  };

  var addToApp = function(f, segments, ext) {
    ext = ext || '.js';
    var filePath = f.slice(f.length - ext.length) === ext ? f : f+ext;
    var exists = false;
    for (var i=0; i<data.appList.length; i++) {
      if (data.appList[i][0] === filePath) exists = true;
    }
    if (!exists) data.appList.push([filePath, segments]);
  };

  // Split for dir, list dir, filter on glob, return list of matched files.
  var glob = function(requirePath) {
    var dir = path.dirname(requirePath);
    var filter = minimatch.filter(path.basename(requirePath), {matchBase: true});
    return fs.readdirSync(path.join(baseDir, dir)).filter(filter).map(function(p) {
      return path.join(dir, p);
    });
  };

  // Public api.
  var api = {
    // Requires the file on both node and the browser,
    // and extends the global module tree with the result.
    define: function(requirePath, opts) {
      opts = opts || {};
      opts.define = true;
      data.usedDefine = true;
      return this.require(requirePath, opts);
    },

    require: function(requirePath, opts) {
      opts = opts || {};
      if (typeof opts.define === 'undefined') opts.define = false;
      var paths = [requirePath];
      if (requirePath.indexOf('*') === -1) {
        return requireAndAdd(requirePath, opts);
      } else {
        var files = glob(requirePath);
        return files.map(function(p) {
          return requireAndAdd(p, opts);
        });
      };
    },

    browser: function(requirePath, opts) {
      opts = opts || {};
      requirePath = requirePath[0] === '/' ? requirePath : path.join(baseDir, requirePath);
      addToApp(requirePath, null, opts.ext);
    }
  };

  return api;
};

bldr.store = store;
module.exports = bldr;

<commit_msg>Better variable name s/exists/alreadyAdded/<commit_after>var fs = require('fs');
var path = require('path');
var minimatch = require('minimatch');

var store = {};

var lookupPackageData = function(attrs) {
  try {
    var parentRootDir = path.join(__dirname, '../../..');
    var bldr = require(path.join(parentRootDir, 'package')).bldr;
    if (bldr && bldr.appDir) attrs.appDir = path.resolve(parentRootDir, bldr.appDir);
    if (bldr && bldr.global) attrs.appGlobal = bldr.global;
  } catch (e) {
  }
};

var fetchData = function(key) {
  var attrs = store[key];
  if (!attrs) {
    attrs = store[key] = {
      key: key,
      appDir: null,   // Root of the application source tree
      appGlobal: key, // Global variable as string for defining the app.
      appList: [],    // List of files that make up the app
      buildList: {},  // List of files used to build up the app
      exported: {},
      usedDefine: false,
    };
    lookupPackageData(attrs);
  }
  return attrs;
};

var bldr = function(key, filename, options) {
  var data = fetchData(key);

  // Dir we are requiring things from.
  var baseDir = path.dirname(filename);

  options = options || {};
  if (options.appDir) data.appDir = path.resolve(baseDir, options.appDir);
  if (!data.appDir) data.appDir = baseDir;

  data.buildList[filename] = true;

  // Takes module and a fullpath (without extension), and adds it to the app root.
  // extendApp(mod, '/src/app/models/User')
  // eg: app.models.User = mod;
  var extendApp = function(mod, fullPath) {
    var relativeToAppDir = path.relative(data.appDir, fullPath);
    var segments = relativeToAppDir.split('/');
    if (options.global || data.appGlobal) segments = [options.global || data.appGlobal].concat(segments);

    var root = global;
    segments.slice(0, segments.length - 1).forEach(function(seg) {
      root[seg] = root[seg] || {};
      root = root[seg];
    });
    var last = segments[segments.length - 1];
    root[path.basename(last, path.extname(last))] = mod;

    return segments
  };

  var requireAndAdd = function(requirePath, opts) {
    var fullPath = path.join(baseDir, requirePath);
    var mod = require(fullPath);
    var segments = opts.define && extendApp(mod, fullPath);
    addToApp(fullPath, segments, opts.ext);
    return mod;
  };

  var addToApp = function(f, segments, ext) {
    ext = ext || '.js';
    var filePath = f.slice(f.length - ext.length) === ext ? f : f+ext;
    var alreadyAdded = false;
    for (var i=0; i<data.appList.length; i++) {
      if (data.appList[i][0] === filePath) alreadyAdded = true;
    }
    if (!alreadyAdded) data.appList.push([filePath, segments]);
  };

  // Split for dir, list dir, filter on glob, return list of matched files.
  var glob = function(requirePath) {
    var dir = path.dirname(requirePath);
    var filter = minimatch.filter(path.basename(requirePath), {matchBase: true});
    return fs.readdirSync(path.join(baseDir, dir)).filter(filter).map(function(p) {
      return path.join(dir, p);
    });
  };

  // Public api.
  var api = {
    // Requires the file on both node and the browser,
    // and extends the global module tree with the result.
    define: function(requirePath, opts) {
      opts = opts || {};
      opts.define = true;
      data.usedDefine = true;
      return this.require(requirePath, opts);
    },

    require: function(requirePath, opts) {
      opts = opts || {};
      if (typeof opts.define === 'undefined') opts.define = false;
      var paths = [requirePath];
      if (requirePath.indexOf('*') === -1) {
        return requireAndAdd(requirePath, opts);
      } else {
        var files = glob(requirePath);
        return files.map(function(p) {
          return requireAndAdd(p, opts);
        });
      };
    },

    browser: function(requirePath, opts) {
      opts = opts || {};
      requirePath = requirePath[0] === '/' ? requirePath : path.join(baseDir, requirePath);
      addToApp(requirePath, null, opts.ext);
    }
  };

  return api;
};

bldr.store = store;
module.exports = bldr;

<|endoftext|>


<commit_before>if ( typeof(window) === 'undefined' ) {
  module.exports = require('./node');
} else {
  module.exports = require('./browser');
}
<commit_msg>Remove index<commit_after><|endoftext|>