<commit_before>var falafel = require('falafel')
var duplexify = require('duplexify')
var through = require('through2')
var concat = require('concat-stream')
var from = require('from2')
var gdeps = require('glslify-deps')
var gbundle = require('glslify-bundle')
var path = require('path')
var seval = require('static-eval')
var resolve = require('resolve')
var gresolve = require('glsl-resolve')
var extend = require('xtend')

var glslfile0 = path.join(__dirname,'index.js')
var glslfile1 = path.join(__dirname,'index')

module.exports = function (file, opts) {
  if (path.extname(file) == '.json') return through()
  if (!opts) opts = {}
  var posts = []
  var dir = path.dirname(file)
  var glvar = null, mdir = dir
  var evars = {
    __dirname: dir,
    __filename: file,
    require: { resolve: resolve }
  }
  function evaluate (expr) {
    return seval(expr, evars)
  }

  var d = duplexify()
  var out = from(function () {})
  d.setReadable(out)
  d.setWritable(concat({ encoding: 'string' }, function (src) {
    var pending = 1
    try { var fout = falafel(src, { ecmaVersion: 6 }, onnode) }
    catch (err) { return d.emit('error', err) }
    done()
    function onnode (node) {
      if (node.type === 'Identifier' && node.name === 'require'
      && node.parent.type === 'CallExpression'
      && node.parent.arguments[0]
      && node.parent.arguments[0].type === 'Literal'
      && node.parent.arguments[0].value === 'path'
      && node.parent.parent.type === 'VariableDeclarator') {
        evars.path = path
      } else if (node.type === 'Identifier' && node.name === 'require'
      && node.parent.type === 'CallExpression'
      && node.parent.arguments[0]
      && node.parent.arguments[0].type === 'Literal'
      && (/^glslify(?:\/index(?:\.js)?)?/.test(node.parent.arguments[0].value)
      || path.resolve(dir,node.parent.arguments[0].value) === __dirname
      || path.resolve(dir,node.parent.arguments[0].value) === glslfile0
      || path.resolve(dir,node.parent.arguments[0].value) === glslfile1)) {
        var p = node.parent.parent, pp = p.parent
        if (p.type === 'CallExpression' && pp.type === 'CallExpression') {
          // case: require('glslify')(...)
          pending++
          callexpr(p, done)
        } else if (p.type === 'VariableDeclarator') {
          // case: var glvar = require('glslify')
          glvar = p.id.name
        } else if (p.type === 'MemberExpression' && p.property.name === 'file'
        && pp.type === 'CallExpression') {
          // case: require('glslify').file(...)
          pending++
          rcallfile(pp, done)
        } else if (p.type === 'MemberExpression' && p.property.name === 'compile'
        && pp.type === 'CallExpression') {
          // case: require('glslify').compile(...)
          pending++
          rcallcompile(pp, done)
        } else if (p.type === 'TaggedTemplateExpression') {
          // case: require('glslify')`...`
          pending++
          tagexpr(p, done)
        }
      } else if (node.type === 'Identifier' && node.name === glvar
      && node.parent.type === 'CallExpression') {
        // case: glvar(...)
        pending++
        callexpr(node.parent, done)
      } else if (node.type === 'TaggedTemplateExpression'
      && node.tag.name === glvar) {
        // case: glvar`...`
        pending++
        tagexpr(node, done)
      } else if (node.type === 'Identifier' && node.name === glvar
      && node.parent.type === 'MemberExpression'
      && node.parent.property.name === 'file'
      && node.parent.parent.type === 'CallExpression'
      && node.parent.parent.arguments[0]) {
        pending++
        callfile(node.parent.parent, done)
      } else if (node.type === 'Identifier' && node.name === glvar
      && node.parent.type === 'MemberExpression'
      && node.parent.property.name === 'compile'
      && node.parent.parent.type === 'CallExpression'
      && node.parent.parent.arguments[0]) {
        pending++
        callcompile(node.parent.parent, done)
      }
    }
    function tagexpr (node, cb) {
      var q = node.quasi
      var shadersrc = q.quasis.map(function (s) {
        return s.value.raw + '__GLX_PLACEHOLDER__'
      }).join('')
      var d = createDeps({ cwd: mdir })
      d.inline(shadersrc, mdir, function (err, deps) {
        if (err) return d.emit('error', err)
        try { var bsrc = bundle(deps) }
        catch (err) { return d.emit('error', err) }
        node.update(node.tag.source() + '('
          + JSON.stringify(bsrc.split('__GLX_PLACEHOLDER__'))
          + [''].concat(q.expressions.map(function (e) {
            return e.source()
          })).join(',')
          + ')')
        cb()
      })
    }
    function callexpr (p, cb) {
      var marg = evaluate(p.arguments[0])
      var mopts = p.arguments[1] ? evaluate(p.arguments[1]) || {} : {}
      var d = createDeps(extend({ cwd: mdir }, mopts))
      if (/\n/.test(marg)) { // source string
        d.inline(marg, mdir, ondeps)
      } else gresolve(marg, { basedir: mdir }, function (err, res) {
        if (err) d.emit('error', err)
        else d.add(res, ondeps)
      })
      function ondeps (err, deps) {
        if (err) return d.emit('error', err)
        try { var bsrc = bundle(deps) }
        catch (err) { return d.emit('error', err) }
        p.update(p.callee.source()+'(['+JSON.stringify(bsrc)+'])')
        cb()
      }
    }
    function callcompile (p, cb) {
      var mfile = p.arguments[0].value
      var mopts = p.arguments[1] ? evaluate(p.arguments[1]) || {} : {}
      var d = createDeps({ cwd: mdir })
      d.inline(mfile, mdir, ondeps)
      function ondeps (err, deps) {
        if (err) return d.emit('error', err)
        try { var bsrc = bundle(deps) }
        catch (err) { return d.emit('error', err) }
        p.update(glvar + '([' + JSON.stringify(bsrc) + '])')
        cb()
      }
    }
    function callfile (p, cb) {
      var mfile = p.arguments[0].value
      var mopts = p.arguments[1] ? evaluate(p.arguments[1]) || {} : {}
      var d = createDeps({ cwd: mdir })
      gresolve(mfile, { basedir: mdir }, function (err, res) {
        if (err) return d.emit('error', err)
        d.add(res, ondeps)
      })
      function ondeps (err, deps) {
        if (err) return d.emit('error', err)
        try { var bsrc = bundle(deps) }
        catch (err) { return d.emit('error', err) }
        p.update(glvar + '([' + JSON.stringify(bsrc) + '])')
        cb()
      }
    }
    function rcallfile (p, cb) {
      var mfile = evaluate(p.arguments[0])
      var mopts = p.arguments[1] ? evaluate(p.arguments[1]) || {} : {}
      var d = createDeps({ cwd: mdir })
      gresolve(mfile, { basedir: mdir }, function (err, res) {
        if (err) return d.emit('error', err)
        d.add(res, ondeps)
      })
      function ondeps (err, deps) {
        if (err) return d.emit('error', err)
        try { var bsrc = bundle(deps) }
        catch (err) { return d.emit('error', err) }
        p.update(p.callee.object.source()+'(['+JSON.stringify(bsrc)+'])')
        cb()
      }
    }
    function rcallcompile (p, cb) {
      var marg = evaluate(p.arguments[0])
      var mopts = p.arguments[1] ? evaluate(p.arguments[1]) || {} : {}
      var d = createDeps({ cwd: mdir })
      d.inline(marg, mdir, ondeps)
      function ondeps (err, deps) {
        if (err) return d.emit('error', err)
        try { var bsrc = bundle(deps) }
        catch (err) { return d.emit('error', err) }
        p.update(p.callee.object.source()+'(['+JSON.stringify(bsrc)+'])')
        cb()
      }
    }
    function done () {
      if (--pending === 0) {
        out.push(fout.toString())
        out.push(null)
      }
    }
  }))
  return d

  function createDeps (opts) {
    var depper = gdeps(opts)
    var transforms = opts.transform || []
    transforms = Array.isArray(transforms) ? transforms : [transforms]
    transforms.forEach(function(transform) {
      transform = Array.isArray(transform) ? transform : [transform]
      var name = transform[0]
      var opts = transform[1] || {}
      if (opts.post) {
        posts.push({ name: name, opts: opts })
      } else {
        depper.transform(name, opts)
      }
    })
    return depper
  }
  function bundle (deps) {
    var source = gbundle(deps)
    posts.forEach(function (tr) {
      var target = nodeResolve.sync(tr.name, {
        basedir: base
      })
      var transform = require(target)
      var src = transform(null, source, { post: true })
      if (src) source = src
    })
    return source
  }
}
<commit_msg>emit file and error events in the transform<commit_after>var falafel = require('falafel')
var duplexify = require('duplexify')
var through = require('through2')
var concat = require('concat-stream')
var from = require('from2')
var gdeps = require('glslify-deps')
var gbundle = require('glslify-bundle')
var path = require('path')
var seval = require('static-eval')
var resolve = require('resolve')
var gresolve = require('glsl-resolve')
var extend = require('xtend')

var glslfile0 = path.join(__dirname,'index.js')
var glslfile1 = path.join(__dirname,'index')

