<commit_before>
/**
 * Object#toString() ref for stringify().
 */

var toString = Object.prototype.toString;

/**
 * Array#indexOf shim.
 */

var indexOf = typeof Array.prototype.indexOf === 'function'
  ? function(arr, el) { return arr.indexOf(el); }
  : function(arr, el) {
      for (var i = 0; i < arr.length; i++) {
        if (arr[i] === el) return i;
      }
      return -1;
    };

/**
 * Array.isArray shim.
 */

var isArray = Array.isArray || function(arr) {
  return toString.call(arr) == '[object Array]';
};

/**
 * Object.keys shim.
 */

var objectKeys = Object.keys || function(obj) {
  var ret = [];
  for (var key in obj) ret.push(key);
  return ret;
};

/**
 * Array#forEach shim.
 */

var forEach = typeof Array.prototype.forEach === 'function'
  ? function(arr, fn) { return arr.forEach(fn); }
  : function(arr, fn) {
      for (var i = 0; i < arr.length; i++) fn(arr[i]);
    };

/**
 * Array#reduce shim.
 */

var reduce = function(arr, fn, initial) {
  if (typeof arr.reduce === 'function') return arr.reduce(fn, initial);
  var res = initial;
  for (var i = 0; i < arr.length; i++) res = fn(res, arr[i]);
  return res;
};

/**
 * Create a nullary object if possible
 */

function createObject() {
  return Object.create
    ? Object.create(null)
    : {};
}

/**
 * Cache non-integer test regexp.
 */

var isint = /^[0-9]+$/;

function promote(parent, key) {
  if (parent[key].length == 0) return parent[key] = createObject();
  var t = createObject();
  for (var i in parent[key]) t[i] = parent[key][i];
  parent[key] = t;
  return t;
}

function parse(parts, parent, key, val) {
  var part = parts.shift();
  // end
  if (!part) {
    if (isArray(parent[key])) {
      parent[key].push(val);
    } else if ('object' == typeof parent[key]) {
      parent[key] = val;
    } else if ('undefined' == typeof parent[key]) {
      parent[key] = val;
    } else {
      parent[key] = [parent[key], val];
    }
    // array
  } else {
    var obj = parent[key] = parent[key] || [];
    if (']' == part) {
      if (isArray(obj)) {
        if ('' != val) obj.push(val);
      } else if ('object' == typeof obj) {
        obj[objectKeys(obj).length] = val;
      } else {
        obj = parent[key] = [parent[key], val];
      }
      // prop
    } else if (~indexOf(part, ']')) {
      part = part.substr(0, part.length - 1);
      if (!isint.test(part) && isArray(obj)) obj = promote(parent, key);
      parse(parts, obj, part, val);
      // key
    } else {
      if (!isint.test(part) && isArray(obj)) obj = promote(parent, key);
      parse(parts, obj, part, val);
    }
  }
}

/**
 * Merge parent key/val pair.
 */

function merge(parent, key, val){
  if (~indexOf(key, ']')) {
    var parts = key.split('[')
      , len = parts.length
      , last = len - 1;
    parse(parts, parent, 'base', val);
    // optimize
  } else {
    if (!isint.test(key) && isArray(parent.base)) {
      var t = createObject();
      for (var k in parent.base) t[k] = parent.base[k];
      parent.base = t;
    }
    set(parent.base, key, val);
  }

  return parent;
}

/**
 * Compact sparse arrays.
 */

function compact(obj) {
  if ('object' != typeof obj) return obj;

  if (isArray(obj)) {
    var ret = [];
    for (var i in obj) ret.push(obj[i]);
    return ret;
  }

  for (var key in obj) {
    obj[key] = compact(obj[key]);
  }

  return obj;
}

/**
 * Restore Object.prototype.
 * see pull-request #58
 */

function restoreProto(obj) {
  if (!Object.create) return obj;
  if (isArray(obj)) return obj;
  if (obj && 'object' != typeof obj) return obj;

  for (var key in obj) {
    obj[key] = restoreProto(obj[key]);
  }

  obj.__proto__ = Object.prototype;
  return obj;
}

/**
 * Parse the given obj.
 */

function parseObject(obj){
  var ret = { base: {} };

  forEach(objectKeys(obj), function(name){
    merge(ret, name, obj[name]);
  });

  return compact(ret.base);
}

/**
 * Parse the given str.
 */

function parseString(str){
  var ret = reduce(String(str).split('&'), function(ret, pair){
    var eql = indexOf(pair, '=')
      , brace = lastBraceInKey(pair)
      , key = pair.substr(0, brace || eql)
      , val = pair.substr(brace || eql, pair.length)
      , val = val.substr(indexOf(val, '=') + 1, val.length);

    // ?foo
    if ('' == key) key = pair, val = '';
    if ('' == key) return ret;

    return merge(ret, decode(key), decode(val));
  }, { base: createObject() }).base;

  return restoreProto(compact(ret));
}

/**
 * Parse the given query `str` or `obj`, returning an object.
 *
 * @param {String} str | {Object} obj
 * @return {Object}
 * @api public
 */

exports.parse = function(str){
  if (null == str || '' == str) return {};
  return 'object' == typeof str
    ? parseObject(str)
    : parseString(str);
};

/**
 * Turn the given `obj` into a query string
 *
 * @param {Object} obj
 * @return {String}
 * @api public
 */

var stringify = exports.stringify = function(obj, prefix) {
  if (isArray(obj)) {
    return stringifyArray(obj, prefix);
  } else if ('[object Object]' == toString.call(obj)) {
    return stringifyObject(obj, prefix);
  } else if ('string' == typeof obj) {
    return stringifyString(obj, prefix);
  } else {
    return prefix + '=' + encodeURIComponent(String(obj));
  }
};

/**
 * Stringify the given `str`.
 *
 * @param {String} str
 * @param {String} prefix
 * @return {String}
 * @api private
 */

function stringifyString(str, prefix) {
  if (!prefix) throw new TypeError('stringify expects an object');
  return prefix + '=' + encodeURIComponent(str);
}

/**
 * Stringify the given `arr`.
 *
 * @param {Array} arr
 * @param {String} prefix
 * @return {String}
 * @api private
 */

function stringifyArray(arr, prefix) {
  var ret = [];
  if (!prefix) throw new TypeError('stringify expects an object');
  for (var i = 0; i < arr.length; i++) {
    ret.push(stringify(arr[i], prefix + '[' + i + ']'));
  }
  return ret.join('&');
}

/**
 * Stringify the given `obj`.
 *
 * @param {Object} obj
 * @param {String} prefix
 * @return {String}
 * @api private
 */

function stringifyObject(obj, prefix) {
  var ret = []
    , keys = objectKeys(obj)
    , key;

  for (var i = 0, len = keys.length; i < len; ++i) {
    key = keys[i];
    if ('' == key) continue;
    if (null == obj[key]) {
      ret.push(encodeURIComponent(key) + '=');
    } else {
      ret.push(stringify(obj[key], prefix
        ? prefix + '[' + encodeURIComponent(key) + ']'
        : encodeURIComponent(key)));
    }
  }

  return ret.join('&');
}

/**
 * Set `obj`'s `key` to `val` respecting
 * the weird and wonderful syntax of a qs,
 * where "foo=bar&foo=baz" becomes an array.
 *
 * @param {Object} obj
 * @param {String} key
 * @param {String} val
 * @api private
 */

function set(obj, key, val) {
  var v = obj[key];
  if (undefined === v) {
    obj[key] = val;
  } else if (isArray(v)) {
    v.push(val);
  } else {
    obj[key] = [v, val];
  }
}

/**
 * Locate last brace in `str` within the key.
 *
 * @param {String} str
 * @return {Number}
 * @api private
 */

function lastBraceInKey(str) {
  var len = str.length
    , brace
    , c;
  for (var i = 0; i < len; ++i) {
    c = str[i];
    if (']' == c) brace = false;
    if ('[' == c) brace = true;
    if ('=' == c && !brace) return i;
  }
}

/**
 * Decode `str`.
 *
 * @param {String} str
 * @return {String}
 * @api private
 */

function decode(str) {
  try {
    return decodeURIComponent(str.replace(/\+/g, ' '));
  } catch (err) {
    return str;
  }
}
<commit_msg>check hasOwnProperty before restoring proto<commit_after>/**
 * Object#toString() ref for stringify().
 */

var toString = Object.prototype.toString;

/**
 * Object#hasOwnProperty ref
 */

var hasOwnProperty = Object.prototype.hasOwnProperty;

/**
 * Array#indexOf shim.
 */

var indexOf = typeof Array.prototype.indexOf === 'function'
  ? function(arr, el) { return arr.indexOf(el); }
  : function(arr, el) {
      for (var i = 0; i < arr.length; i++) {
        if (arr[i] === el) return i;
      }
      return -1;
    };

/**
 * Array.isArray shim.
 */

var isArray = Array.isArray || function(arr) {
  return toString.call(arr) == '[object Array]';
};

/**
 * Object.keys shim.
 */

var objectKeys = Object.keys || function(obj) {
  var ret = [];
  for (var key in obj) ret.push(key);
  return ret;
};

/**
 * Array#forEach shim.
 */

var forEach = typeof Array.prototype.forEach === 'function'
  ? function(arr, fn) { return arr.forEach(fn); }
  : function(arr, fn) {
      for (var i = 0; i < arr.length; i++) fn(arr[i]);
    };

/**
 * Array#reduce shim.
 */

var reduce = function(arr, fn, initial) {
  if (typeof arr.reduce === 'function') return arr.reduce(fn, initial);
  var res = initial;
  for (var i = 0; i < arr.length; i++) res = fn(res, arr[i]);
  return res;
};

/**
 * Create a nullary object if possible
 */

function createObject() {
  return Object.create
    ? Object.create(null)
    : {};
}

/**
 * Cache non-integer test regexp.
 */

var isint = /^[0-9]+$/;

function promote(parent, key) {
  if (parent[key].length == 0) return parent[key] = createObject();
  var t = createObject();
  for (var i in parent[key]) t[i] = parent[key][i];
  parent[key] = t;
  return t;
}

function parse(parts, parent, key, val) {
  var part = parts.shift();
  // end
  if (!part) {
    if (isArray(parent[key])) {
      parent[key].push(val);
    } else if ('object' == typeof parent[key]) {
      parent[key] = val;
    } else if ('undefined' == typeof parent[key]) {
      parent[key] = val;
    } else {
      parent[key] = [parent[key], val];
    }
    // array
  } else {
    var obj = parent[key] = parent[key] || [];
    if (']' == part) {
      if (isArray(obj)) {
        if ('' != val) obj.push(val);
      } else if ('object' == typeof obj) {
        obj[objectKeys(obj).length] = val;
      } else {
        obj = parent[key] = [parent[key], val];
      }
      // prop
    } else if (~indexOf(part, ']')) {
      part = part.substr(0, part.length - 1);
      if (!isint.test(part) && isArray(obj)) obj = promote(parent, key);
      parse(parts, obj, part, val);
      // key
    } else {
      if (!isint.test(part) && isArray(obj)) obj = promote(parent, key);
      parse(parts, obj, part, val);
    }
  }
}

/**
 * Merge parent key/val pair.
 */

function merge(parent, key, val){
  if (~indexOf(key, ']')) {
    var parts = key.split('[')
      , len = parts.length
      , last = len - 1;
    parse(parts, parent, 'base', val);
    // optimize
  } else {
    if (!isint.test(key) && isArray(parent.base)) {
      var t = createObject();
      for (var k in parent.base) t[k] = parent.base[k];
      parent.base = t;
    }
    set(parent.base, key, val);
  }

  return parent;
}

/**
 * Compact sparse arrays.
 */

function compact(obj) {
  if ('object' != typeof obj) return obj;

  if (isArray(obj)) {
    var ret = [];
    for (var i in obj) ret.push(obj[i]);
    return ret;
  }

  for (var key in obj) {
    obj[key] = compact(obj[key]);
  }

  return obj;
}

