<commit_before>// Load modules

var Events = require('events');
var Stream = require('stream');
var Hoek = require('hoek');
var Vise = require('vise');

// Declare internals

var internals = {};

exports.compile = function (needle) {

    Hoek.assert(needle && needle.length, 'Missing needle');
    Hoek.assert(Buffer.isBuffer(needle), 'Needle must be a buffer');

    var profile = {
        value: needle,
        lastPos: needle.length - 1,
        last: needle[needle.length - 1],
        length: needle.length,
        badCharShift: new Buffer(256)                  // Lookup table of how many characters can be skipped for each match
    };

    for (var i = 0; i < 256; ++i) {
        profile.badCharShift[i] = profile.length;       // Defaults to the full length of the needle
    }

    var last = profile.length - 1;
    for (i = 0; i < last; ++i) {                        // For each character in the needle (skip last since its position is already the default)
        profile.badCharShift[profile.value[i]] = last - i;
    }

    return profile;
};

exports.horspool = function (haystack, needle, start) {

    Hoek.assert(haystack, 'Missing haystack');

    needle = (needle.badCharShift ? needle : exports.compile(needle));
    start = start || 0;

    for (var i = start, il = haystack.length - needle.length; i <= il;) {       // Has enough room to fit the entire needle
        var lastChar = haystack.readUInt8(i + needle.lastPos, true);
        if (lastChar === needle.last &&
            internals.startsWith(haystack, needle, i)) {

            return i;
        }

        i += needle.badCharShift[lastChar];           // Jump to the next possible position based on last character location in needle
    }

    return -1;
};

internals.startsWith = function (haystack, needle, pos) {

    if (haystack.startsWith) {
        return haystack.startsWith(needle.value, pos, needle.lastPos);
    }

    for (var i = 0, il = needle.lastPos; i < il; ++i) {
        if (needle.value[i] !== haystack.readUInt8(pos + i, true)) {
            return false;
        }
    }

    return true;
};

exports.all = function (haystack, needle, start) {

    needle = exports.compile(needle);
    start = start || 0;

    var matches = [];
    for (var hlen = haystack.length, last = start; last !== -1 && last < hlen;) {

        last = exports.horspool(haystack, needle, last);
        if (last !== -1) {
            matches.push(last);
            last += needle.length;
        }
    }

    return matches;
};

internals._indexOf = function (haystack, needle) {

    Hoek.assert(haystack, 'Missing haystack');

    for (var i = 0, il = haystack.length - needle.length; i <= il; ++i) {       // Has enough room to fit the entire needle
        if (haystack.startsWith(needle.value, i)) {
            return i;
        }
    }

    return -1;
};

exports.Stream = internals.Stream = function (needle) {

    var self = this;

    Stream.Writable.call(this);

    this.needle(needle);
    this._haystack = new Vise();
    this._indexOf = this._needle.length > 2 ? exports.horspool : internals._indexOf;

    this.on('finish', function () {

        // Flush out the remainder

        var chunks = self._haystack.chunks();
        for (var i = 0, il = chunks.length; i < il; ++i) {
            self.emit('haystack', chunks[i]);
        }

        setImmediate(function () {                  // Give pending events a chance to fire

            self.emit('close');
        });
    });
};

Hoek.inherits(internals.Stream, Stream.Writable);

internals.Stream.prototype.needle = function (needle) {

    this._needle = exports.compile(needle);
};

internals.Stream.prototype._write = function (chunk, encoding, next) {

    this._haystack.push(chunk);

    var match = this._indexOf(this._haystack, this._needle);
    if (match === -1 &&
        chunk.length >= this._needle.length) {

        this._flush(this._haystack.length - chunk.length);
    }

    while (match !== -1) {
        this._flush(match);
        this._haystack.shift(this._needle.length);
        this.emit('needle');

        match = this._indexOf(this._haystack, this._needle);
    }

    if (this._haystack.length) {
        var notChecked = this._haystack.length - this._needle.length + 1;       // Not enough space for Horspool
        for (var i = notChecked; i < this._haystack.length; ++i) {
            if (this._haystack.startsWith(this._needle.value, i, this._haystack.length - i)) {
                break;
            }
        }

        this._flush(i);
    }

    return next();
};

internals.Stream.prototype._flush = function (pos) {

    var chunks = this._haystack.shift(pos);
    for (var i = 0, il = chunks.length; i < il; ++i) {
        this.emit('haystack', chunks[i]);
    }
};

internals.Stream.prototype.flush = function () {

    var chunks = this._haystack.shift(this._haystack.length);
    for (var i = 0, il = chunks.length; i < il; ++i) {
        this.emit('haystack', chunks[i]);
    }
};
<commit_msg>Adjust whitespace after semicolons to fix tests<commit_after>// Load modules

var Events = require('events');
var Stream = require('stream');
var Hoek = require('hoek');
var Vise = require('vise');

// Declare internals

var internals = {};

exports.compile = function (needle) {

    Hoek.assert(needle && needle.length, 'Missing needle');
    Hoek.assert(Buffer.isBuffer(needle), 'Needle must be a buffer');

    var profile = {
        value: needle,
        lastPos: needle.length - 1,
        last: needle[needle.length - 1],
        length: needle.length,
        badCharShift: new Buffer(256)                  // Lookup table of how many characters can be skipped for each match
    };

    for (var i = 0; i < 256; ++i) {
        profile.badCharShift[i] = profile.length;       // Defaults to the full length of the needle
    }

    var last = profile.length - 1;
    for (i = 0; i < last; ++i) {                        // For each character in the needle (skip last since its position is already the default)
        profile.badCharShift[profile.value[i]] = last - i;
    }

    return profile;
};

exports.horspool = function (haystack, needle, start) {

    Hoek.assert(haystack, 'Missing haystack');

    needle = (needle.badCharShift ? needle : exports.compile(needle));
    start = start || 0;

    for (var i = start, il = haystack.length - needle.length; i <= il; ) {       // Has enough room to fit the entire needle
        var lastChar = haystack.readUInt8(i + needle.lastPos, true);
        if (lastChar === needle.last &&
            internals.startsWith(haystack, needle, i)) {

            return i;
        }

        i += needle.badCharShift[lastChar];           // Jump to the next possible position based on last character location in needle
    }

    return -1;
};

internals.startsWith = function (haystack, needle, pos) {

    if (haystack.startsWith) {
        return haystack.startsWith(needle.value, pos, needle.lastPos);
    }

    for (var i = 0, il = needle.lastPos; i < il; ++i) {
        if (needle.value[i] !== haystack.readUInt8(pos + i, true)) {
            return false;
        }
    }

    return true;
};

exports.all = function (haystack, needle, start) {

    needle = exports.compile(needle);
    start = start || 0;

    var matches = [];
    for (var hlen = haystack.length, last = start; last !== -1 && last < hlen; ) {

        last = exports.horspool(haystack, needle, last);
        if (last !== -1) {
            matches.push(last);
            last += needle.length;
        }
    }

    return matches;
};

internals._indexOf = function (haystack, needle) {

    Hoek.assert(haystack, 'Missing haystack');

    for (var i = 0, il = haystack.length - needle.length; i <= il; ++i) {       // Has enough room to fit the entire needle
        if (haystack.startsWith(needle.value, i)) {
            return i;
        }
    }

    return -1;
};

exports.Stream = internals.Stream = function (needle) {

    var self = this;

    Stream.Writable.call(this);

    this.needle(needle);
    this._haystack = new Vise();
    this._indexOf = this._needle.length > 2 ? exports.horspool : internals._indexOf;

    this.on('finish', function () {

        // Flush out the remainder

        var chunks = self._haystack.chunks();
        for (var i = 0, il = chunks.length; i < il; ++i) {
            self.emit('haystack', chunks[i]);
        }

        setImmediate(function () {                  // Give pending events a chance to fire

            self.emit('close');
        });
    });
};

Hoek.inherits(internals.Stream, Stream.Writable);

internals.Stream.prototype.needle = function (needle) {

    this._needle = exports.compile(needle);
};

internals.Stream.prototype._write = function (chunk, encoding, next) {

    this._haystack.push(chunk);

    var match = this._indexOf(this._haystack, this._needle);
    if (match === -1 &&
        chunk.length >= this._needle.length) {

        this._flush(this._haystack.length - chunk.length);
    }

    while (match !== -1) {
        this._flush(match);
        this._haystack.shift(this._needle.length);
        this.emit('needle');

        match = this._indexOf(this._haystack, this._needle);
    }

    if (this._haystack.length) {
        var notChecked = this._haystack.length - this._needle.length + 1;       // Not enough space for Horspool
        for (var i = notChecked; i < this._haystack.length; ++i) {
            if (this._haystack.startsWith(this._needle.value, i, this._haystack.length - i)) {
                break;
            }
        }

        this._flush(i);
    }

    return next();
};