module.exports = function (file, opts) {
  if (path.extname(file) == '.json') return through()
  if (!opts) opts = {}
  var posts = []
  var dir = path.dirname(file)
  var glvar = null, mdir = dir
  var evars = {
    __dirname: dir,
    __filename: file,
    require: { resolve: resolve }
  }
  function evaluate (expr) {
    return seval(expr, evars)
  }

  var d = duplexify()
  var out = from(function () {})
  d.setReadable(out)
  d.setWritable(concat({ encoding: 'string' }, function (src) {
    var pending = 1
    try { var fout = falafel(src, { ecmaVersion: 6 }, onnode) }
    catch (err) { return d.emit('error', err) }
    done()
    function onnode (node) {
      if (node.type === 'Identifier' && node.name === 'require'
      && node.parent.type === 'CallExpression'
      && node.parent.arguments[0]
      && node.parent.arguments[0].type === 'Literal'
      && node.parent.arguments[0].value === 'path'
      && node.parent.parent.type === 'VariableDeclarator') {
        evars.path = path
      } else if (node.type === 'Identifier' && node.name === 'require'
      && node.parent.type === 'CallExpression'
      && node.parent.arguments[0]
      && node.parent.arguments[0].type === 'Literal'
      && (/^glslify(?:\/index(?:\.js)?)?/.test(node.parent.arguments[0].value)
      || path.resolve(dir,node.parent.arguments[0].value) === __dirname
      || path.resolve(dir,node.parent.arguments[0].value) === glslfile0
      || path.resolve(dir,node.parent.arguments[0].value) === glslfile1)) {
        var p = node.parent.parent, pp = p.parent
        if (p.type === 'CallExpression' && pp.type === 'CallExpression') {
          // case: require('glslify')(...)
          pending++
          callexpr(p, done)
        } else if (p.type === 'VariableDeclarator') {
          // case: var glvar = require('glslify')
          glvar = p.id.name
        } else if (p.type === 'MemberExpression' && p.property.name === 'file'
        && pp.type === 'CallExpression') {
          // case: require('glslify').file(...)
          pending++
          rcallfile(pp, done)
        } else if (p.type === 'MemberExpression' && p.property.name === 'compile'
        && pp.type === 'CallExpression') {
          // case: require('glslify').compile(...)
          pending++
          rcallcompile(pp, done)
        } else if (p.type === 'TaggedTemplateExpression') {
          // case: require('glslify')`...`
          pending++
          tagexpr(p, done)
        }
      } else if (node.type === 'Identifier' && node.name === glvar
      && node.parent.type === 'CallExpression') {
        // case: glvar(...)
        pending++
        callexpr(node.parent, done)
      } else if (node.type === 'TaggedTemplateExpression'
      && node.tag.name === glvar) {
        // case: glvar`...`
        pending++
        tagexpr(node, done)
      } else if (node.type === 'Identifier' && node.name === glvar
      && node.parent.type === 'MemberExpression'
      && node.parent.property.name === 'file'
      && node.parent.parent.type === 'CallExpression'
      && node.parent.parent.arguments[0]) {
        pending++
        callfile(node.parent.parent, done)
      } else if (node.type === 'Identifier' && node.name === glvar
      && node.parent.type === 'MemberExpression'
      && node.parent.property.name === 'compile'
      && node.parent.parent.type === 'CallExpression'
      && node.parent.parent.arguments[0]) {
        pending++
        callcompile(node.parent.parent, done)
      }
    }
    function tagexpr (node, cb) {
      var q = node.quasi
      var shadersrc = q.quasis.map(function (s) {
        return s.value.raw + '__GLX_PLACEHOLDER__'
      }).join('')
      var d = createDeps({ cwd: mdir })
      d.inline(shadersrc, mdir, function (err, deps) {
        if (err) return d.emit('error', err)
        try { var bsrc = bundle(deps) }
        catch (err) { return d.emit('error', err) }
        node.update(node.tag.source() + '('
          + JSON.stringify(bsrc.split('__GLX_PLACEHOLDER__'))
          + [''].concat(q.expressions.map(function (e) {
            return e.source()
          })).join(',')
          + ')')
        cb()
      })
    }
    function callexpr (p, cb) {
      var marg = evaluate(p.arguments[0])
      var mopts = p.arguments[1] ? evaluate(p.arguments[1]) || {} : {}
      var d = createDeps(extend({ cwd: mdir }, mopts))
      if (/\n/.test(marg)) { // source string
        d.inline(marg, mdir, ondeps)
      } else gresolve(marg, { basedir: mdir }, function (err, res) {
        if (err) d.emit('error', err)
        else d.add(res, ondeps)
      })
      function ondeps (err, deps) {
        if (err) return d.emit('error', err)
        try { var bsrc = bundle(deps) }
        catch (err) { return d.emit('error', err) }
        p.update(p.callee.source()+'(['+JSON.stringify(bsrc)+'])')
        cb()
      }
    }
    function callcompile (p, cb) {
      var mfile = p.arguments[0].value
      var mopts = p.arguments[1] ? evaluate(p.arguments[1]) || {} : {}
      var d = createDeps({ cwd: mdir })
      d.inline(mfile, mdir, ondeps)
      function ondeps (err, deps) {
        if (err) return d.emit('error', err)
        try { var bsrc = bundle(deps) }
        catch (err) { return d.emit('error', err) }
        p.update(glvar + '([' + JSON.stringify(bsrc) + '])')
        cb()
      }
    }
    function callfile (p, cb) {
      var mfile = p.arguments[0].value
      var mopts = p.arguments[1] ? evaluate(p.arguments[1]) || {} : {}
      var d = createDeps({ cwd: mdir })
      gresolve(mfile, { basedir: mdir }, function (err, res) {
        if (err) return d.emit('error', err)
        d.add(res, ondeps)
      })
      function ondeps (err, deps) {
        if (err) return d.emit('error', err)
        try { var bsrc = bundle(deps) }
        catch (err) { return d.emit('error', err) }
        p.update(glvar + '([' + JSON.stringify(bsrc) + '])')
        cb()
      }
    }
    function rcallfile (p, cb) {
      var mfile = evaluate(p.arguments[0])
      var mopts = p.arguments[1] ? evaluate(p.arguments[1]) || {} : {}
      var d = createDeps({ cwd: mdir })
      gresolve(mfile, { basedir: mdir }, function (err, res) {
        if (err) return d.emit('error', err)
        d.add(res, ondeps)
      })
      function ondeps (err, deps) {
        if (err) return d.emit('error', err)
        try { var bsrc = bundle(deps) }
        catch (err) { return d.emit('error', err) }
        p.update(p.callee.object.source()+'(['+JSON.stringify(bsrc)+'])')
        cb()
      }
    }
    function rcallcompile (p, cb) {
      var marg = evaluate(p.arguments[0])
      var mopts = p.arguments[1] ? evaluate(p.arguments[1]) || {} : {}
      var d = createDeps({ cwd: mdir })
      d.inline(marg, mdir, ondeps)
      function ondeps (err, deps) {
        if (err) return d.emit('error', err)
        try { var bsrc = bundle(deps) }
        catch (err) { return d.emit('error', err) }
        p.update(p.callee.object.source()+'(['+JSON.stringify(bsrc)+'])')
        cb()
      }
    }
    function done () {
      if (--pending === 0) {
        out.push(fout.toString())
        out.push(null)
      }
    }
  }))
  return d

  function createDeps (opts) {
    var depper = gdeps(opts)
    depper.on('error', function (err) { d.emit('error', err) })
    depper.on('file', function (file) { d.emit('file', file) })
    var transforms = opts.transform || []
    transforms = Array.isArray(transforms) ? transforms : [transforms]
    transforms.forEach(function(transform) {
      transform = Array.isArray(transform) ? transform : [transform]
      var name = transform[0]
      var opts = transform[1] || {}
      if (opts.post) {
        posts.push({ name: name, opts: opts })
      } else {
        depper.transform(name, opts)
      }
    })
    return depper
  }
  function bundle (deps) {
    var source = gbundle(deps)
    posts.forEach(function (tr) {
      var target = nodeResolve.sync(tr.name, {
        basedir: base
      })
      var transform = require(target)
      var src = transform(null, source, { post: true })
      if (src) source = src
    })
    return source
  }
}
<|endoftext|>


<commit_before>var gracenode = require('../../');
var logger = gracenode.log.create('server-request');
var queryDataHandler = require('./queryData');
var headers = require('./headers');
var Cookies = require('cookies');
var queryString = require('querystring');
var url = require('url');
var multiparty = require('multiparty');

module.exports = Request;

function Request(request, response, params) {
	// private
	this._props = {};
	this._response = response;
	this._request = request;
	this._method = request.method;

	// public
	this.url = request.url;
	this.parameters = params;
	this.headers = headers.create(request.headers);
}

Request.prototype.setup = function (cb) {
	var that = this;
	this.extractQueries(this._request, function (error, dataHandler) {
		if (error) {
			return cb(error);
		}
		that._dataHandler = dataHandler;

		logger.info('request:', that._method, that.url, that._dataHandler.getAll());

		cb(null, that);
	});
};

Request.prototype.cookies = function () {
	return new Cookies(this._request, this._response);
};

Request.prototype.getMethod = function () {
	return this._method;
};

Request.prototype.set = function (name, value) {
	this._props[name] = value;
};

Request.prototype.get = function (name) {
	if (this._props[name] === undefined) {
		return null;
	}
	return gracenode.lib.cloneObj(this._props[name]);
};

Request.prototype.data = function (key) {
	return this._dataHandler.get(key);
};

Request.prototype.dataAll = function () {
	return this._dataHandler.getAll();
};

Request.prototype.extractQueries = function (req, cb) {

	if (req.headers['content-type'] && req.headers['content-type'].indexOf('multipart') >= 0) {

		var form = new multiparty.Form();

		form.parse(req, function (error, fields, files) {

			if (error) {
				return cb(error);
			}

			var obj   = fields;
			obj.files = [];

			for (var f in files) {

				obj.files.push(files[f][0]);

			}

			cb(null, queryDataHandler.createGetter(obj));

		});

	} else {

		switch (req.method) {
			case 'POST':
				var body = '';
				req.on('data', function (data) {
					body += data;
				});
				req.on('end', function () {
					var post = readRequestBody(req.url, req.headers, body);
					cb(null, queryDataHandler.createGetter(post));
				});
				req.on('error', function (error) {
					cb(error);
				});
				break;
			case 'PUT':
				var putBody = '';
				req.on('data', function (data) {
					putBody += data;
				});
				req.on('end', function () {
					var put = readRequestBody(req.url, req.headers, putBody);
					cb(null, queryDataHandler.createGetter(put));
				});
				req.on('error', function (error) {
					cb(error);
				});
				break;
			case 'DELETE':
				var deleteBody = '';
				req.on('data', function (data) {
					deleteBody += data;
				});
				req.on('end', function () {
					var del = queryString.parse(deleteBody);
					cb(null, queryDataHandler.createGetter(del));
				});
				req.on('error', function (error) {
					cb(error);
				});
				break;
			case 'GET':
				var parsed = url.parse(req.url, true);
				var getBody = '';
				req.on('data', function (data) {
					getBody += data;
				});
				req.on('end', function () {
					var get = queryString.parse(getBody);
					for (var key in parsed.query) {
						get[key] = parsed.query[key];
					}
					cb(null, queryDataHandler.createGetter(get));
				});
				break;
			default:
				logger.warning('only POST, PUT, DELETE, and GET are supported');
				cb(null, queryDataHandler.createGetter({}));
				break;
		}

	}

};

function readRequestBody(url, headers, body) {
	var reqBody;

	if (headers['content-type'] === 'application/json') {

		try {
			reqBody = JSON.parse(body);
		} catch (e) {
			logger.error('Invalid JSON in request: (url:' + url + ')', body, e);
			reqBody = {};
		}

	} else {
		reqBody = queryString.parse(body);
	}

	return reqBody;
}
<commit_msg>gracenode path fixed<commit_after>var gracenode = require('../gracenode');
var logger = gracenode.log.create('server-request');
var queryDataHandler = require('./queryData');
var headers = require('./headers');
var Cookies = require('cookies');
var queryString = require('querystring');
var url = require('url');
var multiparty = require('multiparty');

module.exports = Request;

function Request(request, response, params) {
	// private
	this._props = {};
	this._response = response;
	this._request = request;
	this._method = request.method;

	// public
	this.url = request.url;
	this.parameters = params;
	this.headers = headers.create(request.headers);
}

Request.prototype.setup = function (cb) {
	var that = this;
	this.extractQueries(this._request, function (error, dataHandler) {
		if (error) {
			return cb(error);
		}
		that._dataHandler = dataHandler;

		logger.info('request:', that._method, that.url, that._dataHandler.getAll());

		cb(null, that);
	});
};

Request.prototype.cookies = function () {
	return new Cookies(this._request, this._response);
};

Request.prototype.getMethod = function () {
	return this._method;
};

Request.prototype.set = function (name, value) {
	this._props[name] = value;
};

Request.prototype.get = function (name) {
	if (this._props[name] === undefined) {
		return null;
	}
	return gracenode.lib.cloneObj(this._props[name]);
};

Request.prototype.data = function (key) {
	return this._dataHandler.get(key);
};

Request.prototype.dataAll = function () {
	return this._dataHandler.getAll();
};