/**
 * Restore Object.prototype.
 * see pull-request #58
 */

function restoreProto(obj) {
  if (!Object.create) return obj;
  if (isArray(obj)) return obj;
  if (obj && 'object' != typeof obj) return obj;

  for (var key in obj) {
    if (hasOwnProperty.call(obj, key)) {
      obj[key] = restoreProto(obj[key]);
    }
  }

  obj.__proto__ = Object.prototype;
  return obj;
}

/**
 * Parse the given obj.
 */

function parseObject(obj){
  var ret = { base: {} };

  forEach(objectKeys(obj), function(name){
    merge(ret, name, obj[name]);
  });

  return compact(ret.base);
}

/**
 * Parse the given str.
 */

function parseString(str){
  var ret = reduce(String(str).split('&'), function(ret, pair){
    var eql = indexOf(pair, '=')
      , brace = lastBraceInKey(pair)
      , key = pair.substr(0, brace || eql)
      , val = pair.substr(brace || eql, pair.length)
      , val = val.substr(indexOf(val, '=') + 1, val.length);

    // ?foo
    if ('' == key) key = pair, val = '';
    if ('' == key) return ret;

    return merge(ret, decode(key), decode(val));
  }, { base: createObject() }).base;

  return restoreProto(compact(ret));
}

/**
 * Parse the given query `str` or `obj`, returning an object.
 *
 * @param {String} str | {Object} obj
 * @return {Object}
 * @api public
 */

exports.parse = function(str){
  if (null == str || '' == str) return {};
  return 'object' == typeof str
    ? parseObject(str)
    : parseString(str);
};

/**
 * Turn the given `obj` into a query string
 *
 * @param {Object} obj
 * @return {String}
 * @api public
 */

var stringify = exports.stringify = function(obj, prefix) {
  if (isArray(obj)) {
    return stringifyArray(obj, prefix);
  } else if ('[object Object]' == toString.call(obj)) {
    return stringifyObject(obj, prefix);
  } else if ('string' == typeof obj) {
    return stringifyString(obj, prefix);
  } else {
    return prefix + '=' + encodeURIComponent(String(obj));
  }
};

/**
 * Stringify the given `str`.
 *
 * @param {String} str
 * @param {String} prefix
 * @return {String}
 * @api private
 */

function stringifyString(str, prefix) {
  if (!prefix) throw new TypeError('stringify expects an object');
  return prefix + '=' + encodeURIComponent(str);
}

/**
 * Stringify the given `arr`.
 *
 * @param {Array} arr
 * @param {String} prefix
 * @return {String}
 * @api private
 */

function stringifyArray(arr, prefix) {
  var ret = [];
  if (!prefix) throw new TypeError('stringify expects an object');
  for (var i = 0; i < arr.length; i++) {
    ret.push(stringify(arr[i], prefix + '[' + i + ']'));
  }
  return ret.join('&');
}

/**
 * Stringify the given `obj`.
 *
 * @param {Object} obj
 * @param {String} prefix
 * @return {String}
 * @api private
 */

function stringifyObject(obj, prefix) {
  var ret = []
    , keys = objectKeys(obj)
    , key;

  for (var i = 0, len = keys.length; i < len; ++i) {
    key = keys[i];
    if ('' == key) continue;
    if (null == obj[key]) {
      ret.push(encodeURIComponent(key) + '=');
    } else {
      ret.push(stringify(obj[key], prefix
        ? prefix + '[' + encodeURIComponent(key) + ']'
        : encodeURIComponent(key)));
    }
  }

  return ret.join('&');
}

/**
 * Set `obj`'s `key` to `val` respecting
 * the weird and wonderful syntax of a qs,
 * where "foo=bar&foo=baz" becomes an array.
 *
 * @param {Object} obj
 * @param {String} key
 * @param {String} val
 * @api private
 */

function set(obj, key, val) {
  var v = obj[key];
  if (undefined === v) {
    obj[key] = val;
  } else if (isArray(v)) {
    v.push(val);
  } else {
    obj[key] = [v, val];
  }
}

/**
 * Locate last brace in `str` within the key.
 *
 * @param {String} str
 * @return {Number}
 * @api private
 */

function lastBraceInKey(str) {
  var len = str.length
    , brace
    , c;
  for (var i = 0; i < len; ++i) {
    c = str[i];
    if (']' == c) brace = false;
    if ('[' == c) brace = true;
    if ('=' == c && !brace) return i;
  }
}

/**
 * Decode `str`.
 *
 * @param {String} str
 * @return {String}
 * @api private
 */

function decode(str) {
  try {
    return decodeURIComponent(str.replace(/\+/g, ' '));
  } catch (err) {
    return str;
  }
}
<|endoftext|>


<commit_before>/*!
 * base-questions <https://github.com/jonschlinkert/base-questions>
 *
 * Copyright (c) 2015, Jon Schlinkert.
 * Licensed under the MIT License.
 */

'use strict';

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

module.exports = function(config) {
  return function plugin(app) {
    if (!isValidInstance(app)) return;

    var opts = utils.merge({project: this.project}, this.options, config);
    opts.store = this.store;
    opts.globals = this.globals;
    opts.data = this.cache.data;
    var self = this;

    /**
     * Decorate the `questions` instance onto `app` and lazily
     * invoke the `question-store` lib when a questions related
     * method is called.
     */

    utils.sync(this, 'questions', function fn() {
      // return cached instance
      if (fn._questions) return fn._questions;

      var Questions = utils.Questions;
      var questions = new Questions(opts);
      fn._questions = questions;

      questions.on('ask', app.emit.bind(app, 'ask'));
      questions.on('answer', app.emit.bind(app, 'answer'));
      questions.on('error', function(err) {
        err.reason = 'base-questions error';
        self.emit('error', err);
        self.emit('*', 'error', err);
      });

      utils.sync(questions, 'data', function() {
        return self.cache.data;
      });

      utils.sync(questions, 'store', function() {
        return self.store;
      });

      utils.sync(questions, 'globals', function() {
        return self.globals;
      });

      return questions;
    });

    /**
     * Create a "choices" question from an array.
     *
     * ```js
     * app.choices('Favorite color?', ['blue', 'orange', 'green']);
     *
     * // or
     * app.choices('foo', {
     *   message: 'Favorite color?',
     *   choices: ['blue', 'orange', 'green']
     * });
     * ```
     * @name .choices
     * @param {String|Array} `queue` Name or array of question names.
     * @param {Object|Function} `options` Question options or callback function
     * @param {Function} `callback` callback function
     * @api public
     */

    this.define('choices', function() {
      this.questions.choices.apply(this.questions, arguments);
      return this;
    });

    /**
     * Add a question to be asked at a later point.
     *
     * ```js
     * app.question('beverage', 'What is your favorite beverage?');
     *
     * // or
     * app.question('beverage', {
     *   type: 'input',
     *   message: 'What is your favorite beverage?'
     * });
     *
     * // or
     * app.question({
     *   name: 'beverage'
     *   type: 'input',
     *   message: 'What is your favorite beverage?'
     * });
     * ```
     * @name .question
     * @param {Object|String} `value` Question object, message (string), or options object.
     * @param {String} `locale` Optionally pass the locale to use, otherwise the default locale is used.
     * @return {Object} Returns the `this.questions` object, for chaining
     * @api public
     */

    this.define('question', function() {
      return this.questions.set.apply(this.questions, arguments);
    });

    /**
     * Ask one or more questions, with the given `options` and callback.
     *
     * ```js
     * // ask all questions
     * app.ask(function(err, answers) {
     *   console.log(answers);
     * });
     *
     * // ask the specified questions
     * app.ask(['name', 'description'], function(err, answers) {
     *   console.log(answers);
     * });
     * ```
     * @name .ask
     * @param {String|Array} `queue` Name or array of question names.
     * @param {Object|Function} `options` Question options or callback function
     * @param {Function} `callback` callback function
     * @api public
     */

    this.define('ask', function(queue, opts, cb) {
      if (typeof queue === 'string' && !this.questions.has(queue)) {
        this.questions.set(queue, opts, queue);
      }
      this.questions.ask(queue, opts, cb);
    });

    return plugin;
  };
};

function isValidInstance(app) {
  var fn = app.options.validatePlugin;
  if (typeof fn === 'function' && !fn(app)) {
    return false;
  }
  if (app.isRegistered('base-questions')) {
    return false;
  }
  if (app.isCollection || app.isView) {
    return false;
  }
  return true;
}
<commit_msg>pass cwd on base-questions options<commit_after>/*!
 * base-questions <https://github.com/jonschlinkert/base-questions>
 *
 * Copyright (c) 2015, Jon Schlinkert.
 * Licensed under the MIT License.
 */

'use strict';

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

module.exports = function(config) {
  return function plugin(app) {
    if (!isValidInstance(app)) return;

    var opts = utils.merge({project: this.project}, this.options, config);
    opts.store = this.store;
    opts.globals = this.globals;
    opts.data = this.cache.data;
    opts.cwd = this.cwd;
    var self = this;

    /**
     * Decorate the `questions` instance onto `app` and lazily
     * invoke the `question-store` lib when a questions related
     * method is called.
     */

    utils.sync(this, 'questions', function fn() {
      // return cached instance
      if (fn._questions) return fn._questions;

      var Questions = utils.Questions;
      var questions = new Questions(opts);
      fn._questions = questions;

      questions.on('ask', app.emit.bind(app, 'ask'));
      questions.on('answer', app.emit.bind(app, 'answer'));
      questions.on('error', function(err) {
        err.reason = 'base-questions error';
        self.emit('error', err);
        self.emit('*', 'error', err);
      });

      utils.sync(questions, 'data', function() {
        return self.cache.data;
      });

      utils.sync(questions, 'store', function() {
        return self.store;
      });

      utils.sync(questions, 'globals', function() {
        return self.globals;
      });

      return questions;
    });

    /**
     * Create a "choices" question from an array.
     *
     * ```js
     * app.choices('Favorite color?', ['blue', 'orange', 'green']);
     *
     * // or
     * app.choices('foo', {
     *   message: 'Favorite color?',
     *   choices: ['blue', 'orange', 'green']
     * });
     * ```
     * @name .choices
     * @param {String|Array} `queue` Name or array of question names.
     * @param {Object|Function} `options` Question options or callback function
     * @param {Function} `callback` callback function
     * @api public
     */

    this.define('choices', function() {
      this.questions.choices.apply(this.questions, arguments);
      return this;
    });

    /**
     * Add a question to be asked at a later point.
     *
     * ```js
     * app.question('beverage', 'What is your favorite beverage?');
     *
     * // or
     * app.question('beverage', {
     *   type: 'input',
     *   message: 'What is your favorite beverage?'
     * });
     *
     * // or
     * app.question({
     *   name: 'beverage'
     *   type: 'input',
     *   message: 'What is your favorite beverage?'
     * });
     * ```
     * @name .question
     * @param {Object|String} `value` Question object, message (string), or options object.
     * @param {String} `locale` Optionally pass the locale to use, otherwise the default locale is used.
     * @return {Object} Returns the `this.questions` object, for chaining
     * @api public
     */

    this.define('question', function() {
      return this.questions.set.apply(this.questions, arguments);
    });

    /**
     * Ask one or more questions, with the given `options` and callback.
     *
     * ```js
     * // ask all questions
     * app.ask(function(err, answers) {
     *   console.log(answers);
     * });
     *
     * // ask the specified questions
     * app.ask(['name', 'description'], function(err, answers) {
     *   console.log(answers);
     * });
     * ```
     * @name .ask
     * @param {String|Array} `queue` Name or array of question names.
     * @param {Object|Function} `options` Question options or callback function
     * @param {Function} `callback` callback function
     * @api public
     */

    this.define('ask', function(queue, opts, cb) {
      if (typeof queue === 'string' && !this.questions.has(queue)) {
        this.questions.set(queue, opts, queue);
      }
      this.questions.ask(queue, opts, cb);
    });

    return plugin;
  };
};