internals.Stream.prototype._flush = function (pos) {

    var chunks = this._haystack.shift(pos);
    for (var i = 0, il = chunks.length; i < il; ++i) {
        this.emit('haystack', chunks[i]);
    }
};

internals.Stream.prototype.flush = function () {

    var chunks = this._haystack.shift(this._haystack.length);
    for (var i = 0, il = chunks.length; i < il; ++i) {
        this.emit('haystack', chunks[i]);
    }
};
<|endoftext|>


<commit_before>'use strict';
var path = require('path');
var childProcess = require('child_process');
var BinWrapper = require('bin-wrapper');
var osFilterObj = require('os-filter-obj');
var pathExists = require('path-exists');

var VERSION = '0.4.0';
var BASE = 'https://github.com/facebook/infer/releases/download/v' + VERSION + '/';

var binWrapper = new BinWrapper()
	.src(BASE + 'infer-osx-v' + VERSION + '.tar.xz', 'darwin')
	.src(BASE + 'infer-linux64-v' + VERSION + '.tar.xz', 'linux', 'x64')
	.dest(path.join(__dirname, '../vendor'))
	.use(path.join('infer', 'bin', 'infer'));

// super ugly hack to work around `bin-wrapper` limitations
var get = binWrapper.get.bind(binWrapper);
binWrapper.get = function (cb) {
	get(function () {
		var filename = path.basename(osFilterObj(this.src())[0].url.replace(/https:\/\//, ''));

		if (pathExists.sync(path.join(__dirname, '../vendor', 'infer'))) {
			cb();
			return;
		}

		childProcess.execFile('tar', [
			'--strip-components=1',
			'--extract',
			'--file', filename
		], {
			cwd: path.join(__dirname, '../vendor')
		}, function (err) {
			if (err) {
				throw err;
			}

			cb();
		});
	}.bind(this));
};

module.exports = binWrapper;
<commit_msg>:arrow_up: infer@0.5.0<commit_after>'use strict';
var path = require('path');
var childProcess = require('child_process');
var BinWrapper = require('bin-wrapper');
var osFilterObj = require('os-filter-obj');
var pathExists = require('path-exists');

var VERSION = '0.5.0';
var BASE = 'https://github.com/facebook/infer/releases/download/v' + VERSION + '/';

var binWrapper = new BinWrapper()
	.src(BASE + 'infer-osx-v' + VERSION + '.tar.xz', 'darwin')
	.src(BASE + 'infer-linux64-v' + VERSION + '.tar.xz', 'linux', 'x64')
	.dest(path.join(__dirname, '../vendor'))
	.use(path.join('infer', 'bin', 'infer'));

// super ugly hack to work around `bin-wrapper` limitations
var get = binWrapper.get.bind(binWrapper);
binWrapper.get = function (cb) {
	get(function () {
		var filename = path.basename(osFilterObj(this.src())[0].url.replace(/https:\/\//, ''));

		if (pathExists.sync(path.join(__dirname, '../vendor', 'infer'))) {
			cb();
			return;
		}

		childProcess.execFile('tar', [
			'--strip-components=1',
			'--extract',
			'--file', filename
		], {
			cwd: path.join(__dirname, '../vendor')
		}, function (err) {
			if (err) {
				throw err;
			}

			cb();
		});
	}.bind(this));
};

module.exports = binWrapper;
<|endoftext|>


<commit_before>var path = require('path');
var fs = require('fs');
var koaStatic = require('./koa-static');
var Compressor = require('./compressor');
var htmlTags = require('./html-tags');

/**
 * serve assets and compress js/css
 *
 * @param {Object} server    koa app object
 * @param {String} rootPath  root path of your web app
 * @param {Object} options   koa-assets-minify module options
 */
module.exports = function assetsMinify(server, rootPath, options) {
  // complete options
  var defaults = {
    assetsPath: 'assets',
    tempPath: 'tmp',
    maxBuffer: 2000 * 1024,
    maxAge: 24* 3600 * 1000,
    baseUrl: '',

    compression: false,
    js: {},
    css: {}
  };

  options = options || defaults;
  options.assetsPath = options.assetsPath || defaults.assetsPath;
  options.tempPath = options.tempPath || defaults.tempPath;
  options.maxBuffer = options.maxBuffer || defaults.maxBuffer;
  options.maxAge = options.maxAge || defaults.maxAge;
  options.baseUrl = options.baseUrl || defaults.baseUrl;
  options.rootPath = rootPath;

  var compressor = new Compressor(options);

  if (options.compression) {
    server.use(compressor.assets());

    compressor.prepare(function() {
      compressor.run(function(err) {
        if (err) {
          console.trace(err);
        }

        console.log('Assets compression finished!');
      });
    });
  } else {
    server.use(koaStatic(assetsPath, { maxage: options.maxAge }));
  }

  // set assets which will be used in views
  server.use(function* (next) {
    var ctx = this.state;
    var assets;

    if (options.compression) {
      assets = yield compressor.loadAssetsJsonFile();
    } else {
      assets.js = options.js;
      assets.css = options.css;
    }

    ctx.assets = htmlTags(assets, options.baseUrl);

    yield next;
  });
};<commit_msg>fix bug when compression is false<commit_after>var path = require('path');
var fs = require('fs');
var koaStatic = require('./koa-static');
var Compressor = require('./compressor');
var htmlTags = require('./html-tags');

/**
 * serve assets and compress js/css
 *
 * @param {Object} server    koa app object
 * @param {String} rootPath  root path of your web app
 * @param {Object} options   koa-assets-minify module options
 */
module.exports = function assetsMinify(server, rootPath, options) {
  // complete options
  var defaults = {
    assetsPath: 'assets',
    tempPath: 'tmp',
    maxBuffer: 2000 * 1024,
    maxAge: 24* 3600 * 1000,
    baseUrl: '',

    compression: false,
    js: {},
    css: {}
  };

  options = options || defaults;
  options.assetsPath = options.assetsPath || defaults.assetsPath;
  options.tempPath = options.tempPath || defaults.tempPath;
  options.maxBuffer = options.maxBuffer || defaults.maxBuffer;
  options.maxAge = options.maxAge || defaults.maxAge;
  options.baseUrl = options.baseUrl || defaults.baseUrl;
  options.rootPath = rootPath;

  var compressor = new Compressor(options);

  if (options.compression) {
    server.use(compressor.assets());

    compressor.prepare(function() {
      compressor.run(function(err) {
        if (err) {
          console.trace(err);
        }

        console.log('Assets compression finished!');
      });
    });
  } else {
    server.use(koaStatic(options.assetsPath, { maxage: options.maxAge }));
  }

  // set assets which will be used in views
  server.use(function* (next) {
    var ctx = this.state;
    var assets = {};

    if (options.compression) {
      assets = yield compressor.loadAssetsJsonFile();
    } else {
      assets.js = options.js;
      assets.css = options.css;
    }

    ctx.assets = htmlTags(assets, options.baseUrl);

    yield next;
  });
};<|endoftext|>


<commit_before>var fs = require('fs');
var ff = require('ff');
var path = require('path');
var Rsync = require('rsync');

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

var lockFile = require('../util/lockfile');
var rimraf = require('../util/rimraf');
var gitClient = require('../util/gitClient');
var logger = require('../util/logging').get('apps');
var stringify = require('../util/stringify');

var _exists = require('../util/exists');
var exists = _exists.exists;
var IOError = exists.IOError;

var LOCK_FILE = 'devkit.lock';

var APP_TEMPLATE_ROOT = path.join(__dirname, 'templates');
var DEFAULT_TEMPLATE = 'default';

var App = module.exports = Class(function () {

  this.init = function (root, manifest, lastOpened) {
    this.paths = {
      root: root,
      build: path.join(root, 'build'),
      shared: path.join(root, 'shared'),
      src: path.join(root, 'src'),
      modules: path.join(root, 'modules'),
      resources: path.join(root, 'resources'),
      icons: path.join(root, 'resources', 'icons'),
      lang: path.join(root, 'resources', 'lang'),
      manifest: path.join(root, 'manifest.json')
    };

    this.manifest = manifest || {};
    this._dependencies = this._parseDeps();
    this.lastOpened = lastOpened || Date.now();
  };

  this.getModules = function () {
    if (!this._modules) {
      this._loadModules();
    }

    return this._modules;
  };

  this.removeModules = function (toRemove) {
    toRemove.forEach(function (moduleName) {
      delete this._modules[moduleName];
    }, this);
  };

  this.getClientPaths = function () {
    var appPath = this.paths.root;
    var paths = {'*': []};
    Object.keys(this.getModules()).forEach(function (moduleName) {
      var module = this._modules[moduleName];
      var clientPaths = module.getClientPaths();
      for (var key in clientPaths) {
        var p = path.relative(
          appPath, path.resolve(module.path, clientPaths[key])
        );
        if (key === '*') {
          paths[key] = paths[key].concat(p);
        } else {
          paths[key] = p;
        }
      }
    }, this);

    return paths;
  };

  // assuming app is loaded, reload the manifest and modules synchronously
  this.reloadSync = function () {
    if (!fs.existsSync(this.paths.manifest)) {
      // app does not exist anymore?
      require('./index').unload(this.paths.root);
    } else {
      logger.log(this.paths.manifest);
      try {
        this.manifest = JSON.parse(
          fs.readFileSync(this.paths.manifest, 'utf8')
        );
      } catch (e) {
        logger.error('Error loading and parsing manifest at',
                     this.paths.manifest);
        throw e;
      }
      if (this._modules) {
        this.reloadModules();
      }
    }
  };

  this.reloadModules = function () {
    this._modules = {};
    this._loadModules();
  };

  this._loadModules = function () {
    if (!this._modules) {
      this._modules = {};
    }

    var _queue = [];

    function addToQueue(parentPath) {
      function scanDir(basePath) {
        try {
          return fs.readdirSync(basePath)
            .map(function (item) {
              return {
                path: path.join(basePath, item),
                parent: parentPath
              };
            });

        } catch (e) {}
      }

      _queue.push.apply(_queue, scanDir(path.join(parentPath, 'modules')));
      _queue.push.apply(_queue, scanDir(path.join(parentPath, 'node_modules')));
    }

    addToQueue(this.paths.root);

    while (_queue[0]) {
      var item = _queue.shift();
      var modulePath = path.resolve(this.paths.root, item.path);
      var parentPath = path.resolve(this.paths.root, item.parent);
      var packageFile = path.join(modulePath, 'package.json');

      if (!fs.existsSync(packageFile)) { continue; }

      var packageContents;
      try {
        packageContents = require(packageFile);
      } catch (e) {
        return logger.warn('Module', item.path, 'failed to load');
      }

      if (!packageContents.devkit) { continue; }

      var existingModule = this._modules[packageContents.name];
      if (existingModule) {
        if (existingModule.version !== packageContents.version) {
          throw new Error(
            packageContents.name +
            ' included twice with different versions:\n' +
            existingModule.version + ': ' + existingModule.path + '\n' +
            packageContents.version + ': ' + modulePath);
        }
      } else {
        var name = path.basename(modulePath);
        var version = null;
        var isDependency = (this.paths.root === parentPath);
        if (isDependency && this._dependencies[name]) {
          version = this._dependencies[name].version;
        }

        this._modules[name] = new Module({
          name: name,
          path: modulePath,
          parent: parentPath,
          isDependency: isDependency,
          version: version,
          packageContents: packageContents
        });
      }

      addToQueue(modulePath);
    }
  };

  this.getDependency = function (name) {
    return this._dependencies[name];
  };

  this._parseDeps = function () {
    var deps = {};
    var src = this.manifest.dependencies;
    for (var name in src) {
      var url = src[name];
      var pieces = url.split('#', 2);
      deps[name] = {
        url: pieces[0],
        version: pieces[1]
      };
    }

    return deps;
  };

  this._stringifyDeps = function () {
    var deps = this.manifest.dependencies = {};
    Object.keys(this._dependencies).forEach(function (name) {
      var dep = this._dependencies[name];
      deps[name] = (dep.url || '') + '#' + (dep.version || '');
    }, this);
  };

  /* Manifest */

  function createUUID (a) {
    return a ?
      (a ^ Math.random() * 16 >> a / 4).toString(16) :
      ([1e7]+1e3+4e3+8e3+1e11).replace(/[018]/g, createUUID);
  }

  var DEFAULT_PROTOCOL = 'https';
  var REQUIRED_DEPS = [
    {
      name: 'devkit-core',
      ssh: 'git@github.com:',
      https: 'https://github.com/',
      repo: 'gameclosure/devkit-core',
      tag: ''
    }
  ];

  function getRequiredDeps(protocol) {
    protocol = protocol === 'ssh' ? 'ssh' : 'https';

    var out = {};
    REQUIRED_DEPS.forEach(function (dep) {
      out[dep.name] = dep[protocol] + dep.repo + (dep.tag ? '#' + dep.tag : '');
    });
    return out;
  }

  this.validate = function (opts, cb) {
    if (typeof opts === 'function') {
      cb = opts;
      opts = {};
    }

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

    var defaults = {
      appID: createUUID(),
      shortName: opts.shortName || '',
      title: opts.title || opts.shortName || '',

      studio: {
        name: 'Your Studio Name',
        domain: 'studio.example.com',
        stagingDomain: 'staging.example.com'
      },

      supportedOrientations: [
        'portrait',
        'landscape'
      ],

      dependencies: {}
    };

    var changed = false;
    var key;

    // create defaults for anything missing
    for (key in defaults) {
      if (!(key in this.manifest)) {
        this.manifest[key] = defaults[key];
        changed = true;
      }
    }

    // ensure required dependencies are set
    var requiredDeps = getRequiredDeps(opts.protocol || 'https');
    for (key in requiredDeps) {
      if (!(key in this.manifest.dependencies)) {
        this.manifest.dependencies[key] = requiredDeps[key];
        changed = true;
      }
    }

    // if manifest has been changed, save it and update dependencies
    if (changed) {
      this._dependencies = this._parseDeps();
      this._stringifyDeps();
      return this.saveManifest(cb);
    } else {
      return Promise.delay(0).nodeify(cb);
    }
  };

  this.setModuleVersion = function (moduleName, version, cb) {
    return this.validate(null).bind(this).then(function () {
      var dep = this._dependencies[moduleName];
      if (dep && dep.version !== version) {
        dep.version = version;
      }
    }).nodeify(cb);
  };

  this.addDependency = function (name, opts, cb) {
    var dep = this._dependencies[name];
    var changed = false;
    if (!dep) {
      this._dependencies[name] = dep = {};
      changed = true;
    }

    if (opts.url) {
      dep.url = opts.url;
      changed = true;
    }

    if (opts.version) {
      dep.version = opts.version;
      changed = true;
    }

    var write = bind(this, function () {
      this._stringifyDeps();
      this.saveManifest(cb);
    });

    if (!dep.url) {
      Module.getURL(path.join(this.paths.modules, name), function (err, url) {
        if (!err) { dep.url = url; }
        write();
      });
    } else if (changed) {
      write();
    } else {
      cb && process.nextTick(cb);
    }
  };

  this.removeDependency = function (name, cb) {
    var promises = [];
    // remove from manifest dependencies
    if (this._dependencies[name]) {
      logger.log('removing dependency from manifest...');
      delete this._dependencies[name];
      this._stringifyDeps();
      promises.push(this.saveManifest());
    }

    // remove from file system
    var modulePath = path.join(this.paths.modules, name);
    if (fs.existsSync(modulePath)) {
      logger.log('removing module directory...');
      promises.push(rimraf(modulePath));
    }

    return Promise.all(promises).nodeify(cb);
  };

  this.saveManifest = function (cb) {
    trace('App#saveManifest');
    var writeFile = Promise.promisify(fs.writeFile);
    var data = stringify(this.manifest);
    return writeFile(path.join(this.paths.manifest), data).nodeify(cb);
  };

  this.getPackageName = function() {
    var studio = this.manifest.studio;
    if (studio && studio.domain && this.manifest.shortName) {
      return printf('%(reversedDomain)s.%(shortName)s', {
        reversedDomain: studio.domain.split(/\./g).reverse().join('.'),
        shortName: this.manifest.shortName
      });
    }
    return '';
  };

  this.getId = function () {
    return this.manifest.appID.toLowerCase();
  };

  this.getIcon = function (targetSize) {
    return this.manifest.icon
      || getIcon(this.manifest.android && this.manifest.android.icons,
                 targetSize)
      || getIcon(this.manifest.ios && this.manifest.ios.icons, targetSize)
      || '/images/defaultIcon.png';

    function getIcon(iconList, targetSize) {
      var sizes = [], closest = null;

      if (iconList) {
        for (var size in iconList) {
          var numSize = parseInt(size);
          if (!Number.isNaN(numSize) && numSize.toString() === size) {
            sizes.push(numSize);
          } else {
            logger.warn('Non integer icon size encountered:', size);
          }
        }

        sizes.sort(function (a, b) { return a < b ? -1 : 1; });

        for (var i = sizes.length - 1; i >= 0; i--) {
          if (sizes[i] <= targetSize) {
            return iconList[sizes[i]];
          }
        }

        if (sizes.length) {
          return iconList[sizes.pop()];
        }
      }

      return null;
    }
  };

  this.createFromTemplate = function (template, cb) {

    if (!template.type) {
      logger.log('Creating app using default template');
      return this.createFromDefaultTemplate().nodeify(cb);
    }

    // if template is local file, copy it
    if (template.type === 'local') {
      // TODO: support expanding user home dir and other shortcuts
      templatePath = path.normalize(template.path);
      if (fs.existsSync(templatePath) &&
          fs.lstatSync(templatePath).isDirectory()) {
        logger.log('Creating app using local template ' + templatePath);
        return this._copyLocalTemplate(templatePath, cb);
      } else {
        logger.warn('Failed to find template ' + templatePath);
        return this.createFromDefaultTemplate(cb);
      }
    } else if (template.type === 'git') {
      // if template is not a local path, attempt to clone it
      var tempPath = path.join(APP_TEMPLATE_ROOT, '_template');

      return exists(tempPath).then(function () {
        trace('tempPath exists - removing');
        return rimraf(tempPath);
      }).catch(IOError, function (err) {
        trace('tempPath does not exist - OK');
      }).then(function () {
        // shallow clone the repository
        logger.log('Creating app using remote template ' + template.path);
        var git = gitClient.get(APP_TEMPLATE_ROOT);
        return git('clone', '--depth', '1', template.path, tempPath);
      }).then(function () {
        logger.log('Copying ' + tempPath + ' to ' + this.paths.root);
        return this._copyLocalTemplate(tempPath, f.wait());
      }).catch(FatalGitError, function (err) {
        logger.error(err.message);
        logger.log('Falling back to default template creation');
        return this.createFromDefaultTemplate();
      }).finally(function () {
        if (fs.existsSync(tempPath)) {
          return rimraf(tempPath);
        }
      }).nodeify(cb);

    } else if (template.type === 'none') {
      logger.log('Creating application with no template');
      return Promise.resolve().nodeify(cb);
    } else {
      // create local
      logger.error('Invalid template - using default');
      return this.createFromDefaultTemplate().nodeify(cb);
    }
  };

  this.createFromDefaultTemplate = function (cb) {
    logger.log('Creating app using default application template');
    var templatePath = path.join(APP_TEMPLATE_ROOT, DEFAULT_TEMPLATE);
    return this._copyLocalTemplate(templatePath, cb);
  };

  this._copyLocalTemplate = function (templatePath, cb) {
    // read every file/folder in the template
    var projectRoot = this.paths.root;
    var templateFileList = fs.readdirSync(templatePath);
    return Promise.each(templateFileList, function () {
      // don't copy .git files
      if (child === '.git') {
        return;
      }

      // copy the file/folder recursively to the new app
      return new Promise(function (resolve, reject) {
        new Rsync()
        .flags('r')
        .source(path.join(templatePath,child))
        .destination(projectRoot)
        .execute(function (err, code, cmd) {
          if (!err) { return resolve(); }
          reject(new Error('Error during ' + cmd));
        });
      });
    }).nodeify(cb);
  };

  this.acquireLock = function (cb) {
    return lockFile.lock(path.join(this.paths.root, LOCK_FILE), cb);
  };

  this.releaseLock = function (cb) {
    return lockFile.unlock(path.join(this.paths.root, LOCK_FILE), cb);
  };

  // defines the public JSON API for DevKit extensions
  this.toJSON = function () {
    var modules = {};
    Object.keys(this.getModules()).forEach(function (moduleName) {
      modules[moduleName] = this._modules[moduleName].toJSON();
    }, this);

    return {
        'id': this.paths.root,
        'lastOpened': this.lastOpened,
        'appId': this.getId(),
        'modules': modules,
        'clientPaths': this.getClientPaths(),
        'paths': merge({}, this.paths),
        'manifest': this.manifest,
        'title': this.manifest.title
      };
  };
});
<commit_msg>Fix reference error in App.js<commit_after>var fs = require('fs');
var ff = require('ff');
var path = require('path');
var Rsync = require('rsync');

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

var lockFile = require('../util/lockfile');
var rimraf = require('../util/rimraf');
var gitClient = require('../util/gitClient');
var logger = require('../util/logging').get('apps');
var stringify = require('../util/stringify');

var _exists = require('../util/exists');
var exists = _exists.exists;
var IOError = _exists.IOError;

var LOCK_FILE = 'devkit.lock';

var APP_TEMPLATE_ROOT = path.join(__dirname, 'templates');
var DEFAULT_TEMPLATE = 'default';

var App = module.exports = Class(function () {

  this.init = function (root, manifest, lastOpened) {
    this.paths = {
      root: root,
      build: path.join(root, 'build'),
      shared: path.join(root, 'shared'),
      src: path.join(root, 'src'),
      modules: path.join(root, 'modules'),
      resources: path.join(root, 'resources'),
      icons: path.join(root, 'resources', 'icons'),
      lang: path.join(root, 'resources', 'lang'),
      manifest: path.join(root, 'manifest.json')
    };

    this.manifest = manifest || {};
    this._dependencies = this._parseDeps();
    this.lastOpened = lastOpened || Date.now();
  };

  this.getModules = function () {
    if (!this._modules) {
      this._loadModules();
    }

    return this._modules;
  };

  this.removeModules = function (toRemove) {
    toRemove.forEach(function (moduleName) {
      delete this._modules[moduleName];
    }, this);
  };

  this.getClientPaths = function () {
    var appPath = this.paths.root;
    var paths = {'*': []};
    Object.keys(this.getModules()).forEach(function (moduleName) {
      var module = this._modules[moduleName];
      var clientPaths = module.getClientPaths();
      for (var key in clientPaths) {
        var p = path.relative(
          appPath, path.resolve(module.path, clientPaths[key])
        );
        if (key === '*') {
          paths[key] = paths[key].concat(p);
        } else {
          paths[key] = p;
        }
      }
    }, this);

    return paths;
  };

  // assuming app is loaded, reload the manifest and modules synchronously
  this.reloadSync = function () {
    if (!fs.existsSync(this.paths.manifest)) {
      // app does not exist anymore?
      require('./index').unload(this.paths.root);
    } else {
      logger.log(this.paths.manifest);
      try {
        this.manifest = JSON.parse(
          fs.readFileSync(this.paths.manifest, 'utf8')
        );
      } catch (e) {
        logger.error('Error loading and parsing manifest at',
                     this.paths.manifest);
        throw e;
      }
      if (this._modules) {
        this.reloadModules();
      }
    }
  };

  this.reloadModules = function () {
    this._modules = {};
    this._loadModules();
  };

  this._loadModules = function () {
    if (!this._modules) {
      this._modules = {};
    }

    var _queue = [];

    function addToQueue(parentPath) {
      function scanDir(basePath) {
        try {
          return fs.readdirSync(basePath)
            .map(function (item) {
              return {
                path: path.join(basePath, item),
                parent: parentPath
              };
            });

        } catch (e) {}
      }

      _queue.push.apply(_queue, scanDir(path.join(parentPath, 'modules')));
      _queue.push.apply(_queue, scanDir(path.join(parentPath, 'node_modules')));
    }

    addToQueue(this.paths.root);

    while (_queue[0]) {
      var item = _queue.shift();
      var modulePath = path.resolve(this.paths.root, item.path);
      var parentPath = path.resolve(this.paths.root, item.parent);
      var packageFile = path.join(modulePath, 'package.json');

      if (!fs.existsSync(packageFile)) { continue; }

      var packageContents;
      try {
        packageContents = require(packageFile);
      } catch (e) {
        return logger.warn('Module', item.path, 'failed to load');
      }

      if (!packageContents.devkit) { continue; }

      var existingModule = this._modules[packageContents.name];
      if (existingModule) {
        if (existingModule.version !== packageContents.version) {
          throw new Error(
            packageContents.name +
            ' included twice with different versions:\n' +
            existingModule.version + ': ' + existingModule.path + '\n' +
            packageContents.version + ': ' + modulePath);
        }
      } else {
        var name = path.basename(modulePath);
        var version = null;
        var isDependency = (this.paths.root === parentPath);
        if (isDependency && this._dependencies[name]) {
          version = this._dependencies[name].version;
        }

        this._modules[name] = new Module({
          name: name,
          path: modulePath,
          parent: parentPath,
          isDependency: isDependency,
          version: version,
          packageContents: packageContents
        });
      }

      addToQueue(modulePath);
    }
  };

  this.getDependency = function (name) {
    return this._dependencies[name];
  };

  this._parseDeps = function () {
    var deps = {};
    var src = this.manifest.dependencies;
    for (var name in src) {
      var url = src[name];
      var pieces = url.split('#', 2);
      deps[name] = {
        url: pieces[0],
        version: pieces[1]
      };
    }

    return deps;
  };

  this._stringifyDeps = function () {
    var deps = this.manifest.dependencies = {};
    Object.keys(this._dependencies).forEach(function (name) {
      var dep = this._dependencies[name];
      deps[name] = (dep.url || '') + '#' + (dep.version || '');
    }, this);
  };

  /* Manifest */

  function createUUID (a) {
    return a ?
      (a ^ Math.random() * 16 >> a / 4).toString(16) :
      ([1e7]+1e3+4e3+8e3+1e11).replace(/[018]/g, createUUID);
  }

  var DEFAULT_PROTOCOL = 'https';
  var REQUIRED_DEPS = [
    {
      name: 'devkit-core',
      ssh: 'git@github.com:',
      https: 'https://github.com/',
      repo: 'gameclosure/devkit-core',
      tag: ''
    }
  ];

  function getRequiredDeps(protocol) {
    protocol = protocol === 'ssh' ? 'ssh' : 'https';

    var out = {};
    REQUIRED_DEPS.forEach(function (dep) {
      out[dep.name] = dep[protocol] + dep.repo + (dep.tag ? '#' + dep.tag : '');
    });
    return out;
  }

  this.validate = function (opts, cb) {
    if (typeof opts === 'function') {
      cb = opts;
      opts = {};
    }

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

    var defaults = {
      appID: createUUID(),
      shortName: opts.shortName || '',
      title: opts.title || opts.shortName || '',

      studio: {
        name: 'Your Studio Name',
        domain: 'studio.example.com',
        stagingDomain: 'staging.example.com'
      },

      supportedOrientations: [
        'portrait',
        'landscape'
      ],

      dependencies: {}
    };

    var changed = false;
    var key;

    // create defaults for anything missing
    for (key in defaults) {
      if (!(key in this.manifest)) {
        this.manifest[key] = defaults[key];
        changed = true;
      }
    }

    // ensure required dependencies are set
    var requiredDeps = getRequiredDeps(opts.protocol || 'https');
    for (key in requiredDeps) {
      if (!(key in this.manifest.dependencies)) {
        this.manifest.dependencies[key] = requiredDeps[key];
        changed = true;
      }
    }

    // if manifest has been changed, save it and update dependencies
    if (changed) {
      this._dependencies = this._parseDeps();
      this._stringifyDeps();
      return this.saveManifest(cb);
    } else {
      return Promise.delay(0).nodeify(cb);
    }
  };

  this.setModuleVersion = function (moduleName, version, cb) {
    return this.validate(null).bind(this).then(function () {
      var dep = this._dependencies[moduleName];
      if (dep && dep.version !== version) {
        dep.version = version;
      }
    }).nodeify(cb);
  };

  this.addDependency = function (name, opts, cb) {
    var dep = this._dependencies[name];
    var changed = false;
    if (!dep) {
      this._dependencies[name] = dep = {};
      changed = true;
    }

    if (opts.url) {
      dep.url = opts.url;
      changed = true;
    }

    if (opts.version) {
      dep.version = opts.version;
      changed = true;
    }

    var write = bind(this, function () {
      this._stringifyDeps();
      this.saveManifest(cb);
    });

    if (!dep.url) {
      Module.getURL(path.join(this.paths.modules, name), function (err, url) {
        if (!err) { dep.url = url; }
        write();
      });
    } else if (changed) {
      write();
    } else {
      cb && process.nextTick(cb);
    }
  };

  this.removeDependency = function (name, cb) {
    var promises = [];
    // remove from manifest dependencies
    if (this._dependencies[name]) {
      logger.log('removing dependency from manifest...');
      delete this._dependencies[name];
      this._stringifyDeps();
      promises.push(this.saveManifest());
    }

    // remove from file system
    var modulePath = path.join(this.paths.modules, name);
    if (fs.existsSync(modulePath)) {
      logger.log('removing module directory...');
      promises.push(rimraf(modulePath));
    }

    return Promise.all(promises).nodeify(cb);
  };

  this.saveManifest = function (cb) {
    trace('App#saveManifest');
    var writeFile = Promise.promisify(fs.writeFile);
    var data = stringify(this.manifest);
    return writeFile(path.join(this.paths.manifest), data).nodeify(cb);
  };

  this.getPackageName = function() {
    var studio = this.manifest.studio;
    if (studio && studio.domain && this.manifest.shortName) {
      return printf('%(reversedDomain)s.%(shortName)s', {
        reversedDomain: studio.domain.split(/\./g).reverse().join('.'),
        shortName: this.manifest.shortName
      });
    }
    return '';
  };

  this.getId = function () {
    return this.manifest.appID.toLowerCase();
  };

  this.getIcon = function (targetSize) {
    return this.manifest.icon
      || getIcon(this.manifest.android && this.manifest.android.icons,
                 targetSize)
      || getIcon(this.manifest.ios && this.manifest.ios.icons, targetSize)
      || '/images/defaultIcon.png';

    function getIcon(iconList, targetSize) {
      var sizes = [], closest = null;

      if (iconList) {
        for (var size in iconList) {
          var numSize = parseInt(size);
          if (!Number.isNaN(numSize) && numSize.toString() === size) {
            sizes.push(numSize);
          } else {
            logger.warn('Non integer icon size encountered:', size);
          }
        }

        sizes.sort(function (a, b) { return a < b ? -1 : 1; });

        for (var i = sizes.length - 1; i >= 0; i--) {
          if (sizes[i] <= targetSize) {
            return iconList[sizes[i]];
          }
        }

        if (sizes.length) {
          return iconList[sizes.pop()];
        }
      }

      return null;
    }
  };

  this.createFromTemplate = function (template, cb) {

    if (!template.type) {
      logger.log('Creating app using default template');
      return this.createFromDefaultTemplate().nodeify(cb);
    }

    // if template is local file, copy it
    if (template.type === 'local') {
      // TODO: support expanding user home dir and other shortcuts
      templatePath = path.normalize(template.path);
      if (fs.existsSync(templatePath) &&
          fs.lstatSync(templatePath).isDirectory()) {
        logger.log('Creating app using local template ' + templatePath);
        return this._copyLocalTemplate(templatePath, cb);
      } else {
        logger.warn('Failed to find template ' + templatePath);
        return this.createFromDefaultTemplate(cb);
      }
    } else if (template.type === 'git') {
      // if template is not a local path, attempt to clone it
      var tempPath = path.join(APP_TEMPLATE_ROOT, '_template');

      return exists(tempPath).then(function () {
        trace('tempPath exists - removing');
        return rimraf(tempPath);
      }).catch(IOError, function (err) {
        trace('tempPath does not exist - OK');
      }).then(function () {
        // shallow clone the repository
        logger.log('Creating app using remote template ' + template.path);
        var git = gitClient.get(APP_TEMPLATE_ROOT);
        return git('clone', '--depth', '1', template.path, tempPath);
      }).then(function () {
        logger.log('Copying ' + tempPath + ' to ' + this.paths.root);
        return this._copyLocalTemplate(tempPath, f.wait());
      }).catch(FatalGitError, function (err) {
        logger.error(err.message);
        logger.log('Falling back to default template creation');
        return this.createFromDefaultTemplate();
      }).finally(function () {
        if (fs.existsSync(tempPath)) {
          return rimraf(tempPath);
        }
      }).nodeify(cb);

    } else if (template.type === 'none') {
      logger.log('Creating application with no template');
      return Promise.resolve().nodeify(cb);
    } else {
      // create local
      logger.error('Invalid template - using default');
      return this.createFromDefaultTemplate().nodeify(cb);
    }
  };

  this.createFromDefaultTemplate = function (cb) {
    logger.log('Creating app using default application template');
    var templatePath = path.join(APP_TEMPLATE_ROOT, DEFAULT_TEMPLATE);
    return this._copyLocalTemplate(templatePath, cb);
  };

  this._copyLocalTemplate = function (templatePath, cb) {
    // read every file/folder in the template
    var projectRoot = this.paths.root;
    var templateFileList = fs.readdirSync(templatePath);
    return Promise.each(templateFileList, function () {
      // don't copy .git files
      if (child === '.git') {
        return;
      }

      // copy the file/folder recursively to the new app
      return new Promise(function (resolve, reject) {
        new Rsync()
        .flags('r')
        .source(path.join(templatePath,child))
        .destination(projectRoot)
        .execute(function (err, code, cmd) {
          if (!err) { return resolve(); }
          reject(new Error('Error during ' + cmd));
        });
      });
    }).nodeify(cb);
  };

  this.acquireLock = function (cb) {
    return lockFile.lock(path.join(this.paths.root, LOCK_FILE), cb);
  };

  this.releaseLock = function (cb) {
    return lockFile.unlock(path.join(this.paths.root, LOCK_FILE), cb);
  };

  // defines the public JSON API for DevKit extensions
  this.toJSON = function () {
    var modules = {};
    Object.keys(this.getModules()).forEach(function (moduleName) {
      modules[moduleName] = this._modules[moduleName].toJSON();
    }, this);

    return {
        'id': this.paths.root,
        'lastOpened': this.lastOpened,
        'appId': this.getId(),
        'modules': modules,
        'clientPaths': this.getClientPaths(),
        'paths': merge({}, this.paths),
        'manifest': this.manifest,
        'title': this.manifest.title
      };
  };
});
<|endoftext|>


<commit_before>var request = require("request");
var events = require('events');
var util = require('util');
var Q = require('q');
var _ = require('lodash');

var Client = function(config) {
    events.EventEmitter.call(this);

    this.set(config);
};
util.inherits(Client, events.EventEmitter);

// Update configuration
Client.prototype.set = function(config) {
    this.config = _.extend({
        'host': null,
        'auth': null
    },
    this.config || {},
    config || {});

    this.http = request.defaults({
        'auth': this.config.auth,
        'json': true,
        'headers': {
            'User-Agent': 'reportr-node'
        },
        'strictSSL': false,
    });
};

Client.prototype.request = function(mode, method, args) {
    var that = this;
    var deferred = Q.defer();

    this.http[mode.toLowerCase()](this.config.host+"/api/"+method, {
        'form': args
    }, function (error, response, body) {
        if (!error && response.statusCode == 200) {
            deferred.resolve(body);
        } else {
            that.emit("apierror", error, body);
            if (body && body.error) error = new Error(body.error);
            error = error || new Error(JSON.stringify(body));
            deferred.reject(error);
        }
    });

    return deferred.promise;
};

// Post an event
Client.prototype.postEvent = function(name, properties) {
    return this.request("POST", "events", {
        'type': name,
        'properties': properties
    });
};

module.exports = Client;

<commit_msg>Fix encoding of arguments<commit_after>var request = require("request");
var events = require('events');
var util = require('util');
var Q = require('q');
var _ = require('lodash');
var querystring = require('querystring');

var Client = function(config) {
    events.EventEmitter.call(this);

    this.set(config);
};
util.inherits(Client, events.EventEmitter);

// Update configuration
Client.prototype.set = function(config) {
    this.config = _.extend({
        'host': null,
        'auth': null
    },
    this.config || {},
    config || {});

    this.http = request.defaults({
        'auth': this.config.auth,
        'json': true,
        'headers': {
            'User-Agent': 'reportr-node'
        },
        'strictSSL': false,
    });
};

Client.prototype.request = function(mode, method, args) {
    var that = this;
    var deferred = Q.defer();
    mode = mode.toLowerCase();

    if (mode == "get" && args) {
        method = method+"?"+querystring.stringify(args);
    }

    console.log(mode, method, JSON.stringify(args));
    this.http[mode](this.config.host+"/api/"+method, {
        'body': args
    }, function (error, response, body) {
        if (!error && response.statusCode == 200) {
            deferred.resolve(body);
        } else {
            that.emit("apierror", error, body);
            if (body && body.error) error = new Error(body.error);
            error = error || new Error(JSON.stringify(body));
            deferred.reject(error);
        }
    });

    return deferred.promise;
};

// Post an event
Client.prototype.postEvent = function(name, properties) {
    return this.request("POST", "events", {
        'type': name,
        'properties': properties
    });
};

module.exports = Client;

<|endoftext|>


<commit_before>!function(e,t){if("object"==typeof exports&&"object"==typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{var r=t();for(var i in r)("object"==typeof exports?exports:e)[i]=r[i]}}(this,function(){return function(e){function t(i){if(r[i])return r[i].exports;var a=r[i]={i:i,l:!1,exports:{}};return e[i].call(a.exports,a,a.exports,t),a.l=!0,a.exports}var r={};return t.m=e,t.c=r,t.i=function(e){return e},t.d=function(e,r,i){t.o(e,r)||Object.defineProperty(e,r,{configurable:!1,enumerable:!0,get:i})},t.n=function(e){var r=e&&e.__esModule?function(){return e.default}:function(){return e};return t.d(r,"a",r),r},t.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},t.p="",t(t.s=2)}([function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});t.pick=function(e,t){var r={};return t.forEach(function(t){r[t]=e[t]}),r},t.difference=function(e,t){var r=[];return e.forEach(function(e){t.indexOf(e)<0&&r.push(e)}),r}},function(e,t,r){"use strict";function i(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(t,"__esModule",{value:!0});var a=function(){function e(e,t){for(var r=0;r<t.length;r++){var i=t[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}return function(t,r,i){return r&&e(t.prototype,r),i&&e(t,i),t}}(),n=function(){function e(t){i(this,e),this.types=t}return a(e,[{key:"getTypes",value:function(){return this.types||[]}},{key:"parseValue",value:function(e){var t={};return this.getTypes().forEach(function(r,i){t["type"+i]=e}),t}},{key:"getSchema",value:function(){var e={};return this.getTypes().forEach(function(t,r){e["type"+r]={type:t,required:!0}}),e}}]),e}();t.default=n},function(e,t,r){"use strict";function i(e){return e&&e.__esModule?e:{default:e}}function a(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(t,"__esModule",{value:!0});var n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},o=function(){function e(e,t){for(var r=0;r<t.length;r++){var i=t[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}return function(t,r,i){return r&&e(t.prototype,r),i&&e(t,i),t}}(),s=r(0),u=r(1),l=i(u),f={notDefinedKey:function(e){return"Key '"+e+"' is not defined in schema"},modelIsUndefined:function(){return"Validated model is undefined"},validateRequired:function(e){return"Field '"+e+"' is required"},validateString:function(e){return"Field '"+e+"' is not a String"},validateNumber:function(e){return"Field '"+e+"' is not a Number"},validateObject:function(e){return"Field '"+e+"' is not a Object"},validateArray:function(e){return"Field '"+e+"' is not a Array"},validateBoolean:function(e){return"Field '"+e+"' is not a Boolean"},validateDate:function(e){return"Field '"+e+"' is not a Date"}},d=function(){function e(t,r){var i=!(arguments.length>2&&void 0!==arguments[2])||arguments[2];a(this,e),this.schema=t,this.errors={},this.promises=[],this.messages=r||f,this.validateKeys=i,this.validateTypeString=this.validateTypeString.bind(this),this.validateTypeNumber=this.validateTypeNumber.bind(this),this.validateTypeObject=this.validateTypeObject.bind(this),this.validateTypeArray=this.validateTypeArray.bind(this),this.validateTypeBoolean=this.validateTypeBoolean.bind(this),this.validateTypeDate=this.validateTypeDate.bind(this),this.validateTypeSchema=this.validateTypeSchema.bind(this),this.typesValidators={String:this.validateTypeString,Number:this.validateTypeNumber,Object:this.validateTypeObject,Array:this.validateTypeArray,Boolean:this.validateTypeBoolean,Date:this.validateTypeDate}}return o(e,[{key:"getDefaultValueForModel",value:function(e,t){return t?[e]:e}},{key:"getDefaultValues",value:function(){var t=this,r=Object.keys(this.schema),i={};return r.forEach(function(r){var a=t.getField(r),n=Array.isArray(a.type),o=n?a.type[0]:a.type;return a.defaultValue?void(i[r]=t.getDefaultValueForModel(a.defaultValue,n)):a.options?void(i[r]=t.getDefaultValueForModel(a.options[0].label?a.options[0].value:a.options[0],n)):o instanceof e?void(i[r]=t.getDefaultValueForModel(o.getDefaultValues(),n)):"Number"===o.name?void(i[r]=t.getDefaultValueForModel(NaN,n)):"Boolean"===o.name?void(i[r]=t.getDefaultValueForModel(!1,n)):"Object"===o.name?void(i[r]=t.getDefaultValueForModel({},n)):void(i[r]=t.getDefaultValueForModel("",n))}),i}},{key:"getField",value:function(e){return this.schema[e]}},{key:"getFields",value:function(){return this.schema}},{key:"validate",value:function(e){var t=this;return this.errors={},this.promises=[],this.checkModel(e)&&(this.checkKeysDiff(e),this.checkTypesAndValidators(e)),this.promises.length>0?new Promise(function(e){Promise.all(t.promises).then(e(t.errors))}):this.errors}},{key:"setError",value:function(e,t,r){return this.errors[e]||(this.errors[e]=[]),r>-1?void(this.errors[e][r]=t):void this.errors[e].push(t)}},{key:"checkModel",value:function(e){return!!e||(this.setError("model",this.messages.modelIsUndefined()),!1)}},{key:"checkKeysDiff",value:function(e){var t=this;if(!this.validateKeys)return!0;var r=Object.keys(e),i=Object.keys(this.schema),a=(0,s.difference)(r,i);a.length>0&&a.forEach(function(e){t.setError(e,t.messages.notDefinedKey(e))})}},{key:"checkTypesAndValidators",value:function(e){var t=this,r=Object.keys(this.schema),i=(0,s.pick)(e,r);r.forEach(function(e){var r=i[e],a=t.schema[e],n=Array.isArray(a.type),o=n?a.type[0]:a.type;n&&t.validateType(Array,r)?r.forEach(function(r,i){t.validateType(o,r,e,i)}):t.validateType(o,r,e),t.validateRequired(a,r,e),t.validateCustomValidators({validators:a.validators,value:r,fieldSchema:a,validatedObject:i,key:e})})}},{key:"validateCustomValidators",value:function(e){var t=this,r=e.validators,i=e.value,a=e.fieldSchema,n=e.validatedObject,o=e.key;r&&r.forEach(function(e){var r=e.validator,s=e.errorMessage,u=r(i,a,n);return u instanceof Promise?void t.promises.push(u.then(function(e){e||t.setError(o,s)})):void(u||t.setError(o,s))})}},{key:"validateRequired",value:function(e,t,r){!e.required||t&&0!==t.length||this.setError(r,this.messages.validateRequired(r))}},{key:"validateType",value:function(t,r,i,a){if("function"==typeof this.typesValidators[t.name])return this.typesValidators[t.name](r,i,t,a);if(t instanceof e)return this.validateTypeSchema(r,i,t,a);if(t instanceof l.default)return this.validateOneOfTypes(r,i,t,a);throw new Error("Unrecognized type "+t.name)}},{key:"validateTypeString",value:function(e,t,r){return"string"==typeof e||(this.setError(t,this.messages.validateString(t),r),!1)}},{key:"validateTypeNumber",value:function(e,t,r){return"number"==typeof e||(this.setError(t,this.messages.validateNumber(t),r),!1)}},{key:"validateTypeObject",value:function(e,t,r){return"object"===("undefined"==typeof e?"undefined":n(e))&&!Array.isArray(e)||(this.setError(t,this.messages.validateObject(t),r),!1)}},{key:"validateTypeArray",value:function(e,t,r){return!!Array.isArray(e)||(this.setError(t,this.messages.validateArray(t),r),!1)}},{key:"validateTypeBoolean",value:function(e,t,r){return"boolean"==typeof e||(this.setError(t,this.messages.validateBoolean(t),r),!1)}},{key:"validateTypeDate",value:function(e,t,r){return e instanceof Date||(this.setError(t,this.messages.validateDate(t),r),!1)}},{key:"validateTypeSchema",value:function(e,t,r,i){var a=r.validate(e),n=Object.keys(a);return 0===n.length||(this.setError(t,a,i),!1)}},{key:"validateOneOfTypes",value:function(t,r,i,a){var n=new e(i.getSchema()),o=n.validate(i.parseValue(t)),s=Object.keys(o);return s.length<i.getTypes().length||(this.setError(r,o,a),!1)}}],[{key:"oneOfTypes",value:function(e){return new l.default(e)}}]),e}();t.default=d}])});<commit_msg>build<commit_after>!function(e,t){if("object"==typeof exports&&"object"==typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{var r=t();for(var i in r)("object"==typeof exports?exports:e)[i]=r[i]}}(this,function(){return function(e){function t(i){if(r[i])return r[i].exports;var a=r[i]={i:i,l:!1,exports:{}};return e[i].call(a.exports,a,a.exports,t),a.l=!0,a.exports}var r={};return t.m=e,t.c=r,t.i=function(e){return e},t.d=function(e,r,i){t.o(e,r)||Object.defineProperty(e,r,{configurable:!1,enumerable:!0,get:i})},t.n=function(e){var r=e&&e.__esModule?function(){return e.default}:function(){return e};return t.d(r,"a",r),r},t.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},t.p="",t(t.s=2)}([function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});t.pick=function(e,t){var r={};return t.forEach(function(t){r[t]=e[t]}),r},t.difference=function(e,t){var r=[];return e.forEach(function(e){t.indexOf(e)<0&&r.push(e)}),r}},function(e,t,r){"use strict";function i(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(t,"__esModule",{value:!0});var a=function(){function e(e,t){for(var r=0;r<t.length;r++){var i=t[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}return function(t,r,i){return r&&e(t.prototype,r),i&&e(t,i),t}}(),n=function(){function e(t){i(this,e),this.types=t}return a(e,[{key:"getTypes",value:function(){return this.types||[]}},{key:"parseValue",value:function(e){var t={};return this.getTypes().forEach(function(r,i){t["type"+i]=e}),t}},{key:"getSchema",value:function(){var e={};return this.getTypes().forEach(function(t,r){e["type"+r]={type:t,required:!0}}),e}}]),e}();t.default=n},function(e,t,r){"use strict";function i(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(t,"__esModule",{value:!0});var a="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},n=function(){function e(e,t){for(var r=0;r<t.length;r++){var i=t[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}return function(t,r,i){return r&&e(t.prototype,r),i&&e(t,i),t}}(),o=r(0),s=r(1),u=function(e){return e&&e.__esModule?e:{default:e}}(s),l={notDefinedKey:function(e){return"Key '"+e+"' is not defined in schema"},modelIsUndefined:function(){return"Validated model is undefined"},validateRequired:function(e){return"Field '"+e+"' is required"},validateString:function(e){return"Field '"+e+"' is not a String"},validateNumber:function(e){return"Field '"+e+"' is not a Number"},validateObject:function(e){return"Field '"+e+"' is not a Object"},validateArray:function(e){return"Field '"+e+"' is not a Array"},validateBoolean:function(e){return"Field '"+e+"' is not a Boolean"},validateDate:function(e){return"Field '"+e+"' is not a Date"}},f=function(){function e(t,r){var a=!(arguments.length>2&&void 0!==arguments[2])||arguments[2];i(this,e),this.schema=t,this.errors={},this.promises=[],this.messages=r||l,this.validateKeys=a,this.validateTypeString=this.validateTypeString.bind(this),this.validateTypeNumber=this.validateTypeNumber.bind(this),this.validateTypeObject=this.validateTypeObject.bind(this),this.validateTypeArray=this.validateTypeArray.bind(this),this.validateTypeBoolean=this.validateTypeBoolean.bind(this),this.validateTypeDate=this.validateTypeDate.bind(this),this.validateTypeSchema=this.validateTypeSchema.bind(this),this.typesValidators={String:this.validateTypeString,Number:this.validateTypeNumber,Object:this.validateTypeObject,Array:this.validateTypeArray,Boolean:this.validateTypeBoolean,Date:this.validateTypeDate}}return n(e,[{key:"getDefaultValueForModel",value:function(e,t){return t?[e]:e}},{key:"getDefaultValues",value:function(){var t=this,r=Object.keys(this.schema),i={};return r.forEach(function(r){var a=t.getField(r),n=Array.isArray(a.type),o=n?a.type[0]:a.type;return a.defaultValue?void(i[r]=t.getDefaultValueForModel(a.defaultValue,n)):a.options?void(i[r]=t.getDefaultValueForModel(a.options[0].label?a.options[0].value:a.options[0],n)):o instanceof e?void(i[r]=t.getDefaultValueForModel(o.getDefaultValues(),n)):"Number"===o.name?void(i[r]=t.getDefaultValueForModel(NaN,n)):"Boolean"===o.name?void(i[r]=t.getDefaultValueForModel(!1,n)):"Object"===o.name?void(i[r]=t.getDefaultValueForModel({},n)):void(i[r]=t.getDefaultValueForModel("",n))}),i}},{key:"getField",value:function(e){return this.schema[e]}},{key:"getFields",value:function(){return this.schema}},{key:"validate",value:function(e){var t=this;return this.errors={},this.promises=[],this.checkModel(e)&&(this.checkKeysDiff(e),this.checkTypesAndValidators(e)),this.promises.length>0?new Promise(function(e){Promise.all(t.promises).then(e(t.errors))}):this.errors}},{key:"setError",value:function(e,t,r){if(this.errors[e]||(this.errors[e]=[]),r>-1)return void(this.errors[e][r]=t);this.errors[e].push(t)}},{key:"checkModel",value:function(e){return!!e||(this.setError("model",this.messages.modelIsUndefined()),!1)}},{key:"checkKeysDiff",value:function(e){var t=this;if(!this.validateKeys)return!0;var r=Object.keys(e),i=Object.keys(this.schema),a=(0,o.difference)(r,i);a.length>0&&a.forEach(function(e){t.setError(e,t.messages.notDefinedKey(e))})}},{key:"checkTypesAndValidators",value:function(e){var t=this,r=Object.keys(this.schema),i=(0,o.pick)(e,r);r.forEach(function(e){var r=i[e],a=t.schema[e],n=Array.isArray(a.type),o=n?a.type[0]:a.type;n&&t.validateType(Array,r)?r.forEach(function(r,i){t.validateType(o,r,e,i)}):t.validateType(o,r,e),t.validateRequired(a,r,e),t.validateCustomValidators({validators:a.validators,value:r,fieldSchema:a,validatedObject:i,key:e})})}},{key:"resolveValidatorErrorsForKey",value:function(e,t,r){var i=this;return"boolean"!=typeof r||r?Array.isArray(r)?void r.forEach(function(r){i.resolveValidatorErrorsForKey(e,t,r)}):void("string"==typeof r&&this.resolveValidatorErrorsForKey(e,r,!1)):void this.setError(e,t)}},{key:"validateCustomValidators",value:function(e){var t=this,r=e.validators,i=e.value,a=e.fieldSchema,n=e.validatedObject,o=e.key;r&&r.forEach(function(e){var r=e.validator,s=e.errorMessage,u=r(i,a,n);if(u instanceof Promise){var l=u.then(function(e){t.resolveValidatorErrorsForKey(o,s,e)});return void t.promises.push(l)}t.resolveValidatorErrorsForKey(o,s,u)})}},{key:"validateRequired",value:function(e,t,r){!e.required||t&&0!==t.length||this.setError(r,this.messages.validateRequired(r))}},{key:"validateType",value:function(t,r,i,a){if("function"==typeof this.typesValidators[t.name])return this.typesValidators[t.name](r,i,t,a);if(t instanceof e)return this.validateTypeSchema(r,i,t,a);if(t instanceof u.default)return this.validateOneOfTypes(r,i,t,a);throw new Error("Unrecognized type "+t.name)}},{key:"validateTypeString",value:function(e,t,r){return"string"==typeof e||(this.setError(t,this.messages.validateString(t),r),!1)}},{key:"validateTypeNumber",value:function(e,t,r){return"number"==typeof e||(this.setError(t,this.messages.validateNumber(t),r),!1)}},{key:"validateTypeObject",value:function(e,t,r){return"object"===(void 0===e?"undefined":a(e))&&!Array.isArray(e)||(this.setError(t,this.messages.validateObject(t),r),!1)}},{key:"validateTypeArray",value:function(e,t,r){return!!Array.isArray(e)||(this.setError(t,this.messages.validateArray(t),r),!1)}},{key:"validateTypeBoolean",value:function(e,t,r){return"boolean"==typeof e||(this.setError(t,this.messages.validateBoolean(t),r),!1)}},{key:"validateTypeDate",value:function(e,t,r){return e instanceof Date||(this.setError(t,this.messages.validateDate(t),r),!1)}},{key:"validateTypeSchema",value:function(e,t,r,i){var a=r.validate(e);return 0===Object.keys(a).length||(this.setError(t,a,i),!1)}},{key:"validateOneOfTypes",value:function(t,r,i,a){var n=new e(i.getSchema()),o=n.validate(i.parseValue(t));return Object.keys(o).length<i.getTypes().length||(this.setError(r,o,a),!1)}}],[{key:"oneOfTypes",value:function(e){return new u.default(e)}}]),e}();t.default=f}])});<|endoftext|>


<commit_before>import Hapi        from 'hapi';
import Good        from 'good';
import GoodConsole from 'good-console';

const server = new Hapi.Server();

server.connection({ port: 3000 });

server.route({
  method: 'GET',
  path: '/',
  handler: function (request, reply) {
    reply('Hello, world!');
  }
});

server.route({
  method: 'GET',
  path: '/{name}',
  handler: function (request, reply) {
    reply('Hello, ${encodeURIComponent(request.params.name)]!');
  }
});

server.register({
  register: Good,
  options: {
    reporters: [{
      reporter: GoodConsole,
      events: { response: '*', log: '*' }
    }]
  }
}, (err) => {
  if (err) { throw err; }

  server.start((err) => {
    if (err) { throw err; }

    server.log('info', 'Server running at: ' + server.info.uri);
  });
});
<commit_msg>Back ticks for JS interpolation<commit_after>import Hapi        from 'hapi';
import Good        from 'good';
import GoodConsole from 'good-console';

const server = new Hapi.Server();

server.connection({ port: 3000 });

server.route({
  method: 'GET',
  path: '/',
  handler: function (request, reply) {
    reply('Hello, world!');
  }
});

server.route({
  method: 'GET',
  path: '/{name}',
  handler: function (request, reply) {
    reply(`Hello, ${encodeURIComponent(request.params.name)}!`);
  }
});

server.register({
  register: Good,
  options: {
    reporters: [{
      reporter: GoodConsole,
      events: { response: '*', log: '*' }
    }]
  }
}, (err) => {
  if (err) { throw err; }

  server.start((err) => {
    if (err) { throw err; }

    server.log('info', 'Server running at: ' + server.info.uri);
  });
});
<|endoftext|>


<commit_before>"use strict";

var sass = require("node-sass");
var path = require("path");
var extend = require('util')._extend;
var tools = require('browserify-transform-tools');

module.exports = tools.makeStringTransform('sassify', {
    includeExtensions: ['.css', '.sass', '.scss'],
    evaluateArguments: true
}, function(content, opts, done) {
    var inject = (typeof opts.config !== 'undefined' && typeof opts.config['auto-inject'] !== 'undefined') ? opts.config['auto-inject'] : false;
    var file = opts.file;

    var options = extend({
        sourceComments : false,
        sourceMap : true,
        sourceMapEmbed : true,
        sourceMapContents : true,
        base64Encode : true,
        importer: null
    }, opts.config || {});

    options.includePaths = extend([], (opts.config ? opts.config.includePaths : []) || []);
    options.includePaths.unshift(path.dirname(opts.file));
    options.indentedSyntax = /\.sass$/i.test(opts.file);
    options.file = file;
    options.data = content;
    options.outFile = opts.file;

    if (options.importer) {
        if ((path.resolve(options.importer) === path.normalize(options.importer).replace(/(.+)([\/|\\])$/, '$1'))) {
            options.importer = require(options.importer);
        } else {
            options.importer = require(path.resolve(options.importer));
        }
    }

    var callback = function (error,css) {
        if(error) {
            return done(error);
        }
        var exp;
        if (inject) {
            if(options.base64Encode) {
                exp = "require('" + path.basename(path.dirname(__dirname)) + "').byUrl('" + (function() {
                        var b64 = css.css.toString('base64');
                        return 'data:text/css;base64,' + b64;
                    })() + "');";
            } else {
                exp = "require('" + path.basename(path.dirname(__dirname)) + "')('" + (function() {
                        return css.css.toString().replace(/'/gm, "\\'").replace(/\n/gm, ' ');
                    })() + "');";
            }
        } else {
            exp = JSON.stringify(css.css.toString());
        }
        var out = "module.exports = " + exp + ";";

        done(null, out);
    };

    sass.render(options, callback);
});<commit_msg>Set default options to false. Closes #35.<commit_after>"use strict";

var sass = require("node-sass");
var path = require("path");
var extend = require('util')._extend;
var tools = require('browserify-transform-tools');

module.exports = tools.makeStringTransform('sassify', {
    includeExtensions: ['.css', '.sass', '.scss'],
    evaluateArguments: true
}, function(content, opts, done) {
    var inject = (typeof opts.config !== 'undefined' && typeof opts.config['auto-inject'] !== 'undefined') ? opts.config['auto-inject'] : false;
    var file = opts.file;

    var options = extend({
        sourceComments : false,
        sourceMap : false,
        sourceMapEmbed : false,
        sourceMapContents : false,
        base64Encode : false,
        importer: null
    }, opts.config || {});

    options.includePaths = extend([], (opts.config ? opts.config.includePaths : []) || []);
    options.includePaths.unshift(path.dirname(opts.file));
    options.indentedSyntax = /\.sass$/i.test(opts.file);
    options.file = file;
    options.data = content;
    options.outFile = opts.file;

    if (options.importer) {
        if ((path.resolve(options.importer) === path.normalize(options.importer).replace(/(.+)([\/|\\])$/, '$1'))) {
            options.importer = require(options.importer);
        } else {
            options.importer = require(path.resolve(options.importer));
        }
    }

    var callback = function (error,css) {
        if(error) {
            return done(error);
        }
        var exp;
        if (inject) {
            if(options.base64Encode) {
                exp = "require('" + path.basename(path.dirname(__dirname)) + "').byUrl('" + (function() {
                        var b64 = css.css.toString('base64');
                        return 'data:text/css;base64,' + b64;
                    })() + "');";
            } else {
                exp = "require('" + path.basename(path.dirname(__dirname)) + "')('" + (function() {
                        return css.css.toString().replace(/'/gm, "\\'").replace(/\n/gm, ' ');
                    })() + "');";
            }
        } else {
            exp = JSON.stringify(css.css.toString());
        }
        var out = "module.exports = " + exp + ";";

        done(null, out);
    };

    sass.render(options, callback);
});<|endoftext|>