Request.prototype.extractQueries = function (req, cb) {

	if (req.headers['content-type'] && req.headers['content-type'].indexOf('multipart') >= 0) {

		var form = new multiparty.Form();

		form.parse(req, function (error, fields, files) {

			if (error) {
				return cb(error);
			}

			var obj   = fields;
			obj.files = [];

			for (var f in files) {

				obj.files.push(files[f][0]);

			}

			cb(null, queryDataHandler.createGetter(obj));

		});

	} else {

		switch (req.method) {
			case 'POST':
				var body = '';
				req.on('data', function (data) {
					body += data;
				});
				req.on('end', function () {
					var post = readRequestBody(req.url, req.headers, body);
					cb(null, queryDataHandler.createGetter(post));
				});
				req.on('error', function (error) {
					cb(error);
				});
				break;
			case 'PUT':
				var putBody = '';
				req.on('data', function (data) {
					putBody += data;
				});
				req.on('end', function () {
					var put = readRequestBody(req.url, req.headers, putBody);
					cb(null, queryDataHandler.createGetter(put));
				});
				req.on('error', function (error) {
					cb(error);
				});
				break;
			case 'DELETE':
				var deleteBody = '';
				req.on('data', function (data) {
					deleteBody += data;
				});
				req.on('end', function () {
					var del = queryString.parse(deleteBody);
					cb(null, queryDataHandler.createGetter(del));
				});
				req.on('error', function (error) {
					cb(error);
				});
				break;
			case 'GET':
				var parsed = url.parse(req.url, true);
				var getBody = '';
				req.on('data', function (data) {
					getBody += data;
				});
				req.on('end', function () {
					var get = queryString.parse(getBody);
					for (var key in parsed.query) {
						get[key] = parsed.query[key];
					}
					cb(null, queryDataHandler.createGetter(get));
				});
				break;
			default:
				logger.warning('only POST, PUT, DELETE, and GET are supported');
				cb(null, queryDataHandler.createGetter({}));
				break;
		}

	}

};

function readRequestBody(url, headers, body) {
	var reqBody;

	if (headers['content-type'] === 'application/json') {

		try {
			reqBody = JSON.parse(body);
		} catch (e) {
			logger.error('Invalid JSON in request: (url:' + url + ')', body, e);
			reqBody = {};
		}

	} else {
		reqBody = queryString.parse(body);
	}

	return reqBody;
}
<|endoftext|>


<commit_before>/**
 * power-assert.js - Empower your assertions
 *
 * https://github.com/twada/power-assert.js
 *
 * Copyright (c) 2013 Takuto Wada
 * Licensed under the MIT license.
 *   https://raw.github.com/twada/power-assert.js/master/MIT-LICENSE.txt
 */
var esprima = require('esprima'),
    escodegen = require('escodegen'),
    powerAssertVariableName = "_pa_",
    powerAssertModuleName = "power-assert";

// Executes visitor on the object and its children (recursively).
var traverse = function traverse(object, visitor) {
    var key, child;

    visitor.call(null, object);
    for (key in object) {
        if (object.hasOwnProperty(key)) {
            child = object[key];
            if (typeof child === 'object' && child !== null) {
                traverse(child, visitor);
            }
        }
    }
};

var isSupported = function () {
    var supported = [
        'Identifier',
        'UnaryExpression',
        'BinaryExpression',
        'MemberExpression',
        'CallExpression',
        'LogicalExpression'
    ];
//// TODO
// 'ArrayExpression',
// 'AssignmentExpression',
// 'CallExpression',
// 'ConditionalExpression',
// 'FunctionExpression',
// 'NewExpression',
// 'ObjectExpression',
// 'RegularExpression',
// 'SequenceExpression',
// 'ThisExpression',
// 'UpdateExpression',

//// DONE
// 'BinaryExpression',
// 'MemberExpression',
// 'LogicalExpression',
// 'UnaryExpression',

    return function (node) {
        return supported.some(function (kind) { return node.type === kind; });
    };
};

var capture = function (kind, target, column) {
    return {
        "type": "CallExpression",
        "callee": {
            "type": "MemberExpression",
            "computed": false,
            "object": {
                "type": "Identifier",
                "name": powerAssertVariableName
            },
            "property": {
                "type": "Identifier",
                "name": kind
            }
        },
        "arguments": [
            target,
            {
                "type": "Literal",
                "value": column.start
            },
            {
                "type": "Literal",
                "value": column.end
            }
        ]
    };
};

// enclose in _pa_.ident
var captureIdent = function (target, column) {
    return capture('ident', target, column);
};

// enclose in _pa_.funcall
var captureFuncall = function (target, column) {
    return capture('funcall', target, column);
};

var toColumn = function (node) {
    return {
        start: node.loc.start.column,
        end: node.loc.end.column
    };
};

var captureRecursively = function (node) {
    switch (node.type) {
    case 'Identifier':
        return captureIdent(node, toColumn(node));
    case 'MemberExpression': // ex: foo.bar.baz
        node.object = captureRecursively(node.object);
        return captureIdent(node, toColumn(node.property));
    case 'CallExpression':
        node.arguments = node.arguments.map(function (arg) {
            return captureRecursively(arg);
        });
        return captureFuncall(node, toColumn(node));
        // node.callee = captureRecursively(node.callee);
        // return node;
    case 'UnaryExpression':
        if (node.operator === 'typeof') {
            // 'typeof' operator is not supported
            return node;
        }
        node.argument = captureRecursively(node.argument);
        return node;
    case 'BinaryExpression':
        node.left = captureRecursively(node.left);
        node.right = captureRecursively(node.right);
        return node;
    case 'LogicalExpression':
        node.left = captureRecursively(node.left);
        node.right = captureRecursively(node.right);
        return node;
    default:
        return node;
    }
};

// enclose assert expression in _pa_.expr
var captureFirstArgument = function (firstArgument, line, lineNumber) {
    return {
        "type": "CallExpression",
        "callee": {
            "type": "MemberExpression",
            "computed": false,
            "object": {
                "type": "Identifier",
                "name": powerAssertVariableName
            },
            "property": {
                "type": "Identifier",
                "name": "expr"
            }
        },
        "arguments": [
            firstArgument,
            {
                "type": "Literal",
                "value": line
            },
            {
                "type": "Literal",
                "value": lineNumber
            }
        ]
    };
};

var instrument = function (expression, line, lineNumber) {
    var firstArgument = expression.arguments[0];
    if (!isSupported(firstArgument)) {
        return;
    }
    firstArgument = captureRecursively(firstArgument);
    expression.arguments[0] = captureFirstArgument(firstArgument, line, lineNumber);
};

var isAssertOkCall = function (callee) {
    if (callee.type !== 'MemberExpression' || callee.computed !== false) {
        return false;
    }
    var ob = callee.object,
        prop = callee.property;
    return ((ob.type === 'Identifier' && ob.name === 'assert') && (prop.type === 'Identifier' && prop.name === 'ok'));
};

var isAssertCall = function (callee) {
    return (callee.type === 'Identifier' && callee.name === 'assert');
};

var modifyTree = function (syntax, lines) {
    traverse(syntax, function (node) {
        if (typeof node.type === 'undefined') {
            return;
        }
        if (node.type !== 'ExpressionStatement') {
            return;
        }
        var expression = node.expression;
        if (expression.type !== 'CallExpression') {
            return;
        }
        var callee = expression.callee;
        if (!(isAssertCall(callee) || isAssertOkCall(callee))) {
            return;
        }
        var lineNumber = node.loc.start.line;
        var line = lines[lineNumber - 1];
        instrument(expression, line, lineNumber);
    });
};

var powerAssertVariableDeclaration = {
    "type": "VariableDeclaration",
    "declarations": [
        {
            "type": "VariableDeclarator",
            "id": {
                "type": "Identifier",
                "name": powerAssertVariableName
            },
            "init": {
                "type": "CallExpression",
                "callee": {
                    "type": "Identifier",
                    "name": "require"
                },
                "arguments": [
                    {
                        "type": "Literal",
                        "value": powerAssertModuleName
                    }
                ]
            }
        }
    ],
    "kind": "var"
};

var empower = function empower(source, options) {
    options = options || {};
    var lines = source.split("\n"),
        tree = esprima.parse(source, {tolerant: true, loc: true});
    modifyTree(tree, lines, options);

    if (options['module'] === 'commonjs') {
        // insert "var _pa_ = require('power-assert');"
        tree.body.unshift(powerAssertVariableDeclaration);
    }

    console.log(escodegen.generate(tree));
};

empower.modifyTree = modifyTree;
empower.instrument = instrument;

/*global exports:false*/
if (typeof exports !== 'undefined') {
    module.exports = empower;
}
<commit_msg>update todo<commit_after>/**
 * power-assert.js - Empower your assertions
 *
 * https://github.com/twada/power-assert.js
 *
 * Copyright (c) 2013 Takuto Wada
 * Licensed under the MIT license.
 *   https://raw.github.com/twada/power-assert.js/master/MIT-LICENSE.txt
 */
var esprima = require('esprima'),
    escodegen = require('escodegen'),
    powerAssertVariableName = "_pa_",
    powerAssertModuleName = "power-assert";

// Executes visitor on the object and its children (recursively).
var traverse = function traverse(object, visitor) {
    var key, child;

    visitor.call(null, object);
    for (key in object) {
        if (object.hasOwnProperty(key)) {
            child = object[key];
            if (typeof child === 'object' && child !== null) {
                traverse(child, visitor);
            }
        }
    }
};

var isSupported = function () {
    var supported = [
        'Identifier',
        'UnaryExpression',
        'BinaryExpression',
        'MemberExpression',
        'CallExpression',
        'LogicalExpression'
    ];
//// TODO
// 'ArrayExpression',
// 'AssignmentExpression',
// 'ConditionalExpression',
// 'FunctionExpression',
// 'NewExpression',
// 'ObjectExpression',
// 'RegularExpression',
// 'SequenceExpression',
// 'ThisExpression',
// 'UpdateExpression',

//// DONE
// 'BinaryExpression',
// 'MemberExpression',
// 'LogicalExpression',
// 'UnaryExpression',
// 'CallExpression',

    return function (node) {
        return supported.some(function (kind) { return node.type === kind; });
    };
};

var capture = function (kind, target, column) {
    return {
        "type": "CallExpression",
        "callee": {
            "type": "MemberExpression",
            "computed": false,
            "object": {
                "type": "Identifier",
                "name": powerAssertVariableName
            },
            "property": {
                "type": "Identifier",
                "name": kind
            }
        },
        "arguments": [
            target,
            {
                "type": "Literal",
                "value": column.start
            },
            {
                "type": "Literal",
                "value": column.end
            }
        ]
    };
};

// enclose in _pa_.ident
var captureIdent = function (target, column) {
    return capture('ident', target, column);
};

// enclose in _pa_.funcall
var captureFuncall = function (target, column) {
    return capture('funcall', target, column);
};

var toColumn = function (node) {
    return {
        start: node.loc.start.column,
        end: node.loc.end.column
    };
};