function isValidInstance(app) {
  var fn = app.options.validatePlugin;
  if (typeof fn === 'function' && !fn(app)) {
    return false;
  }
  if (app.isRegistered('base-questions')) {
    return false;
  }
  if (app.isCollection || app.isView) {
    return false;
  }
  return true;
}
<|endoftext|>


<commit_before>var gutil = require('gulp-util');
var zip = require('gulp-zip');
var del = require('del');
var install = require('gulp-install');
var runSequence = require('run-sequence');
var AWS = require('aws-sdk');
var fs = require('fs');

module.exports = function(gulp, opts) {
  if (!gulp) {
    gulp = require('gulp');
    runSequence.use(gulp);
  }

  if(!opts){
    opts = {};
  }

  gulp.task('clean', function(cb) {
    del(['./dist', './dist.zip'], cb);
  });

  gulp.task('js', function() {
    return gulp.src('index.js')
      .pipe(gulp.dest('dist/'));
  });

  gulp.task('bin', function() {
    return gulp.src('./bin/*')
      .pipe(gulp.dest('dist/'));
  });

  gulp.task('node-mods', function() {
    return gulp.src('./package.json')
      .pipe(gulp.dest('dist/'))
      .pipe(install({production: true, ignoreScripts: opts.ignoreScripts}));
  });

  gulp.task('zip', function() {
    return gulp.src(['dist/**/*', '!dist/package.json'])
      .pipe(zip('dist.zip'))
      .pipe(gulp.dest('./'));
  });

  gulp.task('lambda-zip', function(callback) {
    return runSequence(
      ['clean'],
      ['js', 'bin', 'node-mods'],
      ['zip'],
      callback
    );
  });

  gulp.task('upload', function(callback) {
    try {
      var config = require(process.cwd() + "/lambda-config.js");
    } catch(err) {
      gutil.log("lambduh-gulp upload requires a ./lambda-config.js file to return a js object");
      throw err;
    }

    AWS.config.region = config.Region;
    var lambda = new AWS.Lambda();

    var params = {
      FunctionName: config.FunctionName,
      Description: config.Description,
      Handler: config.Handler,
      Role: config.Role,
      Runtime: config.Runtime,
      MemorySize: config.MemorySize,
      Timeout: config.Timeout
    };

    return fs.readFile('./dist.zip', function(err, zip) {
      params.Code = { ZipFile: zip };
      lambda.createFunction(params, function(err, data) {
        if (err && err.statusCode == 409) {//function already exists
          console.log("Function already exists, updating....");
          lambda.updateFunctionConfiguration({
            FunctionName: params.FunctionName,
            Description: params.Description,
            Handler: params.Handler,
            MemorySize: params.MemorySize,
            Role: params.Role,
            Timeout: params.Timeout
          }, function(err, data){
            if(err) {
              var warning = 'Fail while Updating Function Configuration';
              gutil.log(warning);
              //TODO: think about trying to update the code even if the config fails
              callback(err);
            } else {
              console.log("Successful function configuration update.");
              lambda.updateFunctionCode({
                FunctionName: params.FunctionName,
                ZipFile: params.Code.ZipFile
              }, function(err, data) {
                if(err) {
                  var warning = 'Fail while Updating Function Code';
                  gutil.log(warning);
                  callback(err);
                } else {
                  console.log("Successful function upload");
                  callback();
                }
              });
            }
          });
        } else if(err) {
          var warning = 'Fail while Creating Lambda Function';
          gutil.log(warning);
          callback(err);
        } else {
          console.log('Successfully created new lambda function');
          callback();
        }
      });
    });
  });

  gulp.task('zipload', function(callback) {
    return runSequence(
      ['lambda-zip'],
      ['upload'],
      callback
    );
  });
};

<commit_msg>detect filename is config file is available<commit_after>var gutil = require('gulp-util');
var zip = require('gulp-zip');
var del = require('del');
var install = require('gulp-install');
var runSequence = require('run-sequence');
var AWS = require('aws-sdk');
var fs = require('fs');

module.exports = function(gulp, opts) {
  if (!gulp) {
    gulp = require('gulp');
    runSequence.use(gulp);
  }

  if(!opts){
    opts = {};
  }

  gulp.task('clean', function(cb) {
    del(['./dist', './dist.zip'], cb);
  });

  gulp.task('js', function() {
    var config = {};

    try {
      config = require(process.cwd() + "/lambda-config.js");
    } catch(err) {
    }

    var file = config.Handler ? config.Handler.split('.')[0] : 'index';

    return gulp.src(file + '.js')
      .pipe(gulp.dest('dist/'));
  });

  gulp.task('bin', function() {
    return gulp.src('./bin/*')
      .pipe(gulp.dest('dist/'));
  });

  gulp.task('node-mods', function() {
    return gulp.src('./package.json')
      .pipe(gulp.dest('dist/'))
      .pipe(install({production: true, ignoreScripts: opts.ignoreScripts}));
  });

  gulp.task('zip', function() {
    return gulp.src(['dist/**/*', '!dist/package.json'])
      .pipe(zip('dist.zip'))
      .pipe(gulp.dest('./'));
  });

  gulp.task('lambda-zip', function(callback) {
    return runSequence(
      ['clean'],
      ['js', 'bin', 'node-mods'],
      ['zip'],
      callback
    );
  });

  gulp.task('upload', function(callback) {
    try {
      var config = require(process.cwd() + "/lambda-config.js");
    } catch(err) {
      gutil.log("lambduh-gulp upload requires a ./lambda-config.js file to return a js object");
      throw err;
    }

    AWS.config.region = config.Region;
    var lambda = new AWS.Lambda();

    var params = {
      FunctionName: config.FunctionName,
      Description: config.Description,
      Handler: config.Handler,
      Role: config.Role,
      Runtime: config.Runtime,
      MemorySize: config.MemorySize,
      Timeout: config.Timeout
    };

    return fs.readFile('./dist.zip', function(err, zip) {
      params.Code = { ZipFile: zip };
      lambda.createFunction(params, function(err, data) {
        if (err && err.statusCode == 409) {//function already exists
          console.log("Function already exists, updating....");
          lambda.updateFunctionConfiguration({
            FunctionName: params.FunctionName,
            Description: params.Description,
            Handler: params.Handler,
            MemorySize: params.MemorySize,
            Role: params.Role,
            Timeout: params.Timeout
          }, function(err, data){
            if(err) {
              var warning = 'Fail while Updating Function Configuration';
              gutil.log(warning);
              //TODO: think about trying to update the code even if the config fails
              callback(err);
            } else {
              console.log("Successful function configuration update.");
              lambda.updateFunctionCode({
                FunctionName: params.FunctionName,
                ZipFile: params.Code.ZipFile
              }, function(err, data) {
                if(err) {
                  var warning = 'Fail while Updating Function Code';
                  gutil.log(warning);
                  callback(err);
                } else {
                  console.log("Successful function upload");
                  callback();
                }
              });
            }
          });
        } else if(err) {
          var warning = 'Fail while Creating Lambda Function';
          gutil.log(warning);
          callback(err);
        } else {
          console.log('Successfully created new lambda function');
          callback();
        }
      });
    });
  });

  gulp.task('zipload', function(callback) {
    return runSequence(
      ['lambda-zip'],
      ['upload'],
      callback
    );
  });
};

<|endoftext|>


<commit_before>/*!
 * koa-ejs - index.js
 * Copyright(c) 2014 dead_horse <dead_horse@qq.com>
 * MIT Licensed
 */

'use strict';

/**
 * Module dependencies.
 */

var path = require('path');
var ejs = require('ejs');
var fs = require('co-fs');

/**
 * default render options
 * @type {Object}
 */
var _settings = {
  cache: true,
  layout: 'layout.html',
  viewExt: '',
  open: '<%',
  close: '%>',
  filters: {},
  locals: {},
  debug: false
};

/**
 * merge object source into object target
 * only if target[prop] not exist
 * @param {Object} target
 * @param {Object} source
 * @param {Object} ctx
 */
function merge(target, source, ctx) {
  for (var prop in source) {
    if (prop in target) {
      continue;
    }
    target[prop] = typeof source[prop] === 'function'
    ? source[prop].call(ctx)
    : source[prop];
  }
}

/**
 * cache the generate package
 * @type {Object}
 */
var cache = {};

/**
 * response the html to browser
 * @param {Object} ctx
 * @param {String} html
 */
function response(ctx, html) {
  ctx.type = 'html';
  ctx.length = html.length;
  ctx.body = html;
}

/**
 * set app.context.render
 *
 * usage:
 * ```
 * yield this.render('user', {name: 'dead_horse'});
 * ```
 * @param {Application} app koa application instance
 * @param {Object} settings user settings
 */
exports = module.exports = function (app, settings) {
  if (app.context.render) {
    return;
  }

  if (!settings || !settings.root) {
    throw new Error('settings.root required');
  }

  merge(settings, _settings);

  settings.viewExt = settings.viewExt
  ? '.' + settings.viewExt.replace(/^\./, '')
  : '';

  // ejs global options
  // if use koa-ejs in multi server, filters will regist in one ejs instance
  for (var name in settings.filters) {
    ejs.filters[name] = settings.filters[name];
  }

  /**
   * generate html with ejs function and options
   * @param {Function} fn ejs compiled function
   * @param {Object} options
   * @return {String}
   */
  function renderTpl(fn, options) {
    return options.scope
    ? fn.call(options.scope, options)
    : fn(options);
  }

  /**
   * generate html with view name and options
   * @param {String} view
   * @param {Object} options
   * @return {String} html
   */
  function *render(view, options) {
    view += settings.viewExt;
    var viewPath = path.join(settings.root, view);

    // get from cache
    if (settings.cache && cache[viewPath]) {
      return renderTpl(cache[viewPath], options);
    }

    var tpl = yield fs.readFile(viewPath, 'utf8');
    var fn = ejs.compile(tpl, {
      filename: viewPath,
      _with: settings._with,
      compileDebug: settings.debug
    });
    if (settings.cache) {
      cache[viewPath] = fn;
    }

    return renderTpl(fn, options);
  }

  app.context.render = function *(view, options) {
    // merge global locals to options
    merge(options, settings.locals, this);
    options.open = options.open || settings.open;
    options.close = options.close || settings.close;

    var html = yield render(view, options);

    var layout = options.layout || settings.layout;
    if (layout) {
      // if using layout
      options.body = html;
      html = yield render(layout, options);
    }
    response(this, html);
  };
};

exports.ejs = ejs;
<commit_msg>small edit<commit_after>/*!
 * koa-ejs - index.js
 * Copyright(c) 2014 dead_horse <dead_horse@qq.com>
 * MIT Licensed
 */

'use strict';

/**
 * Module dependencies.
 */

var path = require('path');
var ejs = require('ejs');
var fs = require('co-fs');

/**
 * default render options
 * @type {Object}
 */
var _settings = {
  cache: true,
  layout: 'layout.html',
  viewExt: '',
  open: '<%',
  close: '%>',
  filters: {},
  locals: {},
  debug: false
};

/**
 * merge object source into object target
 * only if target[prop] not exist
 * @param {Object} target
 * @param {Object} source
 * @param {Object} ctx
 */
function merge(target, source, ctx) {
  for (var prop in source) {
    if (prop in target) {
      continue;
    }
    target[prop] = typeof source[prop] === 'function'
    ? source[prop].call(ctx)
    : source[prop];
  }
}

/**
 * cache the generate package
 * @type {Object}
 */
var cache = {};

/**
 * response the html to browser
 * @param {Object} ctx
 * @param {String} html
 */
function response(ctx, html) {
  ctx.type = 'html';
  ctx.length = html.length;
  ctx.body = html;
}