var captureRecursively = function (node) {
    switch (node.type) {
    case 'Identifier':
        return captureIdent(node, toColumn(node));
    case 'MemberExpression': // ex: foo.bar.baz
        node.object = captureRecursively(node.object);
        return captureIdent(node, toColumn(node.property));
    case 'CallExpression':
        node.arguments = node.arguments.map(function (arg) {
            return captureRecursively(arg);
        });
        return captureFuncall(node, toColumn(node));
        // node.callee = captureRecursively(node.callee);
        // return node;
    case 'UnaryExpression':
        if (node.operator === 'typeof') {
            // 'typeof' operator is not supported
            return node;
        }
        node.argument = captureRecursively(node.argument);
        return node;
    case 'BinaryExpression':
        node.left = captureRecursively(node.left);
        node.right = captureRecursively(node.right);
        return node;
    case 'LogicalExpression':
        node.left = captureRecursively(node.left);
        node.right = captureRecursively(node.right);
        return node;
    default:
        return node;
    }
};

// enclose assert expression in _pa_.expr
var captureFirstArgument = function (firstArgument, line, lineNumber) {
    return {
        "type": "CallExpression",
        "callee": {
            "type": "MemberExpression",
            "computed": false,
            "object": {
                "type": "Identifier",
                "name": powerAssertVariableName
            },
            "property": {
                "type": "Identifier",
                "name": "expr"
            }
        },
        "arguments": [
            firstArgument,
            {
                "type": "Literal",
                "value": line
            },
            {
                "type": "Literal",
                "value": lineNumber
            }
        ]
    };
};

var instrument = function (expression, line, lineNumber) {
    var firstArgument = expression.arguments[0];
    if (!isSupported(firstArgument)) {
        return;
    }
    firstArgument = captureRecursively(firstArgument);
    expression.arguments[0] = captureFirstArgument(firstArgument, line, lineNumber);
};

var isAssertOkCall = function (callee) {
    if (callee.type !== 'MemberExpression' || callee.computed !== false) {
        return false;
    }
    var ob = callee.object,
        prop = callee.property;
    return ((ob.type === 'Identifier' && ob.name === 'assert') && (prop.type === 'Identifier' && prop.name === 'ok'));
};

var isAssertCall = function (callee) {
    return (callee.type === 'Identifier' && callee.name === 'assert');
};

var modifyTree = function (syntax, lines) {
    traverse(syntax, function (node) {
        if (typeof node.type === 'undefined') {
            return;
        }
        if (node.type !== 'ExpressionStatement') {
            return;
        }
        var expression = node.expression;
        if (expression.type !== 'CallExpression') {
            return;
        }
        var callee = expression.callee;
        if (!(isAssertCall(callee) || isAssertOkCall(callee))) {
            return;
        }
        var lineNumber = node.loc.start.line;
        var line = lines[lineNumber - 1];
        instrument(expression, line, lineNumber);
    });
};

var powerAssertVariableDeclaration = {
    "type": "VariableDeclaration",
    "declarations": [
        {
            "type": "VariableDeclarator",
            "id": {
                "type": "Identifier",
                "name": powerAssertVariableName
            },
            "init": {
                "type": "CallExpression",
                "callee": {
                    "type": "Identifier",
                    "name": "require"
                },
                "arguments": [
                    {
                        "type": "Literal",
                        "value": powerAssertModuleName
                    }
                ]
            }
        }
    ],
    "kind": "var"
};

var empower = function empower(source, options) {
    options = options || {};
    var lines = source.split("\n"),
        tree = esprima.parse(source, {tolerant: true, loc: true});
    modifyTree(tree, lines, options);

    if (options['module'] === 'commonjs') {
        // insert "var _pa_ = require('power-assert');"
        tree.body.unshift(powerAssertVariableDeclaration);
    }

    console.log(escodegen.generate(tree));
};

empower.modifyTree = modifyTree;
empower.instrument = instrument;

/*global exports:false*/
if (typeof exports !== 'undefined') {
    module.exports = empower;
}
<|endoftext|>


<commit_before>var $ = require('jquery');

var counter = 0;

var collisionCanHappen = true;

function Enemy (options) {
  this.options = options || {};
  this.id = Date.now();
  this.x = 800;
  this.y = this.randomY();
  this.width = this.options.width || 50;
  this.height = this.options.height || 35;
  this.image = this.options.image || "../IMGS/airplane.png";
  this.speed = this.options.speed || this.randomSpeed();
}

Enemy.prototype.resetCounter = function() {
  counter = 0;
};

Enemy.prototype.increaseCounter = function() {
  counter++;
};

Enemy.prototype.collision = function (a, b) {
  if (((a.y + a.height) < (b.y)) || (a.y > (b.y + b.height)) || ((a.x + a.width) < b.x) || (a.x > (b.x + b.width)) || collisionCanHappen === false) {
  //if there is no collision
  }
  else {
    console.log('you are dead');
    // themeSong.pause();
    $('#game-over').css('visibility', 'visible');
    // this.active = false;
  }
};

Enemy.prototype.randomY = function() {
  var min = 0;
  var max = 300;
  return Math.floor(Math.random() * (max - min) + min);
};

Enemy.prototype.randomSpeed = function() {
  this.increaseCounter();
  var min;
  var max;

  if (counter < 1000) {
    min = 0.5;
    max = 3;
    $('#game-score').css("color", "black");
  }
  else if (counter < 2000){
    min = 1.5;
    max = 3;
    $('#game-score').css("color", "green");
  }
  else if (counter < 3000){
    min = 2.5;
    max = 4;
    $('#game-score').css("color", "rgb(153, 152, 25)");
}
  else if (counter < 4000){
    min = 3.5;
    max = 5;
    $('#game-score').css("color", "red");
}
    else if (counter < 5000){
    min = 4.5;
    max = 6;

  }

  return Math.random() * (max - min) + min;

}; //end of randomSpeed()

Enemy.prototype.draw = function (ctx) {
  var image = new Image();
  image.src = this.image;
  ctx.drawImage(image, this.x, this.y, this.width, this.height);
  return this;
};

Enemy.prototype.moveLeftRandom = function () {
    this.x = this.x - this.randomSpeed();
    if (this.x < 0){
      this.x = 800;
      this.y = this.randomY();
    }
};

Enemy.prototype.bottomRight = function () {
  var x = this.x + this.width;
  var y  = this.y + this.height;
  return {x: x, y: y};
};

Enemy.prototype.cheat = function (code) {
  if (code === "dogs") {
    collisionCanHappen = false;
    alert("Cheat mode activated!");
  }
  else {
    alert("Nope, wrong code!");
  }
};

module.exports = Enemy;
<commit_msg>at point I want to be, except for the error message Enemy is not a constructor<commit_after>var $ = require('jquery');

var counter = 0;

var collisionCanHappen = true;

var Game = require("./game");
var game = new Game();

function Enemy (options) {
  this.options = options || {};
  this.id = Date.now();
  this.x = 800;
  this.y = this.randomY();
  this.width = this.options.width || 50;
  this.height = this.options.height || 35;
  this.image = this.options.image || "../IMGS/airplane.png";
  this.speed = this.options.speed || this.randomSpeed();
}

Enemy.prototype.resetCounter = function() {
  counter = 0;
};

Enemy.prototype.increaseCounter = function() {
  counter++;
};

Enemy.prototype.collision = function (a, b) {
  if (((a.y + a.height) < (b.y)) || (a.y > (b.y + b.height)) || ((a.x + a.width) < b.x) || (a.x > (b.x + b.width)) || collisionCanHappen === false) {
  //if there is no collision
  }
  else {
    console.log('you are dead');
    game.gameOver();
    game.pauseThemeSong();
  }
};

Enemy.prototype.randomY = function() {
  var min = 0;
  var max = 300;
  return Math.floor(Math.random() * (max - min) + min);
};

Enemy.prototype.randomSpeed = function() {
  this.increaseCounter();
  var min;
  var max;

  if (counter < 1000) {
    min = 0.5;
    max = 3;
    $('#game-score').css("color", "black");
  }
  else if (counter < 2000){
    min = 1.5;
    max = 3;
    $('#game-score').css("color", "green");
  }
  else if (counter < 3000){
    min = 2.5;
    max = 4;
    $('#game-score').css("color", "rgb(153, 152, 25)");
}
  else if (counter < 4000){
    min = 3.5;
    max = 5;
    $('#game-score').css("color", "red");
}
    else if (counter < 5000){
    min = 4.5;
    max = 6;

  }

  return Math.random() * (max - min) + min;

}; //end of randomSpeed()

Enemy.prototype.draw = function (ctx) {
  var image = new Image();
  image.src = this.image;
  ctx.drawImage(image, this.x, this.y, this.width, this.height);
  return this;
};

Enemy.prototype.moveLeftRandom = function () {
    this.x = this.x - this.randomSpeed();
    if (this.x < 0){
      this.x = 800;
      this.y = this.randomY();
    }
};

Enemy.prototype.bottomRight = function () {
  var x = this.x + this.width;
  var y  = this.y + this.height;
  return {x: x, y: y};
};

Enemy.prototype.cheat = function (code) {
  if (code === "dogs") {
    collisionCanHappen = false;
    alert("Cheat mode activated!");
  }
  else {
    alert("Nope, wrong code!");
  }
};

module.exports = Enemy;
<|endoftext|>


<commit_before>var $ = require('jquery');

var counter = 0;

function Enemy (options) {
  this.options = options || {};
  this.x = this.options.x || 800;
  this.y = this.options.y || this.randomY();
  this.width = this.options.width || 50;
  this.height = this.options.height || 35;
  this.image = this.options.image || "../IMGS/airplane.png";
  this.speed = this.options.speed || this.randomSpeed();
}

Enemy.prototype.resetCounter = function() {
  counter = 0;
};

Enemy.prototype.increaseCounter = function() {
  counter++;
};

Enemy.prototype.randomY = function() {
  var min = 0;
  var max = 300;
  return Math.floor(Math.random() * (max - min) + min);
};

Enemy.prototype.randomSpeed = function() {
  this.increaseCounter();
  var min;
  var max;

  if (counter < 1000) {
    min = 0.5;
    max = 3;
    $('#game-score').css("color", "black");
  }
  else if (counter < 2000){
    min = 1.5;
    max = 3;
    $('#game-score').css("color", "green");
  }
  else if (counter < 3000){ //six seconds
    min = 2.5;
    max = 4;
    $('#game-score').css("color", "rgb(153, 152, 25)");
}
  else if (counter < 4000){
    min = 3.5;
    max = 5;
    $('#game-score').css("color", "red");
}
    else if (counter < 5000){
    min = 4.5;
    max = 6;

  }

  return Math.random() * (max - min) + min;

}; //end of randomSpeed()

Enemy.prototype.draw = function (ctx) {
  var image = new Image();
  image.src = this.image;
  ctx.drawImage(image, this.x, this.y, this.width, this.height);
  return this;
};

Enemy.prototype.moveLeftRandom = function () {
    this.x = this.x - this.randomSpeed();
    if (this.x < 0){
      this.x = 800;
      this.y = this.randomY();
    }
};

Enemy.prototype.bottomRight = function () {
  var x = this.x + this.width;
  var y  = this.y + this.height;
  return {x: x, y: y};
};

module.exports = Enemy;
<commit_msg>created randomize function to consolidate rng<commit_after>var $ = require('jquery');

var counter = 0;

function Enemy (options) {
  this.options = options || {};
  this.x = this.options.x || 800;
  this.y = this.options.y || this.randomY();
  this.width = this.options.width || 50;
  this.height = this.options.height || 35;
  this.image = this.options.image || "../IMGS/airplane.png";
  this.speed = this.options.speed || this.randomSpeed();
}

Enemy.prototype.resetCounter = function() {
  counter = 0;
};

Enemy.prototype.increaseCounter = function() {
  counter++;
};

Enemy.prototype.randomY = function() {
  var min = 0;
  var max = 300;
  return randomize(min, max);
  // console.log(randomize());
};

function randomize (min, max) {
  return Math.floor(Math.random() * (max - min) + min);
}

Enemy.prototype.randomSpeed = function() {
  this.increaseCounter();
  var min;
  var max;

  if (counter < 1000) {
    min = 0.5;
    max = 3;
    $('#game-score').css("color", "black");
  }
  else if (counter < 2000){
    min = 1.5;
    max = 3;
    $('#game-score').css("color", "green");
  }
  else if (counter < 3000){ //six seconds
    min = 2.5;
    max = 4;
    $('#game-score').css("color", "rgb(153, 152, 25)");
}
  else if (counter < 4000){
    min = 3.5;
    max = 5;
    $('#game-score').css("color", "red");
}
    else if (counter < 5000){
    min = 4.5;
    max = 6;

  }

  return Math.random() * (max - min) + min;

}; //end of randomSpeed()

Enemy.prototype.draw = function (ctx) {
  var image = new Image();
  image.src = this.image;
  ctx.drawImage(image, this.x, this.y, this.width, this.height);
  return this;
};

Enemy.prototype.moveLeftRandom = function () {
    this.x = this.x - this.randomSpeed();
    if (this.x < 0){
      this.x = 800;
      this.y = this.randomY();
    }
};

Enemy.prototype.bottomRight = function () {
  var x = this.x + this.width;
  var y  = this.y + this.height;
  return {x: x, y: y};
};

module.exports = Enemy;
<|endoftext|>


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

  var globals = typeof window === 'undefined' ? global : window;
  if (typeof globals.require === 'function') return;

  var modules = {};
  var cache = {};
  var aliases = {};
  var has = ({}).hasOwnProperty;

  var unalias = function(alias, loaderPath) {
    var result = aliases[alias] || aliases[alias + '/index.js'];
    return result || alias;
  };

  var _reg = /^\.\.?(\/|$)/;
  var expand = function(root, name) {
    var results = [], part;
    var parts = (_reg.test(name) ? root + '/' + name : name).split('/');
    for (var i = 0, length = parts.length; i < length; i++) {
      part = parts[i];
      if (part === '..') {
        results.pop();
      } else if (part !== '.' && part !== '') {
        results.push(part);
      }
    }
    return results.join('/');
  };

  var dirname = function(path) {
    return path.split('/').slice(0, -1).join('/');
  };

  var localRequire = function(path) {
    return function expanded(name) {
      var absolute = expand(dirname(path), name);
      return globals.require(absolute, path);
    };
  };

  var initModule = function(name, definition) {
    var module = {id: name, exports: {}};
    cache[name] = module;
    definition(module.exports, localRequire(name), module);
    return module.exports;
  };

  var require = function(name, loaderPath) {
    if (loaderPath == null) loaderPath = '/';
    var path = unalias(name, loaderPath);

    if (has.call(cache, path)) return cache[path].exports;
    if (has.call(modules, path)) return initModule(path, modules[path]);

    var dirIndex = expand(path, './index');
    if (has.call(cache, dirIndex)) return cache[dirIndex].exports;
    if (has.call(modules, dirIndex)) return initModule(dirIndex, modules[dirIndex]);

    throw new Error('Cannot find module "' + name + '" from ' + '"' + loaderPath + '"');
  };

  require.alias = function(from, to) {
    aliases[to] = from;
  };

  require.register = require.define = function(bundle, fn) {
    if (typeof bundle === 'object') {
      for (var key in bundle) {
        if (has.call(bundle, key)) {
          require.register(key, bundle[key]);
        }
      }
    } else {
      modules[bundle] = fn;
    }
  };

  require.list = function() {
    var result = [];
    for (var item in modules) {
      if (has.call(modules, item)) {
        result.push(item);
      }
    }
    return result;
  };

  require.brunch = true;
  require._cache = cache;
  globals.require = require;
})();
<commit_msg>Add support for file extensions and main aliases<commit_after>(function() {
  'use strict';

  var globals = typeof window === 'undefined' ? global : window;
  if (typeof globals.require === 'function') return;

  var modules = {};
  var cache = {};
  var aliases = {};
  var has = ({}).hasOwnProperty;
  var extExp = /\.[^.\/]+$/
  var indexExp = /\/index(\.[^\/]+)?$/

  var _reg = /^\.\.?(\/|$)/;
  var expand = function(root, name) {
    var results = [], part;
    var parts = (_reg.test(name) ? root + '/' + name : name).split('/');
    for (var i = 0, length = parts.length; i < length; i++) {
      part = parts[i];
      if (part === '..') {
        results.pop();
      } else if (part !== '.' && part !== '') {
        results.push(part);
      }
    }
    return results.join('/');
  };

  var dirname = function(path) {
    return path.split('/').slice(0, -1).join('/');
  };

  var localRequire = function(path) {
    return function expanded(name) {
      var absolute = expand(dirname(path), name);
      return globals.require(absolute, path);
    };
  };

  var initModule = function(name, definition) {
    var module = {id: name, exports: {}};
    cache[name] = module;
    definition(module.exports, localRequire(name), module);
    return module.exports;
  };

  var require = function(name, loaderPath) {
    if (loaderPath == null) loaderPath = '/';
    var path = aliases[name] || name;

    if (has.call(cache, path)) return cache[path].exports;
    if (has.call(modules, path)) return initModule(path, modules[path]);

    throw new Error('Cannot find module "' + name + '" from ' + '"' + loaderPath + '"');
  };

  require.alias = function(from, to) {
    aliases[to] = from;
  };

  require.register = require.define = function(bundle, fn) {
    if (typeof bundle === 'object') {
      for (var key in bundle) {
        if (has.call(bundle, key)) {
          require.register(key, bundle[key]);
        }
      }
    } else {
      modules[bundle] = fn;

      var alias = bundle;
      while (extExp.test(alias)) {
        alias = alias.replace(extExp, '');
        if (!has.call(aliases, alias) || aliases[alias].replace(extExp, '') === alias + '/index') {
          aliases[alias] = bundle;
        }
      }

      if (indexExp.test(bundle)) {
        alias = bundle.replace(indexExp, '');
        if (!has.call(aliases, alias)) {
          aliases[alias] = bundle;
        }
      }
    }
  };

  require.list = function() {
    var result = [];
    for (var item in modules) {
      if (has.call(modules, item)) {
        result.push(item);
      }
    }
    return result;
  };

  require.brunch = true;
  require._cache = cache;
  globals.require = require;
})();
<|endoftext|>


<commit_before>'use strict';
var fs = require( 'fs' );
var path = require( 'path' );
var Q = require( 'q' );
var extend = require( 'extend-shallow' );
var glob = require( "glob" );

/**
 * Retrieve the meta information of a Qlik Sense extension + the unqiue name of the extension.
 * @returns {{fromFolder: Function, fromFile: Function}}
 * @constructor
 * @api public
 */
var ExtInfo = function () {

    // empty props definition
    //Todo: other props
    var defaultProps = {
        name: "",
        version: "",
        type: "visualization"
    };

    return {

        /**
         * Retrieve the extension meta information from a folder.         *
         * Doesn't search recursively, just in the root of the folder for any file matching the pattern *.qext
         *
         * @exception
         * Throws an exception in the following cases:
         * - More than one qext files in the folder
         * - content of the .qext file is not valid json
         * - property `type` is missing
         *
         * @returns {object} extension meta information.
         * @param folderPath Absolute path of the folder to search in.
         *
         * @api public

         * @todo - if ending slash is missing, the path is not recognized as a valid directory
         */
        fromDir: function ( folderPath ) {

            var that = this;

            var defer = Q.defer();

            var searchMask = folderPath + '*.qext';
            var options = {};

            glob( searchMask, options, function ( err, files ) {

                if ( err ) {
                    defer.reject( {message: 'Error finding the .qext file', error: err} );
                } else {

                    // sanity check first, then return
                    if ( files.length > 1 ) {

                        defer.reject( {message: 'Found more than on file with the extension .qext', result: files} );

                    } else if ( files.length === 0 ) {

                        defer.reject( {message: 'Didn\'t find any .qext file in folder ' + folderPath} );

                    } else {

                        defer.resolve( that.fromFile( files[0] ) );

                    }
                }

            } );

            return defer.promise;

        },

        /**
         * Retrieve meta information by pointing directly to the .qext file.
         * @param filePath Absolute path of the file to fetch the meta data from.
         * @throws
         *  - File doesn\'t exist in case of pointing to a non existing file
         * @returns {promise|*|Q.promise}
         *
         * @api public
         */
        fromFile: function ( filePath ) {

            var defer = Q.defer();

            if ( fs.existsSync( filePath ) ) {
                fs.readFile( filePath, function ( err, data ) {

                    if ( err ) {
                        defer.reject( err );

                    } else {

                        var props = null;
                        try {
                            props = JSON.parse( data );
                        } catch ( e ) {
                            defer.reject( {message: 'Invalid JSON file', error: e} );
                        }

                        props._uniqueName = path.basename( filePath, '.qext' );
                        props = extend( defaultProps, props );
                        defer.resolve( props );

                    }

                } );
            } else {
                defer.reject( 'File doesn\'t exist: ' + filePath );
            }

            return defer.promise;

        }
    };
};

module.exports = new ExtInfo();
<commit_msg>Added fullPath<commit_after>'use strict';
var fs = require( 'fs' );
var path = require( 'path' );
var Q = require( 'q' );
var extend = require( 'extend-shallow' );
var glob = require( "glob" );

/**
 * Retrieve the meta information of a Qlik Sense extension + the unqiue name of the extension.
 * @returns {{fromFolder: Function, fromFile: Function}}
 * @constructor
 * @api public
 */
var ExtInfo = function () {

    // empty props definition
    //Todo: other props
    var defaultProps = {
        name: "",
        version: "",
        type: "visualization"
    };

    return {

        /**
         * Retrieve the extension meta information from a folder.         *
         * Doesn't search recursively, just in the root of the folder for any file matching the pattern *.qext
         *
         * @exception
         * Throws an exception in the following cases:
         * - More than one qext files in the folder
         * - content of the .qext file is not valid json
         * - property `type` is missing
         *
         * @returns {object} extension meta information.
         * @param folderPath Absolute path of the folder to search in.
         *
         * @api public

         * @todo - if ending slash is missing, the path is not recognized as a valid directory
         */
        fromDir: function ( folderPath ) {

            var that = this;

            var defer = Q.defer();

            var searchMask = folderPath + '*.qext';
            var options = {};

            glob( searchMask, options, function ( err, files ) {

                if ( err ) {
                    defer.reject( {message: 'Error finding the .qext file', error: err} );
                } else {

                    // sanity check first, then return
                    if ( files.length > 1 ) {

                        defer.reject( {message: 'Found more than on file with the extension .qext', result: files} );

                    } else if ( files.length === 0 ) {

                        defer.reject( {message: 'Didn\'t find any .qext file in folder ' + folderPath} );

                    } else {

                        defer.resolve( that.fromFile( files[0] ) );

                    }
                }

            } );

            return defer.promise;

        },

        /**
         * Retrieve meta information by pointing directly to the .qext file.
         *
         * In addition to the defined meta data in the .qext file the following information will be added:
         *
         *    - _uniqueName - file path of the .qext file
         *    - _fullPath - full directory name
         *
         * @param filePath Absolute path of the file to fetch the meta data from.
         * @throws
         *  - File doesn\'t exist in case of pointing to a non existing file
         * @returns {promise|*|Q.promise}
         *
         * @api public
         */
        fromFile: function ( filePath ) {

            var defer = Q.defer();

            if ( fs.existsSync( filePath ) ) {
                fs.readFile( filePath, function ( err, data ) {

                    if ( err ) {
                        defer.reject( err );

                    } else {

                        var props = null;
                        try {
                            props = JSON.parse( data );
                        } catch ( e ) {
                            defer.reject( {message: 'Invalid JSON file', error: e} );
                        }

                        props._uniqueName = path.basename( filePath, '.qext' );
                        props._fullPath = path.dirname( filePath );
                        props = extend( defaultProps, props );
                        defer.resolve( props );

                    }

                } );
            } else {
                defer.reject( 'File doesn\'t exist: ' + filePath );
            }

            return defer.promise;

        }
    };
};