/**
 * set app.context.render
 *
 * usage:
 * ```
 * yield this.render('user', {name: 'dead_horse'});
 * ```
 * @param {Application} app koa application instance
 * @param {Object} settings user settings
 */
exports = module.exports = function (app, settings) {
  if (app.context.render) {
    return;
  }

  if (!settings || !settings.root) {
    throw new Error('settings.root required');
  }

  merge(settings, _settings);

  settings.viewExt = settings.viewExt
  ? '.' + settings.viewExt.replace(/^\./, '')
  : '';

  // ejs global options
  // if use koa-ejs in multi server, filters will regist in one ejs instance
  for (var name in settings.filters) {
    ejs.filters[name] = settings.filters[name];
  }

  /**
   * generate html with ejs function and options
   * @param {Function} fn ejs compiled function
   * @param {Object} options
   * @return {String}
   */
  function renderTpl(fn, options) {
    return options.scope
    ? fn.call(options.scope, options)
    : fn(options);
  }

  /**
   * generate html with view name and options
   * @param {String} view
   * @param {Object} options
   * @return {String} html
   */
  function *render(view, options) {
    view += settings.viewExt;
    var viewPath = path.join(settings.root, view);

    // get from cache
    if (settings.cache && cache[viewPath]) {
      return renderTpl(cache[viewPath], options);
    }

    var tpl = yield fs.readFile(viewPath, 'utf8');
    var fn = ejs.compile(tpl, {
      filename: viewPath,
      _with: settings._with,
      compileDebug: settings.debug
    });
    if (settings.cache) {
      cache[viewPath] = fn;
    }

    return renderTpl(fn, options);
  }

  app.context.render = function *(view, options) {
    // merge global locals to options
    options = options || {};
    merge(options, settings.locals, this);
    options.open = options.open || settings.open;
    options.close = options.close || settings.close;

    var html = yield render(view, options);

    var layout = options.layout || settings.layout;
    if (layout) {
      // if using layout
      options.body = html;
      html = yield render(layout, options);
    }
    response(this, html);
  };
};

exports.ejs = ejs;
<|endoftext|>


<commit_before>

/**
 * create-user-info.js
 *
 * Create user info
 */

module.exports = factory;

/**
 * Export a factory function instead of middleware
 *
 * @return  MW
 */
function factory() {
	return middleware;
};

function *middleware(next) {
	yield next;

	var db = this.db;
	var User = db.col('users');

	var body = this.request.body;

	if(!body || !body.uid){
		this.status = 400;
		this.body = {
			code: 400,
			message: "Invalid request",
		};
		return;
	}

	var profile = yield User.findOne({
		uid: body.uid
	});

	if(profile){
		this.status = 409;
		this.body = {
			code: 409,
			message: "User is already exist.",
		};
		return;
	}

	var result = yield User.insert({
		  uid: body.uid
		, name: body.name
		, title: body.title
		, info: body.info
		, location: body.location
		, image: body.image
	});

	this.body = {
		code: 200,
		data : body
	};
};
<commit_msg>get new profile from db.<commit_after>

/**
 * create-user-info.js
 *
 * Create user info
 */

module.exports = factory;

/**
 * Export a factory function instead of middleware
 *
 * @return  MW
 */
function factory() {
	return middleware;
};

function *middleware(next) {
	yield next;

	var db = this.db;
	var User = db.col('users');

	var body = this.request.body;

	if(!body || !body.uid){
		this.status = 400;
		this.body = {
			code: 400,
			message: "Invalid request",
		};
		return;
	}

	var profile = yield User.findOne({
		uid: body.uid
	});

	if(profile){
		this.status = 409;
		this.body = {
			code: 409,
			message: "User is already exist.",
		};
		return;
	}

	var result = yield User.insert({
		  uid: body.uid
		, name: body.name
		, title: body.title
		, info: body.info
		, location: body.location
		, image: body.image
	});

	var new_profile = yield User.findOne({
		  uid: body.uid
	});

	this.body = {
		code: 200,
		data : new_profile
	};
};
<|endoftext|>


<commit_before>'use strict';

var from         = require('es5-ext/array/from')
  , primitiveSet = require('es5-ext/object/primitive-set')
  , eolSet       = require('./lib/ws-eol')
  , wsSet        = require('./lib/ws')

  , hasOwnProperty = Object.prototype.hasOwnProperty

  , next, move, startCollect, endCollect, collectNest
  , $common, $string, $comment, $multiComment, $regExp

  , str, i, char, line, column, afterWs, previous
  , blocks, nest, tenaryNest, lastBlock, lastTenary, nestedTokens, results
  , callback

  , quote
  , collect, data, nestRelease, token
  , preDeclSet, ambigSet, preExpSet;

// Opens declaration blocks
preDeclSet = primitiveSet.apply(null, from(';{'));
// May open decl block
ambigSet = primitiveSet.apply(null, from(':}'));
// Opens expression blocks
preExpSet = primitiveSet.apply(null, from('=([,<>+-*/%&|^!~?'));

next = function () {
	if (!char) return;
	if (collect) token += char;
	if (!hasOwnProperty.call(wsSet, char)) {
		previous = char;
		++column;
		afterWs = false;
	} else if (hasOwnProperty.call(eolSet, char)) {
		column = 1;
		++line;
		afterWs = true;
	} else {
		afterWs = true;
		++column;
	}
	char = str[i];
	++i;
	return char;
};

move = function (j) {
	if (!char) return;
	if (i >= j) return;
	--j;
	while (i !== j) {
		if (!char) return;
		if (collect) token += char;
		if (!hasOwnProperty.call(wsSet, char)) {
			++column;
		} else if (hasOwnProperty.call(eolSet, char)) {
			column = 1;
			++line;
		} else {
			++column;
		}
		char = str[i];
		++i;
	}
	next();
};

startCollect = function (oldNestRelease) {
	if (token != null) nestedTokens.push([data, token, oldNestRelease]);
	data = { line: line, column: column, point: i };
	token = '';
	collect = true;
};

endCollect = function () {
	var previous;
	data.raw = token;
	results.push(data);
	if (nestedTokens.length) {
		previous = nestedTokens.pop();
		data = previous[0];
		token = previous[1] + token;
		nestRelease = previous[2];
		return;
	}
	collect = false;
	token = null;
	nestRelease = null;
};

collectNest = function () {
	var old = nestRelease;
	nestRelease = nest;
	++nest;
	if (!next()) return $common;
	startCollect(old);
	return $common();
};

$common = function () {
	var prev, val;
	while (char && hasOwnProperty.call(wsSet, char)) next();
	if (char === '.') return $common;
	if ((char === '\'') || (char === '"')) {
		quote = char;
		return $string;
	}
	if (char === '(') {
		++nest;
		return $common;
	}
	if (char === ')') {
		if (nestRelease === --nest) endCollect();
		return $common;
	}
	if (char === '{') {
		++nest;
		if (!previous) val = true;
		else if (preExpSet[previous]) val = false;
		else if ((previous === ':') && lastTenary) val = false;
		else val = true;
		blocks.push(val);
		return $common;
	}
	if (char === '}') {
		if (nestRelease === --nest) {
			nestRelease = null;
			endCollect();
			if (exports.forceStop) {
				i = Infinity;
				return $common;
			}
		}
		lastBlock = blocks.pop();
		return $common;
	}
	if (char === '?') {
		++tenaryNest;
		return $common;
	}
	if (char === ':') {
		if (tenaryNest) {
			--tenaryNest;
			lastTenary = true;
		} else {
			lastTenary = false;
		}
		return $common;
	}
	if (char === '/') {
		prev = previous;
		if (!next()) return $common;
		if (char === '/') return $comment;
		if (char === '*') return $multiComment;
		if (hasOwnProperty.call(preExpSet, prev) ||
				hasOwnProperty.call(preDeclSet, prev)) {
			return $regExp();
		}
		if ((prev === '}') && lastBlock) return $regExp();
		if ((prev === ':') && lastTenary) return $regExp();
		return $common();
	}
	if (previous) {
		if (!afterWs && !hasOwnProperty.call(preExpSet, previous) &&
				!hasOwnProperty.call(preDeclSet, previous) &&
				!hasOwnProperty.call(ambigSet, previous)) {
			return $common;
		}
	}

	return callback(char, i, previous, line, column);
};

$string = function () {
	if (char === '\\') {
		next();
		return $string;
	}
	if (char === quote) return $common;
	return $string;
};

$comment = function () {
	if (hasOwnProperty.call(eolSet, char)) return $common;
	return $comment;
};

$multiComment = function () {
	if (char !== '*') return $multiComment;
	if (str[i] !== '/') return $multiComment;
	next();
	return $common;
};

$regExp = function () {
	if (char === '\\') {
		next();
		return $regExp;
	}
	if (char === '/') return $common;
	return $regExp;
};

module.exports = exports = function (code, cb) {
	var state;

	str = String(code);
	i = 1;
	char = str[0];
	line = 1;
	column = 1;
	afterWs = false;
	previous = null;
	blocks = [];
	nest = tenaryNest = 0;
	lastBlock = lastTenary = false;
	nestedTokens = [];
	results = [];
	callback = cb;
	exports.forceStop = false;
	state = $common;
	while (char) {
		state = state();
		next();
	}
	return results;
};

exports.$common = $common;
exports.collectNest = collectNest;
exports.wsSet = wsSet;
exports.move = move;
<commit_msg>Simplify columns calculation<commit_after>'use strict';

var from         = require('es5-ext/array/from')
  , primitiveSet = require('es5-ext/object/primitive-set')
  , eolSet       = require('./lib/ws-eol')
  , wsSet        = require('./lib/ws')

  , hasOwnProperty = Object.prototype.hasOwnProperty

  , next, move, startCollect, endCollect, collectNest
  , $common, $string, $comment, $multiComment, $regExp

  , str, i, char, line, columnStart, afterWs, previous
  , blocks, nest, tenaryNest, lastBlock, lastTenary, nestedTokens, results
  , callback

  , quote
  , collect, data, nestRelease, token
  , preDeclSet, ambigSet, preExpSet;

// Opens declaration blocks
preDeclSet = primitiveSet.apply(null, from(';{'));
// May open decl block
ambigSet = primitiveSet.apply(null, from(':}'));
// Opens expression blocks
preExpSet = primitiveSet.apply(null, from('=([,<>+-*/%&|^!~?'));

next = function () {
	if (!char) return;
	if (collect) token += char;
	if (!hasOwnProperty.call(wsSet, char)) {
		previous = char;
		afterWs = false;
	} else if (hasOwnProperty.call(eolSet, char)) {
		columnStart = i;
		++line;
		afterWs = true;
	} else {
		afterWs = true;
	}
	char = str[i];
	++i;
	return char;
};

move = function (j) {
	if (!char) return;
	if (i >= j) return;
	--j;
	while (i !== j) {
		if (!char) return;
		if (collect) token += char;
		if (hasOwnProperty.call(eolSet, char)) {
			columnStart = i;
			++line;
		}
		char = str[i];
		++i;
	}
	next();
};

startCollect = function (oldNestRelease) {
	if (token != null) nestedTokens.push([data, token, oldNestRelease]);
	data = { line: line, column: i - columnStart, point: i };
	token = '';
	collect = true;
};

endCollect = function () {
	var previous;
	data.raw = token;
	results.push(data);
	if (nestedTokens.length) {
		previous = nestedTokens.pop();
		data = previous[0];
		token = previous[1] + token;
		nestRelease = previous[2];
		return;
	}
	collect = false;
	token = null;
	nestRelease = null;
};

collectNest = function () {
	var old = nestRelease;
	nestRelease = nest;
	++nest;
	if (!next()) return $common;
	startCollect(old);
	return $common();
};

$common = function () {
	var prev, val;
	while (char && hasOwnProperty.call(wsSet, char)) next();
	if (char === '.') return $common;
	if ((char === '\'') || (char === '"')) {
		quote = char;
		return $string;
	}
	if (char === '(') {
		++nest;
		return $common;
	}
	if (char === ')') {
		if (nestRelease === --nest) endCollect();
		return $common;
	}
	if (char === '{') {
		++nest;
		if (!previous) val = true;
		else if (preExpSet[previous]) val = false;
		else if ((previous === ':') && lastTenary) val = false;
		else val = true;
		blocks.push(val);
		return $common;
	}
	if (char === '}') {
		if (nestRelease === --nest) {
			nestRelease = null;
			endCollect();
			if (exports.forceStop) {
				i = Infinity;
				return $common;
			}
		}
		lastBlock = blocks.pop();
		return $common;
	}
	if (char === '?') {
		++tenaryNest;
		return $common;
	}
	if (char === ':') {
		if (tenaryNest) {
			--tenaryNest;
			lastTenary = true;
		} else {
			lastTenary = false;
		}
		return $common;
	}
	if (char === '/') {
		prev = previous;
		if (!next()) return $common;
		if (char === '/') return $comment;
		if (char === '*') return $multiComment;
		if (hasOwnProperty.call(preExpSet, prev) ||
				hasOwnProperty.call(preDeclSet, prev)) {
			return $regExp();
		}
		if ((prev === '}') && lastBlock) return $regExp();
		if ((prev === ':') && lastTenary) return $regExp();
		return $common();
	}
	if (previous) {
		if (!afterWs && !hasOwnProperty.call(preExpSet, previous) &&
				!hasOwnProperty.call(preDeclSet, previous) &&
				!hasOwnProperty.call(ambigSet, previous)) {
			return $common;
		}
	}

	return callback(char, i, previous, line, i - columnStart);
};

$string = function () {
	if (char === '\\') {
		next();
		return $string;
	}
	if (char === quote) return $common;
	return $string;
};

$comment = function () {
	if (hasOwnProperty.call(eolSet, char)) return $common;
	return $comment;
};

$multiComment = function () {
	if (char !== '*') return $multiComment;
	if (str[i] !== '/') return $multiComment;
	next();
	return $common;
};

$regExp = function () {
	if (char === '\\') {
		next();
		return $regExp;
	}
	if (char === '/') return $common;
	return $regExp;
};

module.exports = exports = function (code, cb) {
	var state;

	str = String(code);
	i = 1;
	char = str[0];
	line = 1;
	columnStart = 0;
	afterWs = false;
	previous = null;
	blocks = [];
	nest = tenaryNest = 0;
	lastBlock = lastTenary = false;
	nestedTokens = [];
	results = [];
	callback = cb;
	exports.forceStop = false;
	state = $common;
	while (char) {
		state = state();
		next();
	}
	return results;
};

exports.$common = $common;
exports.collectNest = collectNest;
exports.wsSet = wsSet;
exports.move = move;
<|endoftext|>


<commit_before>/**
 * @namespace hs.layermanager
 * @memberOf hs
 */
define(['angular', 'app', 'map', 'ol'], function(angular, app, map, ol) {
    angular.module('hs.layermanager', ['hs.map'])

    /**
     * @class hs.layermanager.directive
     * @memberOf hs.layermanager
     * @description Directive for displaying layer manager panel
     */
    .directive('hs.layermanager.directive', function() {
        return {
            templateUrl: hsl_path + 'components/layermanager/partials/layermanager.html'
        };
    })

    /**
     * @class hs.layermanager.controller
     * @memberOf hs.layermanager
     * @description Layer manager controller
     */
    .controller('hs.layermanager.controller', ['$scope', 'hs.map.service', 'box_layers', '$rootScope', 'Core',
        function($scope, OlMap, box_layers, $rootScope, Core) {
            $scope.Core = Core;
            var map = OlMap.map;
            var cur_layer_opacity = 1;

            var layerAdded = function(e) {
                if (e.element.get('show_in_manager') != null && e.element.get('show_in_manager') == false) return;
                var sub_layers;
                if (e.element.getSource().getParams) { // Legend only for wms layers with params
                    sub_layers = e.element.getSource().getParams().LAYERS.split(",");
                    for (var i = 0; i < sub_layers.length; i++) {
                        if (e.element.getSource().getUrls) //Multi tile
                            sub_layers[i] = e.element.getSource().getUrls()[0] + "&version=1.3.0&service=WMS&request=GetLegendGraphic&sld_version=1.1.0&layer=" + sub_layers[i] + "&format=image/png";
                        if (e.element.getSource().getUrl) //Single tile
                            sub_layers[i] = e.element.getSource().getUrl() + "&version=1.3.0&service=WMS&request=GetLegendGraphic&sld_version=1.1.0&layer=" + sub_layers[i] + "&format=image/png";
                    }
                }
                e.element.on('change:visible', function(e) {
                    for (var i = 0; i < $scope.layers.length; i++) {
                        if ($scope.layers[i].layer == e.target) {
                            $scope.layers[i].visible = e.target.getVisible();
                            break;
                        }
                    }
                    if (!$scope.$$phase) $scope.$digest();
                })
                $scope.layers.push({
                    title: e.element.get("title"),
                    layer: e.element,
                    sub_layers: sub_layers,
                    visible: e.element.getVisible()
                });
                $rootScope.$broadcast('layermanager.updated');
            };

            var layerRemoved = function(e) {
                $(".layermanager-list").prepend($('.layerpanel'));
                $scope.currentlayer = null;
                for (var i = 0; i < $scope.layers.length; i++) {
                    if ($scope.layers[i].layer == e.element) {
                        $scope.layers.splice(i, 1);
                    }
                }
                $rootScope.$broadcast('layermanager.updated');
            };

            $scope.box_layers = box_layers;
            $scope.layers = [];
            $scope.active_box = null;

            $scope.changeLayerVisibility = function($event, layer) {
                layer.layer.setVisible($event.target.checked);
            }

            $scope.setCurrentLayer = function(layer, index) {
                $scope.currentlayer = layer;
                $(".layerpanel").insertAfter($("#layer-" + index));
                $scope.cur_layer_opacity = layer.layer.getOpacity();
                if (console) console.log(layer);
                return false;
            }

            $scope.removeLayer = function(layer) {
                map.removeLayer(layer);
            }

            $scope.zoomToLayer = function(layer) {
                var extent = null;
                if (layer.get("BoundingBox")) {
                    b = layer.get("BoundingBox")[0].extent;
                    var first_pair = [b[0], b[1]]
                    var second_pair = [b[2], b[3]];
                    first_pair = ol.proj.transform(first_pair, layer.get("BoundingBox")[0].crs, map.getView().getProjection());
                    second_pair = ol.proj.transform(second_pair, layer.get("BoundingBox")[0].crs, map.getView().getProjection());
                    var extent = [first_pair[0], first_pair[1], second_pair[0], second_pair[1]];
                } else {
                    extent = layer.getSource().getExtent();
                }
                if (extent != null)
                    map.getView().fitExtent(extent, map.getSize());
            }

            $scope.layerIsZoomable = function(layer) {
                if (typeof layer == 'undefined') return false;
                if (layer.get("BoundingBox")) return true;
                if (layer.getSource().getExtent && layer.getSource().getExtent()) return true;
                return false;
            }

            $scope.activateTheme = function(theme) {
                if ($scope.active_box) $scope.active_box.set('active', false);
                $scope.active_box = theme;
                theme.set('active', true);
                angular.forEach(box_layers, function(box) {
                    box.setVisible(box == theme);
                    angular.forEach(box.get('layers'), function(lyr) {
                        if (lyr.get('base') == true) return;
                        lyr.setVisible(box.getVisible());
                    });
                });
            }

            OlMap.map.getLayers().forEach(function(lyr) {
                layerAdded({
                    element: lyr
                });
            });
            map.getLayers().on("add", layerAdded);
            map.getLayers().on("remove", layerRemoved);
            $scope.$emit('scope_loaded', "LayerManager");
        }
    ]);
})
<commit_msg>Documentation for layer manager module<commit_after>/**
 * @namespace hs.layermanager
 * @memberOf hs
 */
define(['angular', 'app', 'map', 'ol'], function(angular, app, map, ol) {
    angular.module('hs.layermanager', ['hs.map'])

    /**
     * @class hs.layermanager.directive
     * @memberOf hs.layermanager
     * @description Directive for displaying layer manager panel
     */
    .directive('hs.layermanager.directive', function() {
        return {
            templateUrl: hsl_path + 'components/layermanager/partials/layermanager.html'
        };
    })

    /**
     * @class hs.layermanager.controller
     * @memberOf hs.layermanager
     * @description Layer manager controller
     */
    .controller('hs.layermanager.controller', ['$scope', 'hs.map.service', 'box_layers', '$rootScope', 'Core',
        function($scope, OlMap, box_layers, $rootScope, Core) {
            $scope.Core = Core;
            var map = OlMap.map;
            var cur_layer_opacity = 1;

            /**
            * @function layerAdded
            * @memberOf hs.layermanager.controller
            * @description Callback function for layer adding
            * @param {ol.CollectionEvent} e - Events emitted by ol.Collection instances are instances of this type.
            */
            var layerAdded = function(e) {
                if (e.element.get('show_in_manager') != null && e.element.get('show_in_manager') == false) return;
                var sub_layers;
                if (e.element.getSource().getParams) { // Legend only for wms layers with params
                    sub_layers = e.element.getSource().getParams().LAYERS.split(",");
                    for (var i = 0; i < sub_layers.length; i++) {
                        if (e.element.getSource().getUrls) //Multi tile
                            sub_layers[i] = e.element.getSource().getUrls()[0] + "&version=1.3.0&service=WMS&request=GetLegendGraphic&sld_version=1.1.0&layer=" + sub_layers[i] + "&format=image/png";
                        if (e.element.getSource().getUrl) //Single tile
                            sub_layers[i] = e.element.getSource().getUrl() + "&version=1.3.0&service=WMS&request=GetLegendGraphic&sld_version=1.1.0&layer=" + sub_layers[i] + "&format=image/png";
                    }
                }
                e.element.on('change:visible', function(e) {
                    for (var i = 0; i < $scope.layers.length; i++) {
                        if ($scope.layers[i].layer == e.target) {
                            $scope.layers[i].visible = e.target.getVisible();
                            break;
                        }
                    }
                    if (!$scope.$$phase) $scope.$digest();
                })
                $scope.layers.push({
                    title: e.element.get("title"),
                    layer: e.element,
                    sub_layers: sub_layers,
                    visible: e.element.getVisible()
                });
                $rootScope.$broadcast('layermanager.updated');
            };

            /**
            * @function layerRemoved
            * @memberOf hs.layermanager.controller
            * @description Callback function for layer removing
            * @param {ol.CollectionEvent} e - Events emitted by ol.Collection instances are instances of this type.
            */
            var layerRemoved = function(e) {
                $(".layermanager-list").prepend($('.layerpanel'));
                $scope.currentlayer = null;
                for (var i = 0; i < $scope.layers.length; i++) {
                    if ($scope.layers[i].layer == e.element) {
                        $scope.layers.splice(i, 1);
                    }
                }
                $rootScope.$broadcast('layermanager.updated');
            };

            $scope.box_layers = box_layers;
            $scope.layers = [];
            $scope.active_box = null;

            /**
            * @function changeLayerVisibility
            * @memberOf hs.layermanager.controller
            * @description Callback function to set layers visibility
            * @param {object} $event - Info about the event and checkbox being clicked on
            * @param {object} layer - Wrapped ol.Layer
            */
            $scope.changeLayerVisibility = function($event, layer) {
                layer.layer.setVisible($event.target.checked);
            }

            /**
            * @function setCurrentLayer
            * @memberOf hs.layermanager.controller
            * @description Opens detailed view for manipulating layer and viewing metadata
            * @param {object} layer - Wrapped layer to edit or view
            * @param {number} index - Used to position the detail panel after layers li element
            */
            $scope.setCurrentLayer = function(layer, index) {
                $scope.currentlayer = layer;
                $(".layerpanel").insertAfter($("#layer-" + index));
                $scope.cur_layer_opacity = layer.layer.getOpacity();
                if (console) console.log(layer);
                return false;
            }

            /**
            * @function removeLayer
            * @memberOf hs.layermanager.controller
            * @description Removes layer from map
            * @param {object} layer
            */
            $scope.removeLayer = function(layer) {
                map.removeLayer(layer);
            }

            /**
            * @function zoomToLayer
            * @memberOf hs.layermanager.controller
            * @description Tries to read the BoundingBox property of layer or getExtent() of its source and zooms to it
            * @param {object} layer
            */
            $scope.zoomToLayer = function(layer) {
                var extent = null;
                if (layer.get("BoundingBox")) {
                    b = layer.get("BoundingBox")[0].extent;
                    var first_pair = [b[0], b[1]]
                    var second_pair = [b[2], b[3]];
                    first_pair = ol.proj.transform(first_pair, layer.get("BoundingBox")[0].crs, map.getView().getProjection());
                    second_pair = ol.proj.transform(second_pair, layer.get("BoundingBox")[0].crs, map.getView().getProjection());
                    var extent = [first_pair[0], first_pair[1], second_pair[0], second_pair[1]];
                } else {
                    extent = layer.getSource().getExtent();
                }
                if (extent != null)
                    map.getView().fitExtent(extent, map.getSize());
            }

            /**
            * @function layerIsZoomable
            * @memberOf hs.layermanager.controller
            * @description Determines if layer has BoundingBox defined as its metadata or is a Vector layer. Used for setting visibility of 'Zoom to ' button
            * @param {object} layer
            */
            $scope.layerIsZoomable = function(layer) {
                if (typeof layer == 'undefined') return false;
                if (layer.get("BoundingBox")) return true;
                if (layer.getSource().getExtent && layer.getSource().getExtent()) return true;
                return false;
            }

            /**
            * @function activateTheme
            * @memberOf hs.layermanager.controller
            * @description Show a particular groups layers, hide allthe rest
            * @param {ol.layer.Group} theme - Group layer to activate
            */
            $scope.activateTheme = function(theme) {
                if ($scope.active_box) $scope.active_box.set('active', false);
                $scope.active_box = theme;
                theme.set('active', true);
                angular.forEach(box_layers, function(box) {
                    box.setVisible(box == theme);
                    angular.forEach(box.get('layers'), function(lyr) {
                        if (lyr.get('base') == true) return;
                        lyr.setVisible(box.getVisible());
                    });
                });
            }

            OlMap.map.getLayers().forEach(function(lyr) {
                layerAdded({
                    element: lyr
                });
            });
            map.getLayers().on("add", layerAdded);
            map.getLayers().on("remove", layerRemoved);
            $scope.$emit('scope_loaded', "LayerManager");
        }
    ]);
})
<|endoftext|>