module.exports = new ExtInfo();
<|endoftext|>


<commit_before>//* @protected
/**
	_moon.DataListSpotlightSupport_ a mixin that provides spotlight handling code for use by
	_moon.DataList_ and _moon.DataGridList_.  Since those each extend from their respective
	enyo counterparts, this mixin provides common add-on code needed for proper spotlight handling.
*/
moon.DataListSpotlightSupport = {
	didRender: function () {
		// Since we delay rendering (potentially spottable) children by default, spotlight on the list is
		// true by default; once we render, we check if the list was focused and if so, transfer
		// focus to the first spottable child inside
		var spot = enyo.Spotlight.getCurrent();
		this.spotlight = false;
		if (spot && (spot === this || spot.isDescendantOf(this))) {
			enyo.Spotlight.spot(this);
		}
	},
	didScroll: enyo.inherit(function (sup) {
		return function () {
			// When scrolling in pointer mode, we unspot the last focused child, to prevent it from
			// looping as new pages come up
			var spot;
			if (enyo.Spotlight.getPointerMode() &&
				((spot = enyo.Spotlight.getCurrent()) && (spot === this || spot.isDescendantOf(this)))) {
				// If we haven't enabled spotlightable controls,
				if (this.$.scroller.spotlightPagingControls != true) {
					// go ahead and unspot whatever's currently spotted.
					enyo.Spotlight.unspot();
				}
				this._unspotSinceSpot = true;
			}
			return sup.apply(this, arguments);
		};
	}),
	previewDomEvent: function(inEvent) {
		// When spotlight is being applied back to the list after being unspotted, check that the child being
		// focused is visible and if not, spot the first visible child that is
		if ((inEvent.type == "onSpotlightFocus") && this._unspotSinceSpot) {
			if (enyo.Spotlight.getPointerMode()) {
				this._unspotSinceSpot = false;
			} else {
				var target = inEvent.originator;
				if (target != this) {
					// Calculate the target bounds, relative to the scrollBounds
					var tb = target.getBounds();
					var p = target.isDescendantOf(this.$.page1) ? this.$.page1 : this.$.page2;
					var pb = p.getBounds();
					// Need to add page offset to target bounds
					tb.top += pb.top;
					tb.left += pb.left;
					var sb = this.$.scroller.getScrollBounds();
					// Check if target is inside the current scrollBounds
					if ((tb.top < sb.top) ||
						(tb.left < sb.left) ||
						((tb.top + tb.height) > (sb.top + sb.clientHeight)) ||
						((tb.left + tb.width) > (sb.left + sb.clientWidth))) {
						// Not in view, so find and spot the first visible child
						var vc = this.getFirstVisibleChild(sb);
						if (vc) {
							this._unspotSinceSpot = false;
							enyo.Spotlight.spot(vc);
						}
						return true;
					} else {
						this._unspotSinceSpot = false;
					}
				}
			}
		}
	},
	getFirstVisibleChild: function(inScrollBounds) {
		// Loop through the pages in top-down order
		var pages = (this.$.page1.index < this.$.page2.index) ?
			[this.$.page1, this.$.page2] :
			[this.$.page2, this.$.page1];
		for (var p in pages) {
			var page = pages[p];
			var pb = page.getBounds();
			// Loop through children in each pange top-down
			for (var i=0; i<page.children.length; i++) {
				var c = page.children[i];
				var cb = c.getBounds();
				// Need to add page offset to target bounds
				cb.top += pb.top;
				cb.left += pb.left;
				// Return the first spottable child whose top/left are inside the viewport
				if ((cb.top >= inScrollBounds.top) && (cb.left >= inScrollBounds.left)) {
					if (enyo.Spotlight.isSpottable(c)) {
						return c;
					}
					c = enyo.Spotlight.getFirstChild(c);
					if (c) {
						return c;
					}
				}
			}
		}
		return null;
	}
};

//* @public

/**
	_moon.DataList_ is an [enyo.DataList](#enyo.DataList) with Moonstone styling
	applied.  It uses [moon.Scroller](#moon.Scroller) as its default scroller.
*/
enyo.kind({
	name: "moon.DataList",
	kind: "enyo.DataList",
	//* @protected
	mixins: ["moon.DataListSpotlightSupport"],
	noDefer: true,
	allowTransitions: false,
	spotlight: true,
	scrollerOptions: { kind: "moon.Scroller", horizontal: "hidden" }
});
//* @protected
/**
	Overload the delegate strategy to incorporate measurements for our scrollers
	when they are visible.
*/
(function (enyo, moon) {
	moon.DataList.delegates.vertical   = enyo.clone(moon.DataList.delegates.vertical);
	moon.DataList.delegates.horizontal = enyo.clone(moon.DataList.delegates.horizontal);
	var exts = {
		refresh: enyo.inherit(function (sup) {
			return function (list) {
				sup.apply(this, arguments);
				list.$.scroller.resized();
			};
		}),
		scrollToIndex: function (list, i) {
			// This function recurses, so make sure we are scrolling to a valid index,
			// otherwise childForIndex will never return a control
			if ((i < 0) || (i >= list.collection.length)) {
				return;
			}
				// first see if the child is already available to scroll to
			var c = this.childForIndex(list, i),
				// but we also need the page so we can find its position
				p = this.pageForIndex(list, i);
			// if there is no page then the index is bad
			if (p < 0 || p > this.pageCount(list)) { return; }
			// if there isn't one, then we know we need to go ahead and
			// update, otherwise we should be able to use the scroller's
			// own methods to find it
			if (c) {
				// force a synchronous scroll to the control so it won't dupe and
				// re-animate over positions it has already crossed
				list.$.scroller.scrollToControl(c, false, false);
			} else {
				var idx = list.$.page1.index;

				// attempting to line them up in a useful order
				// given the direction from where our current index is
				if (idx < p) {
					list.$.page1.index = p - 1;
					list.$.page2.index = p;
				} else {
					list.$.page1.index = p;
					list.$.page2.index = p + 1;
				}
				list.refresh();

				this.scrollToIndex(list, i);
			}
		}
	};
	enyo.kind.extendMethods(moon.DataList.delegates.vertical, exts, true);
	enyo.kind.extendMethods(moon.DataList.delegates.vertical, {
		reset: enyo.inherit(function (sup) {
			return function (list) {
				sup.apply(this, arguments);
				if (list.$.scroller.getVertical() != "scroll") {
					this.updateBounds(list);
					list.refresh();
				}
				list.$.scroller.scrollTo(0, 0, false);
			};
		}),
		updateBounds: enyo.inherit(function (sup) {
			return function (list) {
				sup.apply(this, arguments);
				var w = list.boundsCache.width,
					b = list.$.scroller.getScrollBounds(),
					n = list.$.scroller.$.strategy.$.vColumn.hasNode();
				if (list.$.scroller.getVertical() == "scroll" || (b.height > b.clientHeight)) {
					list.boundsCache.width = w-n.offsetWidth;
				}
			};
		})
	}, true);
	enyo.kind.extendMethods(moon.DataList.delegates.horizontal, exts, true);
	enyo.kind.extendMethods(moon.DataList.delegates.horizontal, {
		reset: enyo.inherit(function (sup) {
			return function (list) {
				sup.apply(this, arguments);
				if (list.$.scroller.getHorizontal() != "scroll") {
					this.updateBounds(list);
					list.refresh();
				}
				list.$.scroller.scrollTo(0, 0, false);
			};
		}),
		updateBounds: enyo.inherit(function (sup) {
			return function (list) {
				sup.apply(this, arguments);
				var w = list.boundsCache.height,
					b = list.$.scroller.getScrollBounds(),
					n = list.$.scroller.$.strategy.$.hColumn.hasNode();
				if (list.$.scroller.getVertical() == "scroll" || (b.width > b.clientWidth)) {
					list.boundsCache.height = w-n.offsetHeight;
				}
			};
		})
	}, true);
})(enyo, moon);
<commit_msg>Appeasing the Travis… Enyo-DCO-1.1-Signed-off-by: Blake Stephens <blake.stephens@lge.com><commit_after>//* @protected
/**
	_moon.DataListSpotlightSupport_ a mixin that provides spotlight handling code for use by
	_moon.DataList_ and _moon.DataGridList_.  Since those each extend from their respective
	enyo counterparts, this mixin provides common add-on code needed for proper spotlight handling.
*/
moon.DataListSpotlightSupport = {
	didRender: function () {
		// Since we delay rendering (potentially spottable) children by default, spotlight on the list is
		// true by default; once we render, we check if the list was focused and if so, transfer
		// focus to the first spottable child inside
		var spot = enyo.Spotlight.getCurrent();
		this.spotlight = false;
		if (spot && (spot === this || spot.isDescendantOf(this))) {
			enyo.Spotlight.spot(this);
		}
	},
	didScroll: enyo.inherit(function (sup) {
		return function () {
			// When scrolling in pointer mode, we unspot the last focused child, to prevent it from
			// looping as new pages come up
			var spot;
			if (enyo.Spotlight.getPointerMode() &&
				((spot = enyo.Spotlight.getCurrent()) && (spot === this || spot.isDescendantOf(this)))) {
				// If we haven't enabled spotlightable controls,
				if (!this.$.scroller.spotlightPagingControls) {
					// go ahead and unspot whatever's currently spotted.
					enyo.Spotlight.unspot();
				}
				this._unspotSinceSpot = true;
			}
			return sup.apply(this, arguments);
		};
	}),
	previewDomEvent: function(inEvent) {
		// When spotlight is being applied back to the list after being unspotted, check that the child being
		// focused is visible and if not, spot the first visible child that is
		if ((inEvent.type == "onSpotlightFocus") && this._unspotSinceSpot) {
			if (enyo.Spotlight.getPointerMode()) {
				this._unspotSinceSpot = false;
			} else {
				var target = inEvent.originator;
				if (target != this) {
					// Calculate the target bounds, relative to the scrollBounds
					var tb = target.getBounds();
					var p = target.isDescendantOf(this.$.page1) ? this.$.page1 : this.$.page2;
					var pb = p.getBounds();
					// Need to add page offset to target bounds
					tb.top += pb.top;
					tb.left += pb.left;
					var sb = this.$.scroller.getScrollBounds();
					// Check if target is inside the current scrollBounds
					if ((tb.top < sb.top) ||
						(tb.left < sb.left) ||
						((tb.top + tb.height) > (sb.top + sb.clientHeight)) ||
						((tb.left + tb.width) > (sb.left + sb.clientWidth))) {
						// Not in view, so find and spot the first visible child
						var vc = this.getFirstVisibleChild(sb);
						if (vc) {
							this._unspotSinceSpot = false;
							enyo.Spotlight.spot(vc);
						}
						return true;
					} else {
						this._unspotSinceSpot = false;
					}
				}
			}
		}
	},
	getFirstVisibleChild: function(inScrollBounds) {
		// Loop through the pages in top-down order
		var pages = (this.$.page1.index < this.$.page2.index) ?
			[this.$.page1, this.$.page2] :
			[this.$.page2, this.$.page1];
		for (var p in pages) {
			var page = pages[p];
			var pb = page.getBounds();
			// Loop through children in each pange top-down
			for (var i=0; i<page.children.length; i++) {
				var c = page.children[i];
				var cb = c.getBounds();
				// Need to add page offset to target bounds
				cb.top += pb.top;
				cb.left += pb.left;
				// Return the first spottable child whose top/left are inside the viewport
				if ((cb.top >= inScrollBounds.top) && (cb.left >= inScrollBounds.left)) {
					if (enyo.Spotlight.isSpottable(c)) {
						return c;
					}
					c = enyo.Spotlight.getFirstChild(c);
					if (c) {
						return c;
					}
				}
			}
		}
		return null;
	}
};