<commit_before>'use strict';

const postcss = require('postcss');
const helpers = require('./lib/helpers');

module.exports = postcss.plugin('postcss-js-mixins', (options = {}) => {
	let mixins = options.mixins || {};

	if (options.units) {
		helpers.setDefaultUnits(options.units);
	}

	function isNumber(value) {
		let val = parseFloat(value);

		// Check that parseFloat did not create NaN or infinity and
		// make sure no other characters exist in original value but numerical digits
		return ! isNaN(val) && isFinite(val) && ! /[^\d.]/.test(value);
	}

	/**
	 * Evaluate mixin
	 *
	 * @param {object} node - postcss.Node
	 * @param {object} result - postcss.Result
	 * @returns {array|object}
	 */
	function evalMixin(node, result) {
		let segs = node.name.split('.'),
			key = segs.shift(),
			mixin = mixins[key],
			args = node.arguments.map(arg => {
				if (isNumber(arg)) {
					return parseFloat(arg);
				} else if (typeof arg === 'string') {
					if (arg === 'false' || arg === 'true') {
						return arg === 'true';
					}

					return arg.length ? arg : undefined;
				}

				return arg;
			});

		while (segs.length && mixin.hasOwnProperty(segs[0])) {
			mixin = mixin[segs[0]];
			segs.shift();
		}

		if (! mixin || segs.length) {
			node.warn(result, 'Mixin not found.');
			return [];
		}

		return mixin.apply(mixins, args);
	}

	/**
	 * Create many declarations/rules from one mixin result
	 *
	 * @param {array} data
	 * @param {object} node - postcss.Mixin
	 */
	function createNodes(data, node) {
		return data.map(obj => {
			return createNode(obj, node);
		});
	}

	function createNode(obj, node) {
		if (obj.type === 'rule') {
			return createRule(obj.selector, obj.declarations, node);
		}

		return createDeclaration(obj.prop, obj.value, node);
	}

	/**
	 * Create postcss declaration with meta info from mixin
	 *
	 * @param {string} selector
	 * @param {Array} declarations - one or many postcss.Declaration
	 * @param {object} node - postcss.Mixin
	 * @returns {Rule}
	 */
	function createRule(selector, declarations, node) {
		let rule = postcss.rule({
			selector: selector,
			parent: node.parent,
			source: node.source
		});

		declarations.forEach(decl => {
			rule.append(createDeclaration(decl.prop, decl.value, node));
		});

		return rule;
	}

	/**
	 * Create postcss declaration with meta info from mixin
	 *
	 * @param {string} prop
	 * @param {string|number} value
	 * @param {object} node - postcss.Mixin
	 * @returns {Declaration}
	 */
	function createDeclaration(prop, value, node) {
		let decl = postcss.decl({
			prop: prop,
			value: value,
			parent: node.parent,
			source: node.source
		});

		return decl;
	}

	return (root, result) => {
		root.walk(node => {
			if (node.type === 'mixin') {
				let results = evalMixin(node, result);

				// Remove mixin from CSS
				// Accounting for conditional mixin logic
				if (results === false) {
					return node.remove();
				}

				if (Array.isArray(results)) {
					if (! results.length) {
						return;
					}

					node.replaceWith(createNodes(results, node));
				}

				node.replaceWith(createNode(results, node));
			}
		});
	};
});<commit_msg>Remove empty line<commit_after>'use strict';

const postcss = require('postcss');
const helpers = require('./lib/helpers');

module.exports = postcss.plugin('postcss-js-mixins', (options = {}) => {
	let mixins = options.mixins || {};

	if (options.units) {
		helpers.setDefaultUnits(options.units);
	}

	function isNumber(value) {
		let val = parseFloat(value);

		// Check that parseFloat did not create NaN or infinity and
		// make sure no other characters exist in original value but numerical digits
		return ! isNaN(val) && isFinite(val) && ! /[^\d.]/.test(value);
	}

	/**
	 * Evaluate mixin
	 *
	 * @param {object} node - postcss.Node
	 * @param {object} result - postcss.Result
	 * @returns {array|object}
	 */
	function evalMixin(node, result) {
		let segs = node.name.split('.'),
			key = segs.shift(),
			mixin = mixins[key],
			args = node.arguments.map(arg => {
				if (isNumber(arg)) {
					return parseFloat(arg);
				} else if (typeof arg === 'string') {
					if (arg === 'false' || arg === 'true') {
						return arg === 'true';
					}
					return arg.length ? arg : undefined;
				}

				return arg;
			});

		while (segs.length && mixin.hasOwnProperty(segs[0])) {
			mixin = mixin[segs[0]];
			segs.shift();
		}

		if (! mixin || segs.length) {
			node.warn(result, 'Mixin not found.');
			return [];
		}

		return mixin.apply(mixins, args);
	}

	/**
	 * Create many declarations/rules from one mixin result
	 *
	 * @param {array} data
	 * @param {object} node - postcss.Mixin
	 */
	function createNodes(data, node) {
		return data.map(obj => {
			return createNode(obj, node);
		});
	}

	function createNode(obj, node) {
		if (obj.type === 'rule') {
			return createRule(obj.selector, obj.declarations, node);
		}

		return createDeclaration(obj.prop, obj.value, node);
	}

	/**
	 * Create postcss declaration with meta info from mixin
	 *
	 * @param {string} selector
	 * @param {Array} declarations - one or many postcss.Declaration
	 * @param {object} node - postcss.Mixin
	 * @returns {Rule}
	 */
	function createRule(selector, declarations, node) {
		let rule = postcss.rule({
			selector: selector,
			parent: node.parent,
			source: node.source
		});

		declarations.forEach(decl => {
			rule.append(createDeclaration(decl.prop, decl.value, node));
		});

		return rule;
	}

	/**
	 * Create postcss declaration with meta info from mixin
	 *
	 * @param {string} prop
	 * @param {string|number} value
	 * @param {object} node - postcss.Mixin
	 * @returns {Declaration}
	 */
	function createDeclaration(prop, value, node) {
		let decl = postcss.decl({
			prop: prop,
			value: value,
			parent: node.parent,
			source: node.source
		});

		return decl;
	}

	return (root, result) => {
		root.walk(node => {
			if (node.type === 'mixin') {
				let results = evalMixin(node, result);

				// Remove mixin from CSS
				// Accounting for conditional mixin logic
				if (results === false) {
					return node.remove();
				}

				if (Array.isArray(results)) {
					if (! results.length) {
						return;
					}

					node.replaceWith(createNodes(results, node));
				}

				node.replaceWith(createNode(results, node));
			}
		});
	};
});<|endoftext|>


<commit_before>// Hook for transform all ES6 files on the fly.
require('babel-register');

module.exports = require('./src/google-maps.module.es6');
<commit_msg>remove index.js<commit_after><|endoftext|>


<commit_before>'use strict';

module.exports = {
  name: 'Ember CLI ic-ajax',

  init: function(name) {
    var assets_path = require('path').join('ic-ajax','dist','cjs','main.js');
    this.treePaths['vendor'] = require.resolve('ic-ajax').replace(assets_path, '');
  },

  included: function(app) {
    var options = this.app.options.icAjaxOptions || {enabled: true};

    if (options.enabled) {
      this.app.import('vendor/ic-ajax/dist/named-amd/main.js', {
        exports: {
          'ic-ajax': [
            'default',
            'defineFixture',
            'lookupFixture',
            'raw',
            'request',
          ]
        }
      });
    }
  }
};
<commit_msg>Added deprecation notice<commit_after>'use strict';

module.exports = {
  name: 'Ember CLI ic-ajax',

  init: function(name) {
    var assets_path = require('path').join('ic-ajax','dist','cjs','main.js');
    this.treePaths['vendor'] = require.resolve('ic-ajax').replace(assets_path, '');
  },

  included: function(app) {
    var options = this.app.options.icAjaxOptions || {enabled: true};

    if (options.enabled) {
      this.ui.writeError('ember-cli-ic-ajax is deprecated in favour of ember-ajax. ' +
         'ember-cli-ic-ajax will be removed from app blueprint in ember-cli@2.0.0. ' +
         'https://github.com/embersherpa/ember-ajax#upgrade-from-ic-ajax');

      this.app.import('vendor/ic-ajax/dist/named-amd/main.js', {
        exports: {
          'ic-ajax': [
            'default',
            'defineFixture',
            'lookupFixture',
            'raw',
            'request',
          ]
        }
      });
    }
  }
};
<|endoftext|>


<commit_before>import MagnonElement from "../../src/magnon-element.js";

import html from "./image.content.js";
import css from "./image.style.js";

import "../magnon-styles/magnon-styles.js";
import "../magnon-icon-button/magnon-icon-button.js";

let counter = 0;

export class MagnonImage extends MagnonElement {
    constructor() {
        super({ content: html + css });

        this._fullscreenEnabled = true;
    }

    static get elementName() {
        return "magnon-image";
    }

    static get propertyAttributes() {
        return {
            bool: ["show-alt", "no-fullscreen", "disable-image-url"],
            string: ["src", "alt"]
        };
    }

    contentReady() {
        this._image = this.root.querySelector("#main-image");
        this._altText = this.root.querySelector("#alt-text");

        this._fullscreenContainer = this.root.querySelector("#fullscreen-container");
        this._fullscreenBackdrop = this.root.querySelector("#fullscreen-backdrop");
        this._fullscreenImage = this.root.querySelector("#fullscreen-image");
        this._fullscreenText = this.root.querySelector("#fullscreen-text");
        this._fullscreenCloseButton = this.root.querySelector(".close-button");

        this._fullscreenOpacity = "1";

        this._image.addEventListener("load", () => this._updateImageSize());
        this._image.addEventListener("click", () => {
            if (!this.disableImageUrl && location.hash.startsWith("#mimg-")) return;

            if (!this._animating && this._fullscreenEnabled) {
                if (this.disableImageUrl) {
                    this.fullscreen = true;
                } else {
                    location.hash = this._hash;
                }
            }
        });
        const close = () => {
            if (this._animating) return;

            if (this.disableImageUrl) {
                this.fullscreen = false;
            } else {
                const current = location.href.match(/([^#]*)/)[0];

                if (!this._directlyLinked) {
                    history.back();
                } else {
                    history.replaceState(null, null, current);
                }

                this._checkHash();
            }
        };
        this._fullscreenBackdrop.addEventListener("click", close);
        this._fullscreenCloseButton.addEventListener("click", close);

        window.addEventListener("resize", () => this._updateImageSize());
        window.addEventListener("hashchange", () => this._checkHash());

        this.fullscreen = false;
    }

    get _hasDescription() {
        return this.textContent.trim().length > 0;
    }

    get _hash() {
        return `#mimg-${this._count}`;
    }

    set fullscreen(value) {
        if (value && !this._fullscreenEnabled) return;

        if (this._animating) return;

        this._animating = true;

        this.style.transform = "none";

        this._updateDescription();
        this._updateImageSize();

        if (value) {
            // Disable scroll
            document.body.style.overflow = "hidden";

            // The rest
            this._fullscreenContainer.style.pointerEvents = "all";

            this._fullscreenImage.style.opacity = "1";
            this._fullscreenBackdrop.style.opacity = this._fullscreenOpacity;

            this._image.style.transition = "none";
            this._image.style.opacity = "0";

            this._altText.style.opacity = "0";

            const startBox = this._image.getBoundingClientRect();
            const startBorderRadius = this._image.style.getPropertyValue("--magnon-image-border-radius");
            const endBox = this._fullscreenImage.getBoundingClientRect();

            this._fullscreenImage.style.transition = "none";

            this._fullscreenImage.style.transform = `
                translate(${startBox.left - endBox.left}px, ${startBox.top - endBox.top}px)
                scale(${startBox.width / endBox.width}, ${startBox.height / endBox.height})
            `;

            this._fullscreenImage.style.borderRadius = startBorderRadius;

            setTimeout(() => {
                this._fullscreenImage.style.transition = "";

                this._fullscreenImage.style.transform = `
                    translate(0px, 0px)
                    scale(1, 1)
                `;

                this._fullscreenImage.style.borderRadius = "0";

                this._fullscreenText.style.opacity = "1";
                this._fullscreenCloseButton.style.opacity = "1";

                const endAction = () => {
                    this._fullscreenImage.removeAttribute("style");
                    this._fullscreenImage.removeEventListener("transitionend", endAction);

                    this._image.style.transition = "";

                    this._animating = false;
                };
                this._fullscreenImage.addEventListener("transitionend", endAction);
            }, 100);
        } else {
            // Enable scroll
            document.body.style.overflow = "auto";

            // The rest
            const endAction = () => {
                this.style.transform = "";

                this._fullscreenContainer.style.pointerEvents = "none";
                this._fullscreenBackdrop.removeEventListener("transitionend", endAction);

                this._animating = false;
            };

            if (this._fullscreenBackdrop.style.opacity !== "") {
                this._fullscreenBackdrop.addEventListener("transitionend", endAction);
            } else {
                this._animating = false;
            }

            this._fullscreenImage.style.opacity = "0";
            this._fullscreenBackdrop.style.opacity = "0";
            this._fullscreenText.style.opacity = "0";
            this._fullscreenCloseButton.style.opacity = "0";
            this._image.style.opacity = "1";
            this._altText.style.opacity = "1";
        }
    }

    get fullscreen() {
        return this._fullscreen;
    }

    connectedCallback() {
        this._count = counter++;

        this._checkHash();
    }

    _updateDescription() {
        if (this._hasDescription) {
            this._fullscreenText.classList.add("shown");
        } else {
            this._fullscreenText.classList.remove("shown");
        }
    }

    propertySet(property, old, value) {
        if (property === "src") {
            this._image.src = value;
            this._fullscreenImage.src = value;
        } else if (property === "alt") {
            this._setAlt(value);
        } else if (property === "show-alt") {
            if (value) {
                this._altText.classList.add("shown");
            } else {
                this._altText.classList.remove("shown");
            }
            this._setAlt(this.alt, value);
        } else if (property === "no-fullscreen") {
            this._fullscreenEnabled = !value;
        } else if (property === "disable-image-url") {
            this._fullscreenOpacity = value ? "0.7" : "1";
            this._fullscreenBackdrop.style.background = value
                ? "var(--magnon-black)"
                : "var(--magnon-black-blue)";
        }
    }

    _setAlt(alt, altTextEnabled = this.showAlt) {
        if (altTextEnabled) {
            this._image.alt = "";
            this._fullscreenImage.alt = "";
            this._altText.textContent = alt;
        } else {
            this._image.alt = alt;
            this._fullscreenImage.alt = alt;
            this._altText.textContent = "";
        }
    }

    _updateImageSize() {
        const setClass = (el, name, present) => {
            if (present) el.classList.add(name);
            else el.classList.remove(name);
        };

        setClass(this._fullscreenContainer, "cramped", false);

        const vertical = window.innerWidth / window.innerHeight < 1;
        const cramped = !vertical && this.textContent.trim() !== "" && window.innerWidth < 1200;

        setClass(this._fullscreenContainer, "vertical", vertical);
        setClass(this._fullscreenContainer, "cramped", cramped);

        const textStyle = window.getComputedStyle(this._fullscreenText);
        const textWidth = textStyle.display !== "none" && !vertical
            ? (this._fullscreenText.offsetWidth +
            parseFloat(textStyle.marginLeft) + parseFloat(textStyle.marginRight))
            : 0;

        const imageSpaceRatio = (window.innerWidth - textWidth) / window.innerHeight;
        const imageRatio = this._image.naturalWidth / this._image.naturalHeight;

        setClass(this._fullscreenImage, "tall", imageSpaceRatio > imageRatio);

        this._fullscreenContainer.offsetWidth;
    }

    _checkHash() {
        if (this._prevHash && this._prevHash === this._hash) {
            this.fullscreen = false;
        } else if (location.hash === this._hash) {
            this.fullscreen = true;
        }

        this._directlyLinked =
            typeof this._prevHash === "undefined" &&
            location.hash === this._hash;
        this._prevHash = location.hash;
    }
}

MagnonImage.init();
<commit_msg>Revert 4782538<commit_after>import MagnonElement from "../../src/magnon-element.js";

import html from "./image.content.js";
import css from "./image.style.js";

import "../magnon-styles/magnon-styles.js";
import "../magnon-icon-button/magnon-icon-button.js";

let counter = 0;

export class MagnonImage extends MagnonElement {
    constructor() {
        super({ content: html + css });

        this._fullscreenEnabled = true;
    }

    static get elementName() {
        return "magnon-image";
    }

    static get propertyAttributes() {
        return {
            bool: ["show-alt", "no-fullscreen", "disable-image-url"],
            string: ["src", "alt"]
        };
    }

    contentReady() {
        this._image = this.root.querySelector("#main-image");
        this._altText = this.root.querySelector("#alt-text");

        this._fullscreenContainer = this.root.querySelector("#fullscreen-container");
        this._fullscreenBackdrop = this.root.querySelector("#fullscreen-backdrop");
        this._fullscreenImage = this.root.querySelector("#fullscreen-image");
        this._fullscreenText = this.root.querySelector("#fullscreen-text");
        this._fullscreenCloseButton = this.root.querySelector(".close-button");

        this._fullscreenOpacity = "1";

        this._image.addEventListener("load", () => this._updateImageSize());
        this._image.addEventListener("click", () => {
            if (!this.disableImageUrl && location.hash.startsWith("#mimg-")) return;

            if (!this._animating && this._fullscreenEnabled) {
                if (this.disableImageUrl) {
                    this.fullscreen = true;
                } else {
                    location.hash = this._hash;
                }
            }
        });
        const close = () => {
            if (this._animating) return;

            if (this.disableImageUrl) {
                this.fullscreen = false;
            } else {
                const current = location.href.match(/([^#]*)/)[0];

                if (!this._directlyLinked) {
                    history.back();
                } else {
                    history.replaceState(null, null, current);
                }

                this._checkHash();
            }
        };
        this._fullscreenBackdrop.addEventListener("click", close);
        this._fullscreenCloseButton.addEventListener("click", close);

        window.addEventListener("resize", () => this._updateImageSize());
        window.addEventListener("hashchange", () => this._checkHash());

        this.fullscreen = false;
    }

    get _hasDescription() {
        return this.textContent.trim().length > 0;
    }

    get _hash() {
        return `#mimg-${this._count}`;
    }

    set fullscreen(value) {
        if (value && !this._fullscreenEnabled) return;

        if (this._animating) return;

        this._animating = true;

        this.style.transform = "none";

        this._updateDescription();
        this._updateImageSize();

        if (value) {
            // Disable scroll
            document.body.style.overflow = "hidden";

            // The rest
            this._fullscreenContainer.style.pointerEvents = "all";

            this._fullscreenImage.style.opacity = "1";
            this._fullscreenBackdrop.style.opacity = this._fullscreenOpacity;

            this._image.style.transition = "none";
            this._image.style.opacity = "0";

            this._altText.style.opacity = "0";

            const startBox = this._image.getBoundingClientRect();
            const startBorderRadius = window.getComputedStyle(this._image).getPropertyValue("--magnon-image-border-radius");
            const endBox = this._fullscreenImage.getBoundingClientRect();

            this._fullscreenImage.style.transition = "none";

            this._fullscreenImage.style.transform = `
                translate(${startBox.left - endBox.left}px, ${startBox.top - endBox.top}px)
                scale(${startBox.width / endBox.width}, ${startBox.height / endBox.height})
            `;

            this._fullscreenImage.style.borderRadius = startBorderRadius;

            setTimeout(() => {
                this._fullscreenImage.style.transition = "";

                this._fullscreenImage.style.transform = `
                    translate(0px, 0px)
                    scale(1, 1)
                `;

                this._fullscreenImage.style.borderRadius = "0";

                this._fullscreenText.style.opacity = "1";
                this._fullscreenCloseButton.style.opacity = "1";

                const endAction = () => {
                    this._fullscreenImage.removeAttribute("style");
                    this._fullscreenImage.removeEventListener("transitionend", endAction);

                    this._image.style.transition = "";

                    this._animating = false;
                };
                this._fullscreenImage.addEventListener("transitionend", endAction);
            }, 100);
        } else {
            // Enable scroll
            document.body.style.overflow = "auto";

            // The rest
            const endAction = () => {
                this.style.transform = "";

                this._fullscreenContainer.style.pointerEvents = "none";
                this._fullscreenBackdrop.removeEventListener("transitionend", endAction);

                this._animating = false;
            };

            if (this._fullscreenBackdrop.style.opacity !== "") {
                this._fullscreenBackdrop.addEventListener("transitionend", endAction);
            } else {
                this._animating = false;
            }

            this._fullscreenImage.style.opacity = "0";
            this._fullscreenBackdrop.style.opacity = "0";
            this._fullscreenText.style.opacity = "0";
            this._fullscreenCloseButton.style.opacity = "0";
            this._image.style.opacity = "1";
            this._altText.style.opacity = "1";
        }
    }

    get fullscreen() {
        return this._fullscreen;
    }

    connectedCallback() {
        this._count = counter++;

        this._checkHash();
    }

    _updateDescription() {
        if (this._hasDescription) {
            this._fullscreenText.classList.add("shown");
        } else {
            this._fullscreenText.classList.remove("shown");
        }
    }

    propertySet(property, old, value) {
        if (property === "src") {
            this._image.src = value;
            this._fullscreenImage.src = value;
        } else if (property === "alt") {
            this._setAlt(value);
        } else if (property === "show-alt") {
            if (value) {
                this._altText.classList.add("shown");
            } else {
                this._altText.classList.remove("shown");
            }
            this._setAlt(this.alt, value);
        } else if (property === "no-fullscreen") {
            this._fullscreenEnabled = !value;
        } else if (property === "disable-image-url") {
            this._fullscreenOpacity = value ? "0.7" : "1";
            this._fullscreenBackdrop.style.background = value
                ? "var(--magnon-black)"
                : "var(--magnon-black-blue)";
        }
    }

    _setAlt(alt, altTextEnabled = this.showAlt) {
        if (altTextEnabled) {
            this._image.alt = "";
            this._fullscreenImage.alt = "";
            this._altText.textContent = alt;
        } else {
            this._image.alt = alt;
            this._fullscreenImage.alt = alt;
            this._altText.textContent = "";
        }
    }

    _updateImageSize() {
        const setClass = (el, name, present) => {
            if (present) el.classList.add(name);
            else el.classList.remove(name);
        };

        setClass(this._fullscreenContainer, "cramped", false);

        const vertical = window.innerWidth / window.innerHeight < 1;
        const cramped = !vertical && this.textContent.trim() !== "" && window.innerWidth < 1200;

        setClass(this._fullscreenContainer, "vertical", vertical);
        setClass(this._fullscreenContainer, "cramped", cramped);

        const textStyle = window.getComputedStyle(this._fullscreenText);
        const textWidth = textStyle.display !== "none" && !vertical
            ? (this._fullscreenText.offsetWidth +
            parseFloat(textStyle.marginLeft) + parseFloat(textStyle.marginRight))
            : 0;

        const imageSpaceRatio = (window.innerWidth - textWidth) / window.innerHeight;
        const imageRatio = this._image.naturalWidth / this._image.naturalHeight;

        setClass(this._fullscreenImage, "tall", imageSpaceRatio > imageRatio);

        this._fullscreenContainer.offsetWidth;
    }

    _checkHash() {
        if (this._prevHash && this._prevHash === this._hash) {
            this.fullscreen = false;
        } else if (location.hash === this._hash) {
            this.fullscreen = true;
        }

        this._directlyLinked =
            typeof this._prevHash === "undefined" &&
            location.hash === this._hash;
        this._prevHash = location.hash;
    }
}

MagnonImage.init();
<|endoftext|>


<commit_before>'use strict';

var stream = require('stream');
var util = require('util');

/**
 * Node v0.10+ uses native Transform.
 * Need a polyfill for older versions.
 *
 * @type {Function}
 */

var Transform = stream.Transform || require('readable-stream').Transform;

/**
 * Exit constructor.
 *
 * @param {Object} options
 */

function Exit(options) {
  Transform.call(this, options);
}

/**
 * Inherit from `Transform`.
 */

util.inherits(Exit, Transform);

var exitProto = Exit.prototype;

exitProto._transform = function (c, e, cb) { cb(); };
exitProto._flush = function (cb) {
  cb();
  process.exit(0);
};

module.exports = function () {
  return new Exit({ objectMode: true });
};
<commit_msg>comments and minor code improvements<commit_after>'use strict';

var stream = require('stream');
var util = require('util');

/**
 * Node v0.10+ uses native `Transform`. For older versions, use a polyfill.
 *
 * @type {Function}
 */

var Transform = stream.Transform || require('readable-stream').Transform;

/**
 * `Exit` constructor.
 *
 * @param {Object} options
 */

function Exit(options) {
  if (!(this instanceof Exit)) return new Exit(options);
  Transform.call(this, options);
}

/**
 * Inherit from `Transform`.
 */

util.inherits(Exit, Transform);

/** @type {Object} */
var exitProto = Exit.prototype;

/**
 * Override required methods.
 */

exitProto._transform = function (c, e, cb) { cb(); };

exitProto._flush = function (cb) {
  cb();
  process.exit(0);
};

/**
 * Exports as a gulp plugin.
 */

module.exports = function () {
  return new Exit({ objectMode: true });
};
<|endoftext|>


<commit_before>
(function() {
	'use strict';

	window.Code = window.Code || {};

	window.Code.ModalDialog = function(component) {

		const MODAL_TOGGLE_ATTR 				= 'data-modal-toggle';

		const modalToggle 							= Array.prototype.slice.call(document.querySelectorAll(`[${MODAL_TOGGLE_ATTR}]`));
		const focusableElements 				= Array.prototype.slice.call(component.querySelectorAll('a[href], area[href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), button:not([disabled]), [tabindex="0"]'));

		let previousFocusedElement 			= null;
		let firstFocusableEl 						= focusableElements[0];
		let lastFocusableEl 						= focusableElements[focusableElements.length - 1];

		function isModalOpen() {
			return component.classList.contains('modal--open');
		}

		function addModalClass() {
			component.classList.add('modal--open');
		}

		function removeModalClass() {
			component.classList.remove('modal--open');
		}

		function setFocusToElement(element) {
			element.focus();
		}

		function handleBackwardsTab(event) {
			if(document.activeElement === firstFocusableEl) {
				event.preventDefault();
				setFocusToElement(lastFocusableEl);
			}
		}

		function handleForwardTab(event) {
			if(document.activeElement === lastFocusableEl) {
				event.preventDefault();
				setFocusToElement(firstFocusableEl);
			}
		}

		function keyBoardTrapModal(event) {
			if(focusableElements.length === 1) {
				event.preventDefault();
				return;
			}

			event.shiftKey ? handleBackwardsTab(event) : handleForwardTab(event);
		}

		function handleKeyDownEvents(event) {
			const keyCodes = {
				'27': closeModal,
				'9': keyBoardTrapModal
			};

			if(keyCodes.hasOwnProperty(event.keyCode) && isModalOpen()) {
				keyCodes[event.keyCode](event);
			}
		}

		function handleEscapeKeyEvent(event) {
			const keyCodes = {
				'27': closeModal
			};

			if(keyCodes.hasOwnProperty(event.keyCode) && isModalOpen()) {
				keyCodes[event.keyCode](event);
			}
		}

		function showModal(currentTarget) {
			addModalClass();
			setFocusToElement(focusableElements[0]);
			previousFocusedElement = currentTarget;
		}

		function closeModal() {
			removeModalClass();
			setFocusToElement(previousFocusedElement);
		}

		function handleClickEvent(event) {
			event.preventDefault();
			!isModalOpen() ? showModal(event.currentTarget) : closeModal();
		}

		function bindFocusEvents() {
			focusableElements.forEach(element => { element.addEventListener('keydown', handleKeyDownEvents); });
			document.body.addEventListener('keydown', handleEscapeKeyEvent);
		}

		function init() {
			modalToggle.forEach(element => element.addEventListener('click', handleClickEvent));
			bindFocusEvents();
		}

		init();
	};

	// you dont need this bit.
	const elements = Array.prototype.slice.call(document.querySelectorAll(`[data-modal]`));

	elements.forEach(element => { const newModal = new window.Code.ModalDialog(element); });
}());
<commit_msg>refactor: only bind the keydown event of escape on the document when modal is open. Dont want it to be randomly firing for no reason.<commit_after>
(function() {
	'use strict';

	window.Code = window.Code || {};

	window.Code.ModalDialog = function(component) {

		const MODAL_TOGGLE_ATTR 				= 'data-modal-toggle';

		const modalToggle 							= Array.prototype.slice.call(document.querySelectorAll(`[${MODAL_TOGGLE_ATTR}]`));
		const focusableElements 				= Array.prototype.slice.call(component.querySelectorAll('a[href], area[href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), button:not([disabled]), [tabindex="0"]'));

		let previousFocusedElement 			= null;
		let firstFocusableEl 						= focusableElements[0];
		let lastFocusableEl 						= focusableElements[focusableElements.length - 1];

		function isModalOpen() {
			return component.classList.contains('modal--open');
		}

		function addModalClass() {
			component.classList.add('modal--open');
		}

		function removeModalClass() {
			component.classList.remove('modal--open');
		}

		function setFocusToElement(element) {
			element.focus();
		}

		function handleBackwardsTab(event) {
			if(document.activeElement === firstFocusableEl) {
				event.preventDefault();
				setFocusToElement(lastFocusableEl);
			}
		}

		function handleForwardTab(event) {
			if(document.activeElement === lastFocusableEl) {
				event.preventDefault();
				setFocusToElement(firstFocusableEl);
			}
		}

		function keyBoardTrapModal(event) {
			if(focusableElements.length === 1) {
				event.preventDefault();
				return;
			}

			event.shiftKey ? handleBackwardsTab(event) : handleForwardTab(event);
		}

		function handleKeyDownEvents(event) {
			const keyCodes = {
				'27': closeModal,
				'9': keyBoardTrapModal
			};

			if(keyCodes.hasOwnProperty(event.keyCode) && isModalOpen()) {
				keyCodes[event.keyCode](event);
			}
		}

		function handleEscapeKeyEvent(event) {
			const keyCodes = {
				'27': closeModal
			};

			if(keyCodes.hasOwnProperty(event.keyCode) && isModalOpen()) {
				keyCodes[event.keyCode](event);
			}
		}

		function showModal(currentTarget) {
			addModalClass();
			setFocusToElement(focusableElements[0]);
			previousFocusedElement = currentTarget;
			document.body.addEventListener('keydown', handleEscapeKeyEvent);
		}

		function closeModal() {
			removeModalClass();
			setFocusToElement(previousFocusedElement);
			document.body.removeEventListener('keydown', handleEscapeKeyEvent);

		}

		function handleClickEvent(event) {
			event.preventDefault();
			!isModalOpen() ? showModal(event.currentTarget) : closeModal();
		}

		function bindFocusEvents() {
			focusableElements.forEach(element => { element.addEventListener('keydown', handleKeyDownEvents); });
		}

		function init() {
			modalToggle.forEach(element => element.addEventListener('click', handleClickEvent));
			bindFocusEvents();
		}

		init();
	};

	// you dont need this bit.
	const elements = Array.prototype.slice.call(document.querySelectorAll(`[data-modal]`));

	elements.forEach(element => { const newModal = new window.Code.ModalDialog(element); });
}());
<|endoftext|>


<commit_before>require('./app/less/base.less');
require('./app/javascript/app.js');
require('./app/javascript/accounts.js');
require('./app/javascript/navigation.js');
require('./app/javascript/gamesFactory.js');
require('./app/javascript/cryptoFactory.js');
require('./app/javascript/welcome.js');
require('./app/javascript/messages.js');
require('./app/javascript/initializeGame.js');
require('./app/javascript/joinGame.js');
require('./app/javascript/playGame.js');
<commit_msg>Embed gameStatesFactory<commit_after>require('./app/less/base.less');
require('./app/javascript/app.js');
require('./app/javascript/accounts.js');
require('./app/javascript/navigation.js');
require('./app/javascript/gamesFactory.js');
require('./app/javascript/gameStatesFactory.js');
require('./app/javascript/cryptoFactory.js');
require('./app/javascript/welcome.js');
require('./app/javascript/messages.js');
require('./app/javascript/initializeGame.js');
require('./app/javascript/joinGame.js');
require('./app/javascript/playGame.js');
<|endoftext|>