//* @public

/**
	_moon.DataList_ is an [enyo.DataList](#enyo.DataList) with Moonstone styling
	applied.  It uses [moon.Scroller](#moon.Scroller) as its default scroller.
*/
enyo.kind({
	name: "moon.DataList",
	kind: "enyo.DataList",
	//* @protected
	mixins: ["moon.DataListSpotlightSupport"],
	noDefer: true,
	allowTransitions: false,
	spotlight: true,
	scrollerOptions: { kind: "moon.Scroller", horizontal: "hidden" }
});
//* @protected
/**
	Overload the delegate strategy to incorporate measurements for our scrollers
	when they are visible.
*/
(function (enyo, moon) {
	moon.DataList.delegates.vertical   = enyo.clone(moon.DataList.delegates.vertical);
	moon.DataList.delegates.horizontal = enyo.clone(moon.DataList.delegates.horizontal);
	var exts = {
		refresh: enyo.inherit(function (sup) {
			return function (list) {
				sup.apply(this, arguments);
				list.$.scroller.resized();
			};
		}),
		scrollToIndex: function (list, i) {
			// This function recurses, so make sure we are scrolling to a valid index,
			// otherwise childForIndex will never return a control
			if ((i < 0) || (i >= list.collection.length)) {
				return;
			}
				// first see if the child is already available to scroll to
			var c = this.childForIndex(list, i),
				// but we also need the page so we can find its position
				p = this.pageForIndex(list, i);
			// if there is no page then the index is bad
			if (p < 0 || p > this.pageCount(list)) { return; }
			// if there isn't one, then we know we need to go ahead and
			// update, otherwise we should be able to use the scroller's
			// own methods to find it
			if (c) {
				// force a synchronous scroll to the control so it won't dupe and
				// re-animate over positions it has already crossed
				list.$.scroller.scrollToControl(c, false, false);
			} else {
				var idx = list.$.page1.index;

				// attempting to line them up in a useful order
				// given the direction from where our current index is
				if (idx < p) {
					list.$.page1.index = p - 1;
					list.$.page2.index = p;
				} else {
					list.$.page1.index = p;
					list.$.page2.index = p + 1;
				}
				list.refresh();

				this.scrollToIndex(list, i);
			}
		}
	};
	enyo.kind.extendMethods(moon.DataList.delegates.vertical, exts, true);
	enyo.kind.extendMethods(moon.DataList.delegates.vertical, {
		reset: enyo.inherit(function (sup) {
			return function (list) {
				sup.apply(this, arguments);
				if (list.$.scroller.getVertical() != "scroll") {
					this.updateBounds(list);
					list.refresh();
				}
				list.$.scroller.scrollTo(0, 0, false);
			};
		}),
		updateBounds: enyo.inherit(function (sup) {
			return function (list) {
				sup.apply(this, arguments);
				var w = list.boundsCache.width,
					b = list.$.scroller.getScrollBounds(),
					n = list.$.scroller.$.strategy.$.vColumn.hasNode();
				if (list.$.scroller.getVertical() == "scroll" || (b.height > b.clientHeight)) {
					list.boundsCache.width = w-n.offsetWidth;
				}
			};
		})
	}, true);
	enyo.kind.extendMethods(moon.DataList.delegates.horizontal, exts, true);
	enyo.kind.extendMethods(moon.DataList.delegates.horizontal, {
		reset: enyo.inherit(function (sup) {
			return function (list) {
				sup.apply(this, arguments);
				if (list.$.scroller.getHorizontal() != "scroll") {
					this.updateBounds(list);
					list.refresh();
				}
				list.$.scroller.scrollTo(0, 0, false);
			};
		}),
		updateBounds: enyo.inherit(function (sup) {
			return function (list) {
				sup.apply(this, arguments);
				var w = list.boundsCache.height,
					b = list.$.scroller.getScrollBounds(),
					n = list.$.scroller.$.strategy.$.hColumn.hasNode();
				if (list.$.scroller.getVertical() == "scroll" || (b.width > b.clientWidth)) {
					list.boundsCache.height = w-n.offsetHeight;
				}
			};
		})
	}, true);
})(enyo, moon);
<|endoftext|>


<commit_before>/*! fpo.js
	v0.0.7 (c) Kyle Simpson
	MIT License: http://getify.mit-license.org
*/

(function UMD(name,context,definition){
	if (typeof define === "function" && define.amd) { define(definition); }
	else if (typeof module !== "undefined" && module.exports) { module.exports = definition(); }
	else { context[name] = definition(name,context); }
})("FPO",this,function DEF(name,context){
	"use strict";

	var publicAPI = {
		curry: curryMultiple( {fn: curry, n: 2} ),
		curryMultiple: curryMultiple( {fn: curryMultiple, n: 2} ),
		uncurry,
		partial: curryMultiple( {fn: partial, n: 2 } ),
		complement,
		apply: curryMultiple( {fn: apply, n: 2} ),
		gather: curryMultiple( {fn: gather, n: 2} ),
		prop: curryMultiple( {fn: prop, n: 2} ),
		setProp: curryMultiple( {fn: setProp, n: 3} ),
		filterIn: curryMultiple( {fn: filterIn, n: 2} ),
		filterOut: curryMultiple( {fn: filterOut, n: 2} ),
		map: curryMultiple( {fn: map, n: 2} ),
		reduce: curryMultiple( {fn: reduce, n: 3} ),
		reduceRight: curryMultiple( {fn: reduceRight, n: 3} ),
		zip: curryMultiple( {fn: zip, n: 2} ),
	};

	publicAPI.std = {
		curry: _curryMultiple( _curry, /*arity=*/2 ),
		curryMultiple: _curryMultiple( _curryMultiple, /*arity=*/2 ),
		uncurry: _uncurry,
		partial: _curryMultiple( _partial, /*arity=*/2 ),
		complement: gather( {fn: complement, props: ["fn"]} ),
		apply: _curryMultiple( gather( {fn: apply, props: ["fn","props"]} ), /*arity=*/2 ),
		gather: _curryMultiple( gather( {fn: gather, props: ["fn","props"]} ), /*arity=*/2 ),
		prop: _curryMultiple( gather( {fn: prop, props: ["name","o"]} ), /*arity=*/2 ),
		setProp: _curryMultiple( gather( {fn: setProp, props: ["name","o","v"]} ), /*arity=*/3 ),
		filterIn: _curryMultiple( gather( {fn: filterIn, props: ["fn","arr"]} ), /*arity=*/2 ),
		filterOut: _curryMultiple( gather( {fn: filterOut, props: ["fn","arr"]} ), /*arity=*/2 ),
		map: _curryMultiple( gather( {fn: map, props: ["fn","arr"]} ), /*arity=*/2 ),
		reduce: _curryMultiple( gather( {fn: reduce, props: ["fn","v","arr"]} ), /*arity=*/3 ),
		reduceRight: _curryMultiple( gather( {fn: reduceRight, props: ["fn","v","arr"]} ), /*arity=*/3 ),
		zip: _curryMultiple( gather( {fn: zip, props: ["arr1","arr2"]} ), /*arity=*/2 ),
	};

	return publicAPI;

	// ***************************************

	function curry({ fn, n: arity = 1 } = {}) {
		return (function nextCurried(prevArgsObj){
			return function curried(nextArgObj = {}){
				if (!nextArgObj || typeof nextArgObj != "object") {
					nextArgObj = { v: nextArgObj };
				}

				var [key] = Object.keys( nextArgObj );
				var argsObj = Object.assign( {}, prevArgsObj, { [key || "v"]: nextArgObj[key] } );

				if (Object.keys( argsObj ).length >= arity) {
					return fn( argsObj );
				}
				else {
					return nextCurried( argsObj );
				}
			};
		})( {} );
	}

	function curryMultiple({ fn, n: arity = 1 } = {}) {
		return (function nextCurried(prevArgsObj){
			return function curried(nextArgsObj = {}){
				if (!nextArgsObj || typeof nextArgsObj != "object") {
					nextArgsObj = { v: nextArgsObj };
				}

				var [key] = Object.keys( nextArgsObj );
				var argsObj = Object.assign( {}, prevArgsObj, nextArgsObj );

				if (Object.keys( argsObj ).length >= arity) {
					return fn( argsObj );
				}
				else {
					return nextCurried( argsObj );
				}
			};
		})( {} );
	}

	function uncurry({ fn } = {}) {
		return function uncurried(argsObj = {}){
			var ret = fn;

			for (let prop of Object.keys(argsObj)) {
				// assume `fn` is strictly curried (needs props one at a time),
				// instead of loose/multiple currying
				ret = ret( { [prop]: argsObj[prop] } );
			}

			return ret;
		};
	}

	function partial({ fn, args: partialArgsObj = {} } = {}) {
		return function partiallyApplied(restArgsObj = {}){
			return fn( Object.assign( {}, partialArgsObj, restArgsObj ) );
		};
	}

	function complement({ fn: predicateFn } = {}) {
		return function complemented(...args){
			return !predicateFn( ...args );
		};
	}

	function apply({
		fn,
		props: propOrder = fn.toString()
			.replace( /^(?:(?:function.*\(([^]*?)\))|(?:([^\(\)]+?)\s*=>)|(?:\(([^]*?)\)\s*=>))[^]+$/, "$1$2$3" )
			.split( /\s*,\s*/ )
			.map( v => v.replace( /[=\s].*$/, "" ) )
	} = {}) {
		return function appliedFn(argsObj) {
			return fn( ...propOrder.map( k => argsObj[k] ) );
		};
	}

	function gather({ fn, props: propOrder = [] } = {}) {
		return function gatheredFn(...args) {
			return fn(
				zip( {arr1: propOrder, arr2: args} )
				.reduce( (obj,[key,val]) => (obj[key] = val, obj), {} )
			);
		};
	}

	function prop({ name = "v", o: obj = {} } = {}) {
		return obj[name];
	}

	function setProp({ name = "v", o: obj = {}, v: val } = {}) {
		var clone = Object.assign( {}, obj );
		clone[name] = val;
		return clone;
	}

	function filterIn({ fn: predicateFn, arr } = {}) {
		return arr.filter( predicateFn );
	}

	function filterOut({ fn: predicateFn, arr } = {}) {
		return filterIn( complement( predicateFn ), arr );
	}

	function map({ fn: mapperFn, arr } ={}) {
		return arr.map( mapperFn );
	}

	function reduce({ fn: reducerFn, v: initialValue, arr } = {}) {
		return initialValue !== undefined ?
			arr.reduce( reducerFn, initialValue ) :
			arr.reduce( reducerFn );
	}

	function reduceRight({ fn: reducerFn, v: initialValue, arr } = {}) {
		return initialValue !== undefined ?
			arr.reduceRight( reducerFn, initialValue ) :
			arr.reduceRight( reducerFn );
	}

	function zip({ arr1, arr2 } = {}) {
		var zipped = [];
		arr1 = arr1.slice();
		arr2 = arr2.slice();

		while (arr1.length > 0 && arr2.length > 0) {
			zipped.push( [ arr1.shift(), arr2.shift() ] );
		}

		return zipped;
	}

	// ***************************************
	// Private

	function _curry(fn,arity = fn.length) {
		return (function nextCurried(prevArgs){
			return function curried(nextArg){
				var args = prevArgs.concat( [nextArg] );

				if (args.length >= arity) {
					return fn( ...args );
				}
				else {
					return nextCurried( args );
				}
			};
		})( [] );
	}

	function _curryMultiple(fn,arity = fn.length) {
		return (function nextCurried(prevArgs){
			return function curried(...nextArgs){
				var args = prevArgs.concat( nextArgs );

				if (args.length >= arity) {
					return fn( ...args );
				}
				else {
					return nextCurried( args );
				}
			};
		})( [] );
	}

	function _uncurry(fn) {
		return function uncurried(...args){
			var ret = fn;

			for (let i = 0; i < args.length; i++) {
				// assume `fn` is strictly curried (needs one arg at a time),
				// instead of loose/multiple currying
				ret = ret( args[i] );
			}

			return ret;
		};
	}

	function _partial(fn,presetArgs = []) {
		return function partiallyApplied(...laterArgs){
			return fn( ...presetArgs, ...laterArgs );
		};
	}

});
<commit_msg>adding compose/pipe, tweaking currying-arity on several methods to allow defaults<commit_after>/*! fpo.js
	v0.0.8 (c) Kyle Simpson
	MIT License: http://getify.mit-license.org
*/

(function UMD(name,context,definition){
	if (typeof define === "function" && define.amd) { define(definition); }
	else if (typeof module !== "undefined" && module.exports) { module.exports = definition(); }
	else { context[name] = definition(name,context); }
})("FPO",this,function DEF(name,context){
	"use strict";

	var publicAPI = {
		curry: curryMultiple( {fn: curry, n: 1} ),
		curryMultiple: curryMultiple( {fn: curryMultiple, n: 1} ),
		uncurry,
		partial: curryMultiple( {fn: partial, n: 2 } ),
		complement,
		apply: curryMultiple( {fn: apply, n: 1} ),
		gather: curryMultiple( {fn: gather, n: 2} ),
		compose,
		pipe,
		prop: curryMultiple( {fn: prop, n: 2} ),
		setProp: curryMultiple( {fn: setProp, n: 3} ),
		filterIn: curryMultiple( {fn: filterIn, n: 2} ),
		filterOut: curryMultiple( {fn: filterOut, n: 2} ),
		map: curryMultiple( {fn: map, n: 2} ),
		reduce: curryMultiple( {fn: reduce, n: 3} ),
		reduceRight: curryMultiple( {fn: reduceRight, n: 3} ),
		zip: curryMultiple( {fn: zip, n: 2} ),
	};

	publicAPI.std = {
		curry: _curryMultiple( _curry, /*arity=*/1 ),
		curryMultiple: _curryMultiple( _curryMultiple, /*arity=*/1 ),
		uncurry: _uncurry,
		partial: _curryMultiple( _partial, /*arity=*/2 ),
		complement: gather( {fn: complement, props: ["fn"]} ),
		apply: _curryMultiple( gather( {fn: apply, props: ["fn","props"]} ), /*arity=*/1 ),
		gather: _curryMultiple( gather( {fn: gather, props: ["fn","props"]} ), /*arity=*/2 ),
		prop: _curryMultiple( gather( {fn: prop, props: ["name","o"]} ), /*arity=*/2 ),
		compose: gather( {fn: compose, props: ["fns"]} ),
		pipe: gather( {fn: pipe, props: ["fns"]} ),
		setProp: _curryMultiple( gather( {fn: setProp, props: ["name","o","v"]} ), /*arity=*/3 ),
		filterIn: _curryMultiple( gather( {fn: filterIn, props: ["fn","arr"]} ), /*arity=*/2 ),
		filterOut: _curryMultiple( gather( {fn: filterOut, props: ["fn","arr"]} ), /*arity=*/2 ),
		map: _curryMultiple( gather( {fn: map, props: ["fn","arr"]} ), /*arity=*/2 ),
		reduce: _curryMultiple( gather( {fn: reduce, props: ["fn","v","arr"]} ), /*arity=*/3 ),
		reduceRight: _curryMultiple( gather( {fn: reduceRight, props: ["fn","v","arr"]} ), /*arity=*/3 ),
		zip: _curryMultiple( gather( {fn: zip, props: ["arr1","arr2"]} ), /*arity=*/2 ),
	};

	return publicAPI;

	// ***************************************

	function curry({ fn, n: arity = 1 } = {}) {
		return (function nextCurried(prevArgsObj){
			return function curried(nextArgObj = {}){
				if (!nextArgObj || typeof nextArgObj != "object") {
					nextArgObj = { v: nextArgObj };
				}

				var [key] = Object.keys( nextArgObj );
				var argsObj = Object.assign( {}, prevArgsObj, { [key || "v"]: nextArgObj[key] } );

				if (Object.keys( argsObj ).length >= arity) {
					return fn( argsObj );
				}
				else {
					return nextCurried( argsObj );
				}
			};
		})( {} );
	}

	function curryMultiple({ fn, n: arity = 1 } = {}) {
		return (function nextCurried(prevArgsObj){
			return function curried(nextArgsObj = {}){
				if (!nextArgsObj || typeof nextArgsObj != "object") {
					nextArgsObj = { v: nextArgsObj };
				}

				var [key] = Object.keys( nextArgsObj );
				var argsObj = Object.assign( {}, prevArgsObj, nextArgsObj );

				if (Object.keys( argsObj ).length >= arity) {
					return fn( argsObj );
				}
				else {
					return nextCurried( argsObj );
				}
			};
		})( {} );
	}

	function uncurry({ fn } = {}) {
		return function uncurried(argsObj = {}){
			var ret = fn;

			for (let prop of Object.keys(argsObj)) {
				// assume `fn` is strictly curried (needs props one at a time),
				// instead of loose/multiple currying
				ret = ret( { [prop]: argsObj[prop] } );
			}

			return ret;
		};
	}

	function partial({ fn, args: partialArgsObj = {} } = {}) {
		return function partiallyApplied(restArgsObj = {}){
			return fn( Object.assign( {}, partialArgsObj, restArgsObj ) );
		};
	}

	function complement({ fn: predicateFn } = {}) {
		return function complemented(...args){
			return !predicateFn( ...args );
		};
	}

	function apply({
		fn,
		props: propNamesInOrder = fn.toString()
			.replace( /^(?:(?:function.*\(([^]*?)\))|(?:([^\(\)]+?)\s*=>)|(?:\(([^]*?)\)\s*=>))[^]+$/, "$1$2$3" )
			.split( /\s*,\s*/ )
			.map( v => v.replace( /[=\s].*$/, "" ) )
	} = {}) {
		return function appliedFn(argsObj) {
			return fn( ...propNamesInOrder.map( k => argsObj[k] ) );
		};
	}

	function gather({ fn, props: propNamesInOrder = [] } = {}) {
		return function gatheredFn(...args) {
			return fn(
				zip( {arr1: propNamesInOrder, arr2: args} )
				.reduce( (obj,[key,val]) => (obj[key] = val, obj), {} )
			);
		};
	}

	function compose({ fns = [] } = {}) {
		return function composed(result){
			// copy the array of functions to prevent side effects
			var list = fns.slice();

			while (list.length > 0) {
				result = list.pop()( result );
			}

			return result;
		};
	}

	function pipe({ fns = [] } = {}) {
		return function piped(result){
			// copy the array of functions to prevent side effects
			var list = fns.slice();

			while (list.length > 0) {
				result = list.shift()( result );
			}

			return result;
		};
	}

	function prop({ name = "v", o: obj = {} } = {}) {
		return obj[name];
	}

	function setProp({ name = "v", o: obj = {}, v: val } = {}) {
		var clone = Object.assign( {}, obj );
		clone[name] = val;
		return clone;
	}

	function filterIn({ fn: predicateFn, arr } = {}) {
		return arr.filter( predicateFn );
	}

	function filterOut({ fn: predicateFn, arr } = {}) {
		return filterIn( complement( predicateFn ), arr );
	}

	function map({ fn: mapperFn, arr } ={}) {
		return arr.map( mapperFn );
	}

	function reduce({ fn: reducerFn, v: initialValue, arr } = {}) {
		return initialValue !== undefined ?
			arr.reduce( reducerFn, initialValue ) :
			arr.reduce( reducerFn );
	}

	function reduceRight({ fn: reducerFn, v: initialValue, arr } = {}) {
		return initialValue !== undefined ?
			arr.reduceRight( reducerFn, initialValue ) :
			arr.reduceRight( reducerFn );
	}

	function zip({ arr1, arr2 } = {}) {
		var zipped = [];
		arr1 = arr1.slice();
		arr2 = arr2.slice();

		while (arr1.length > 0 && arr2.length > 0) {
			zipped.push( [ arr1.shift(), arr2.shift() ] );
		}

		return zipped;
	}

	// ***************************************
	// Private

	function _curry(fn,arity = fn.length) {
		return (function nextCurried(prevArgs){
			return function curried(nextArg){
				var args = prevArgs.concat( [nextArg] );

				if (args.length >= arity) {
					return fn( ...args );
				}
				else {
					return nextCurried( args );
				}
			};
		})( [] );
	}

	function _curryMultiple(fn,arity = fn.length) {
		return (function nextCurried(prevArgs){
			return function curried(...nextArgs){
				var args = prevArgs.concat( nextArgs );

				if (args.length >= arity) {
					return fn( ...args );
				}
				else {
					return nextCurried( args );
				}
			};
		})( [] );
	}

	function _uncurry(fn) {
		return function uncurried(...args){
			var ret = fn;

			for (let i = 0; i < args.length; i++) {
				// assume `fn` is strictly curried (needs one arg at a time),
				// instead of loose/multiple currying
				ret = ret( args[i] );
			}

			return ret;
		};
	}

	function _partial(fn,presetArgs = []) {
		return function partiallyApplied(...laterArgs){
			return fn( ...presetArgs, ...laterArgs );
		};
	}

});
<|endoftext|>