<commit_before>/*
 * grunt-maven-tasks
 * https://github.com/smh/grunt-maven-tasks
 *
 * Copyright (c) 2013 Stein Martin Hustad
 * Licensed under the MIT license.
 */

'use strict';

var semver = require('semver');
var fs = require('fs');

function injectDestFolder(targetPath, files) {
  var path = require('path');
  files.forEach(function(file) {
    file.dest = path.join(targetPath, file.dest || '');
  });
  return files;
}

module.exports = function(grunt) {

  grunt.registerMultiTask('maven', 'Packages and deploys artifact to maven repo', function(version, mode) {
    var options = this.options();

    requireOptionProps(options, ['groupId']);

    options.goal = options.goal || this.target;
    options.commitPrefix = options.commitPrefix || '%s';

    var pkg = grunt.file.readJSON(options.versionFile || 'package.json');

    if (options.goal === 'deploy') {
      requireOptionProps(options, ['url']);
      deploy(this, pkg);
    } else if (options.goal === 'install') {
      install(this, pkg);
    } else if (options.goal === 'release') {
      requireOptionProps(options, ['url']);
      release(this, pkg, version, mode);
    }
  });

  function install(task, pkg) {
    var options = task.options({
      artifactId: pkg.name,
      version: pkg.version,
      packaging: 'zip'
    });

    guaranteeFileName(options);
    configureDestination(options, task);
    configureMaven(options, task);

    grunt.task.run('maven:package',
      'maven:install-file');
  }

  function deploy(task, pkg) {
    var options = task.options({
      artifactId: pkg.name,
      version: pkg.version,
      packaging: 'zip'
    });

    guaranteeFileName(options);
    configureDestination(options, task);
    configureMaven(options, task);

    grunt.task.run('maven:package',
      'maven:deploy-file');
  }

  function release(task, pkg, version, mode) {
    var options = task.options({
      artifactId: pkg.name,
      packaging: 'zip',
      mode: 'minor',
      gitpush: false
    });

    if (version && !mode && isValidMode(version)) {
      mode = version;
      version = null;
    }

    options.mode = mode || options.mode;
    options.version = version || pkg.version.substr(0, pkg.version.length - '-SNAPSHOT'.length);

    if (options.nextVersion === 'null-SNAPSHOT') {
      grunt.fail.fatal('Failed to determine next development version ' +
        'based on version (' + options.version.cyan +
        ') and mode (' + options.mode.cyan + ')');
    }
    options.nextVersion = semver.inc(options.version, options.mode) + '-SNAPSHOT';
    if (options.nextVersion === 'null-SNAPSHOT') {
      grunt.fail.fatal('Failed to determine next development version ' +
        'based on version (' + options.version.cyan +
        ') and mode (' + options.mode.cyan + ')');
    }

    guaranteeFileName(options);
    configureDestination(options, task);
    configureMaven(options, task);

    grunt.task.run(
      'maven:version:' + options.version,
      'maven:package',
      'maven:deploy-file',
      'maven:version:' + options.nextVersion + ':deleteTag'
    );

    if (options.gitpush) {
      grunt.task.run(
        'maven:gitpush'
      );
    }

  }

  function getFileNameBase(options) {
    return options.artifactId + '-' + options.version +
      (options.classifier ? '-' + options.classifier : '');
  }

  function guaranteeFileName(options) {
    if (!options.file) {
      options.file = getFileNameBase(options) + '.' + options.packaging;
    }
  }

  function configureDestination(options, task) {
    if (typeof options.injectDestFolder === 'undefined' || options.injectDestFolder === true) {
      task.files = injectDestFolder(getFileNameBase(options), task.files);
    }
    grunt.config.set('grunt.maven.commitPrefix', options.commitPrefix);
  }

  function configureMaven(options, task) {
    grunt.config.set('maven.package.options', { archive: options.file, mode: options.packaging });
    grunt.config.set('maven.package.files', task.files);
    grunt.config.set('maven.deploy-file.options', options);
    grunt.config.set('maven.install-file.options', options);
  }

  grunt.registerTask('maven:package', function() {
    var compress = require('grunt-contrib-compress/tasks/lib/compress')(grunt);
    compress.options = grunt.config('maven.package.options');
    compress.tar(grunt.config('maven.package.files'), this.async());
  });

  grunt.registerTask('maven:install-file', function() {
    var options = grunt.config('maven.install-file.options');

    options.packaging = (options.type === 'war' || options.type === 'jar') ? options.type : options.packaging;
    options.file = renameForKnownPackageTypeArtifacts(options.file, options.packaging);

    var args = [ 'install:install-file' ];
    args.push('-Dfile='         + options.file);
    args.push('-DgroupId='      + options.groupId);
    args.push('-DartifactId='   + options.artifactId);
    args.push('-Dpackaging='    + options.packaging);
    args.push('-Dversion='      + options.version);
    if (options.classifier) {
      args.push('-Dclassifier=' + options.classifier);
    }
    // The lack of a space after the -s is critical
    // otherwise the path will be processed by maven incorrectly.
    if (options.settingsXml) {
      args.push('-s' + options.settingsXml);
    }
    if (grunt.debug || options.debug) {
      args.push('-e');
      args.push('-X');
    }

    var done = this.async();
    var msg = 'Installing to maven...';
    grunt.verbose.write(msg);
    grunt.util.spawn({ cmd: 'mvn', args: args, opts: {stdio: 'inherit'} }, function(err, result, code) {
      if (err) {
        grunt.verbose.or.write(msg);
        grunt.log.error().error('Failed to install to maven');
      } else {
        grunt.verbose.ok();
        grunt.log.writeln('Installed ' + options.file.cyan);
      }
      done(err);
    });
  });

  grunt.registerTask('maven:deploy-file', function() {
    var options = grunt.config('maven.deploy-file.options');

    options.packaging = (options.type === 'war' || options.type === 'jar') ? options.type : options.packaging;
    options.file = renameForKnownPackageTypeArtifacts(options.file, options.packaging);

    var args = [ 'deploy:deploy-file' ];
    args.push('-Dfile='         + options.file);
    args.push('-DgroupId='      + options.groupId);
    args.push('-DartifactId='   + options.artifactId);
    args.push('-Dpackaging='    + options.packaging);
    args.push('-Dversion='      + options.version);
    if (options.classifier) {
      args.push('-Dclassifier=' + options.classifier);
    }
    args.push('-Durl='          + options.url);
    if (options.repositoryId) {
      args.push('-DrepositoryId=' + options.repositoryId);
    }
    if (options.settingsXml) {
      // The lack of a space after the -s is critical
      // otherwise the path will be processed by maven incorrectly.
      args.push('-s' + options.settingsXml);
    }
    if (grunt.debug || options.debug) {
      args.push('-e');
      args.push('-X');
    }

    var done = this.async();
    var msg = 'Deploying to maven...';
    grunt.verbose.write(msg);
    grunt.util.spawn({ cmd: 'mvn', args: args, opts: {stdio: 'inherit'} }, function(err, result, code) {
      if (err) {
        grunt.verbose.or.write(msg);
        grunt.log.error().error('Failed to deploy to maven');
      } else {
        grunt.verbose.ok();
        grunt.log.writeln('Deployed ' + options.file.cyan + ' to ' + options.url.cyan);
      }
      done(err);
    });
  });

  grunt.registerTask('maven:version', 'Bumps version', function(version, deleteTag) {
    var done = this.async();
    var commitPrefix = grunt.config('grunt.maven.commitPrefix') || '';

    var msg = 'Bumping version to ' + version.cyan + '...';
    grunt.verbose.write(msg);

    grunt.util.spawn({ cmd: 'npm', args: ['version', version, '-m', commitPrefix + '%s'] }, function(err, result, code) {
      if (err) {
        grunt.verbose.or.write(msg);
        grunt.log.error().error('Failed to bump version to ' + version.cyan);
        return done(err);
      }

      grunt.verbose.ok();
      grunt.log.writeln('Version bumped to ' + version.cyan);

      if (!deleteTag) {
        return done();
      }

      isGitRepo(function(isGit) {
        if (!isGit) { return done(); }
        msg = 'Deleting tag v' + version.cyan + '...';
        grunt.verbose.write(msg);
        grunt.util.spawn({ cmd: 'git', args: ['tag', '-d', 'v' + version] }, function(err, result, code) {
          if (err) {
            grunt.verbose.or.write(msg);
            grunt.log.error().error('Failed to delete tag ' + ('v' + version).cyan);
          }

          grunt.verbose.ok();
          grunt.log.writeln('Deleted tag ' + ('v' + version).cyan);

          done(err);
        });
      });
    });
  });

  grunt.registerTask('maven:gitpush', 'Pushes to git', function() {
    var done = this.async();

    grunt.verbose.write('Pushing to git');

    gitPush(function(err) {
      if (err) {
        grunt.log.error().error('Failed to push new version to remote');
      } else {
        grunt.log.writeln('Pushed new version to remote');
      }
      done(err);
    });
  });

  function isGitRepo(fn) {
    grunt.util.spawn({ cmd: 'git', args: ['status', '--porcelain'] }, function(err, result, code) {
      fn(!err);
    });
  }

  function gitPush(fn) {
    grunt.util.spawn({ cmd: 'git', args: ['push'] }, function(err, result, code) {
      fn(err);
    });
  }

  function isValidMode(mode) {
    var validModes = ['major', 'minor', 'patch', 'build'].join('|');

    return mode.indexOf('|') < 0 && validModes.indexOf(mode) >=0;
  }

  function requireOptionProps(options, props) {
    var msg = 'Verifying properties ' + grunt.log.wordlist(props) + ' exists in options...';
    grunt.verbose.write(msg);

    var failProps = props.filter(function(p) {
      return !options.hasOwnProperty(p);
    }).map(function(p) {
      return '"' + p + '"';
    });

    if (failProps.length === 0) {
      grunt.verbose.ok();
    } else {
      grunt.verbose.or.write(msg);
      grunt.log.error().error('Unable to process task.');
      throw grunt.util.error('Required options ' + failProps.join(', ') + ' missing.');
    }
  }

  function renameForKnownPackageTypeArtifacts(fileName, packaging) {

      var newFileName = fileName;
      if (packaging === 'war') {
          newFileName = fileName.replace('zip', 'war');
      } else if (packaging === 'jar') {
          newFileName = fileName.replace('zip', 'jar');
      }

      try {
          fs.renameSync(fileName, newFileName);
          return newFileName;
      } catch (e) {
          throw e;
      }
  }
};
<commit_msg>log command arguments before mvn run<commit_after>/*
 * grunt-maven-tasks
 * https://github.com/smh/grunt-maven-tasks
 *
 * Copyright (c) 2013 Stein Martin Hustad
 * Licensed under the MIT license.
 */

'use strict';

var semver = require('semver');
var fs = require('fs');

function injectDestFolder(targetPath, files) {
  var path = require('path');
  files.forEach(function(file) {
    file.dest = path.join(targetPath, file.dest || '');
  });
  return files;
}

module.exports = function(grunt) {

  grunt.registerMultiTask('maven', 'Packages and deploys artifact to maven repo', function(version, mode) {
    var options = this.options();

    requireOptionProps(options, ['groupId']);

    options.goal = options.goal || this.target;
    options.commitPrefix = options.commitPrefix || '%s';

    var pkg = grunt.file.readJSON(options.versionFile || 'package.json');

    if (options.goal === 'deploy') {
      requireOptionProps(options, ['url']);
      deploy(this, pkg);
    } else if (options.goal === 'install') {
      install(this, pkg);
    } else if (options.goal === 'release') {
      requireOptionProps(options, ['url']);
      release(this, pkg, version, mode);
    }
  });

  function install(task, pkg) {
    var options = task.options({
      artifactId: pkg.name,
      version: pkg.version,
      packaging: 'zip'
    });

    guaranteeFileName(options);
    configureDestination(options, task);
    configureMaven(options, task);

    grunt.task.run('maven:package',
      'maven:install-file');
  }

  function deploy(task, pkg) {
    var options = task.options({
      artifactId: pkg.name,
      version: pkg.version,
      packaging: 'zip'
    });

    guaranteeFileName(options);
    configureDestination(options, task);
    configureMaven(options, task);

    grunt.task.run('maven:package',
      'maven:deploy-file');
  }

  function release(task, pkg, version, mode) {
    var options = task.options({
      artifactId: pkg.name,
      packaging: 'zip',
      mode: 'minor',
      gitpush: false
    });

    if (version && !mode && isValidMode(version)) {
      mode = version;
      version = null;
    }

    options.mode = mode || options.mode;
    options.version = version || pkg.version.substr(0, pkg.version.length - '-SNAPSHOT'.length);

    if (options.nextVersion === 'null-SNAPSHOT') {
      grunt.fail.fatal('Failed to determine next development version ' +
        'based on version (' + options.version.cyan +
        ') and mode (' + options.mode.cyan + ')');
    }
    options.nextVersion = semver.inc(options.version, options.mode) + '-SNAPSHOT';
    if (options.nextVersion === 'null-SNAPSHOT') {
      grunt.fail.fatal('Failed to determine next development version ' +
        'based on version (' + options.version.cyan +
        ') and mode (' + options.mode.cyan + ')');
    }

    guaranteeFileName(options);
    configureDestination(options, task);
    configureMaven(options, task);

    grunt.task.run(
      'maven:version:' + options.version,
      'maven:package',
      'maven:deploy-file',
      'maven:version:' + options.nextVersion + ':deleteTag'
    );

    if (options.gitpush) {
      grunt.task.run(
        'maven:gitpush'
      );
    }

  }

  function getFileNameBase(options) {
    return options.artifactId + '-' + options.version +
      (options.classifier ? '-' + options.classifier : '');
  }

  function guaranteeFileName(options) {
    if (!options.file) {
      options.file = getFileNameBase(options) + '.' + options.packaging;
    }
  }

  function configureDestination(options, task) {
    if (typeof options.injectDestFolder === 'undefined' || options.injectDestFolder === true) {
      task.files = injectDestFolder(getFileNameBase(options), task.files);
    }
    grunt.config.set('grunt.maven.commitPrefix', options.commitPrefix);
  }

  function configureMaven(options, task) {
    grunt.config.set('maven.package.options', { archive: options.file, mode: options.packaging });
    grunt.config.set('maven.package.files', task.files);
    grunt.config.set('maven.deploy-file.options', options);
    grunt.config.set('maven.install-file.options', options);
  }

  grunt.registerTask('maven:package', function() {
    var compress = require('grunt-contrib-compress/tasks/lib/compress')(grunt);
    compress.options = grunt.config('maven.package.options');
    compress.tar(grunt.config('maven.package.files'), this.async());
  });

  grunt.registerTask('maven:install-file', function() {
    var options = grunt.config('maven.install-file.options');

    options.packaging = (options.type === 'war' || options.type === 'jar') ? options.type : options.packaging;
    options.file = renameForKnownPackageTypeArtifacts(options.file, options.packaging);

    var args = [ 'install:install-file' ];
    args.push('-Dfile='         + options.file);
    args.push('-DgroupId='      + options.groupId);
    args.push('-DartifactId='   + options.artifactId);
    args.push('-Dpackaging='    + options.packaging);
    args.push('-Dversion='      + options.version);
    if (options.classifier) {
      args.push('-Dclassifier=' + options.classifier);
    }
    // The lack of a space after the -s is critical
    // otherwise the path will be processed by maven incorrectly.
    if (options.settingsXml) {
      args.push('-s' + options.settingsXml);
    }
    if (grunt.debug || options.debug) {
      args.push('-e');
      args.push('-X');
    }

    var done = this.async();
    var msg = 'Installing to maven...';
    grunt.verbose.write(msg);
    grunt.log.debug('Running command "mvn ' + args.join(' ') + '"');
    grunt.util.spawn({ cmd: 'mvn', args: args, opts: {stdio: 'inherit'} }, function(err, result, code) {
      if (err) {
        grunt.verbose.or.write(msg);
        grunt.log.error().error('Failed to install to maven');
      } else {
        grunt.verbose.ok();
        grunt.log.writeln('Installed ' + options.file.cyan);
      }
      done(err);
    });
  });

  grunt.registerTask('maven:deploy-file', function() {
    var options = grunt.config('maven.deploy-file.options');

    options.packaging = (options.type === 'war' || options.type === 'jar') ? options.type : options.packaging;
    options.file = renameForKnownPackageTypeArtifacts(options.file, options.packaging);

    var args = [ 'deploy:deploy-file' ];
    args.push('-Dfile='         + options.file);
    args.push('-DgroupId='      + options.groupId);
    args.push('-DartifactId='   + options.artifactId);
    args.push('-Dpackaging='    + options.packaging);
    args.push('-Dversion='      + options.version);
    if (options.classifier) {
      args.push('-Dclassifier=' + options.classifier);
    }
    args.push('-Durl='          + options.url);
    if (options.repositoryId) {
      args.push('-DrepositoryId=' + options.repositoryId);
    }
    if (options.settingsXml) {
      // The lack of a space after the -s is critical
      // otherwise the path will be processed by maven incorrectly.
      args.push('-s' + options.settingsXml);
    }
    if (grunt.debug || options.debug) {
      args.push('-e');
      args.push('-X');
    }

    var done = this.async();
    var msg = 'Deploying to maven...';
    grunt.verbose.write(msg);
    grunt.log.debug('Running command "mvn ' + args.join(' ') + '"');
    grunt.util.spawn({ cmd: 'mvn', args: args, opts: {stdio: 'inherit'} }, function(err, result, code) {
      if (err) {
        grunt.verbose.or.write(msg);
        grunt.log.error().error('Failed to deploy to maven');
      } else {
        grunt.verbose.ok();
        grunt.log.writeln('Deployed ' + options.file.cyan + ' to ' + options.url.cyan);
      }
      done(err);
    });
  });

  grunt.registerTask('maven:version', 'Bumps version', function(version, deleteTag) {
    var done = this.async();
    var commitPrefix = grunt.config('grunt.maven.commitPrefix') || '';

    var msg = 'Bumping version to ' + version.cyan + '...';
    grunt.verbose.write(msg);

    grunt.util.spawn({ cmd: 'npm', args: ['version', version, '-m', commitPrefix + '%s'] }, function(err, result, code) {
      if (err) {
        grunt.verbose.or.write(msg);
        grunt.log.error().error('Failed to bump version to ' + version.cyan);
        return done(err);
      }

      grunt.verbose.ok();
      grunt.log.writeln('Version bumped to ' + version.cyan);

      if (!deleteTag) {
        return done();
      }

      isGitRepo(function(isGit) {
        if (!isGit) { return done(); }
        msg = 'Deleting tag v' + version.cyan + '...';
        grunt.verbose.write(msg);
        grunt.util.spawn({ cmd: 'git', args: ['tag', '-d', 'v' + version] }, function(err, result, code) {
          if (err) {
            grunt.verbose.or.write(msg);
            grunt.log.error().error('Failed to delete tag ' + ('v' + version).cyan);
          }

          grunt.verbose.ok();
          grunt.log.writeln('Deleted tag ' + ('v' + version).cyan);

          done(err);
        });
      });
    });
  });

  grunt.registerTask('maven:gitpush', 'Pushes to git', function() {
    var done = this.async();

    grunt.verbose.write('Pushing to git');

    gitPush(function(err) {
      if (err) {
        grunt.log.error().error('Failed to push new version to remote');
      } else {
        grunt.log.writeln('Pushed new version to remote');
      }
      done(err);
    });
  });

  function isGitRepo(fn) {
    grunt.util.spawn({ cmd: 'git', args: ['status', '--porcelain'] }, function(err, result, code) {
      fn(!err);
    });
  }

  function gitPush(fn) {
    grunt.util.spawn({ cmd: 'git', args: ['push'] }, function(err, result, code) {
      fn(err);
    });
  }

  function isValidMode(mode) {
    var validModes = ['major', 'minor', 'patch', 'build'].join('|');

    return mode.indexOf('|') < 0 && validModes.indexOf(mode) >=0;
  }

  function requireOptionProps(options, props) {
    var msg = 'Verifying properties ' + grunt.log.wordlist(props) + ' exists in options...';
    grunt.verbose.write(msg);

    var failProps = props.filter(function(p) {
      return !options.hasOwnProperty(p);
    }).map(function(p) {
      return '"' + p + '"';
    });

    if (failProps.length === 0) {
      grunt.verbose.ok();
    } else {
      grunt.verbose.or.write(msg);
      grunt.log.error().error('Unable to process task.');
      throw grunt.util.error('Required options ' + failProps.join(', ') + ' missing.');
    }
  }

  function renameForKnownPackageTypeArtifacts(fileName, packaging) {

      var newFileName = fileName;
      if (packaging === 'war') {
          newFileName = fileName.replace('zip', 'war');
      } else if (packaging === 'jar') {
          newFileName = fileName.replace('zip', 'jar');
      }

      try {
          fs.renameSync(fileName, newFileName);
          return newFileName;
      } catch (e) {
          throw e;
      }
  }
};
<|endoftext|>


<commit_before>var gulp = require('gulp');
var treeWalker = require('./tree-walker');
var builder = require('systemjs-builder');
var RSVP = require('rsvp');
var insert = require('gulp-insert');

var appTree;
var routeTrees = [];
var promises = [];
var treeCache = {};

var build = function(config){
  console.log('tracing source files...')
  return treeWalker.getTrees({
      main: config.main,
      config: config.config
  }, treeCache).then(function (tree) {
      appTree = tree;

      config.routes.forEach(function (route) {
        promises.push(new RSVP.Promise(function (resolve, reject) {
          treeWalker.getTrees({
            main: route,
            config: './system.config.js'
          }, treeCache).then(function (tree) {
            routeTrees.push(tree);
            resolve();
          });
        }));
      })

      return RSVP.all(promises).then(function () {
        // Remove app tree dependencies from route trees;
        removeDepsFromRoutes();

        // generate inverse index of dependencies
        var inverseIndex = generateInverseIndex();
        // generate bundles
        console.log('generating bundles...')
        var bundles = generateBundles(inverseIndex, config.bundleThreshold);
        // build trees
        console.log('building...')
        return buildTrees(bundles, config);
    });
  });
}

var removeDepsFromRoutes = function(){
  Object.keys(appTree).forEach(function (moduleName) {
    routeTrees.forEach(function (treeIndex) {
      if (treeIndex[moduleName]) {
        // deleting the dep tree
        delete treeIndex[moduleName];
        // removing dep from the other trees
        Object.keys(treeIndex).forEach(function (depName) {
          treeIndex[depName].tree = builder.subtractTrees(treeIndex[depName].tree, appTree[moduleName].tree);
        });
      }
    });
  });
}

var generateInverseIndex = function(){
  var inverseIndex = {};
  routeTrees.forEach(function (treeIndex, i) {
    Object.keys(treeIndex).forEach(function (depName) {
      if (inverseIndex[depName] === undefined) {
        inverseIndex[depName] = [i];
      } else {
        inverseIndex[depName].push(i);
      }
    });
  });
  return inverseIndex;
}

var generateBundles = function(inverseIndex, bundleThreshold){
  var bundles = {};
  // generating bundles
  Object.keys(inverseIndex).forEach(function (moduleName) {
    // if it's included in only one route, leave it there
    if (inverseIndex[moduleName].length == 1) {
      return;
    }

    var module = routeTrees[inverseIndex[moduleName][0]][moduleName];
    if (inverseIndex[moduleName].length / routeTrees.length >= bundleThreshold) {
      // if it's included in more than the threshold of the routes, put it in app
      //console.log('shared by more than ' + (bundleThreshold*100) + '% of routes - including in app');
      appTree['app/app'].tree = builder.addTrees(appTree['app/app'].tree, module.tree);
      appTree[moduleName] = module;

    } else {
      // otherwise, put it in a bundle
      var bundleName = inverseIndex[moduleName].sort().join('-');
      if (bundles[bundleName] === undefined) {
        bundles[bundleName] = module;
      } else {
        bundles[bundleName].tree = builder.addTrees(bundles[bundleName].tree, module.tree);
      }
    }

    // remove from other trees;
    inverseIndex[moduleName].forEach(function (index) {
      var treeIndex = routeTrees[index];
      delete treeIndex[moduleName];

      Object.keys(treeIndex).forEach(function (depName) {
        treeIndex[depName].tree = builder.subtractTrees(treeIndex[depName].tree, module.tree);
      });

    })
  });
  return bundles;
}

var buildTrees = function(bundles, config){
  // build bundles
  var bundlesConfig = {};
  console.log('building bundles...')
  Object.keys(bundles).forEach(function (bundleName) {
    buildTree(bundles[bundleName], "bundles/" + bundleName, config);
    bundlesConfig["bundles/" + bundleName] = Object.keys(bundles[bundleName].tree);
  });
  // build route trees
  console.log('building routes...')
  routeTrees.forEach(function (treeIndex) {
    Object.keys(treeIndex).forEach(function (moduleName) {
      buildTree(treeIndex[moduleName], moduleName, config);
    });
  });
  // build root app
  console.log('building app...')
  return Object.keys(appTree).forEach(function (moduleName) {
    buildTree(appTree[moduleName], moduleName, config).then(function () {
      if (moduleName === 'app/app') {
        var bundlesString = "System.bundles = " + JSON.stringify(bundlesConfig, null, 4) + ";";

        return gulp.src('dist/app/app.js')
          .pipe(insert.prepend(bundlesString))
          .pipe(gulp.dest('dist/app'));
      }
    })
  });
}

var buildTree = function (tree, destination, config) {
  //if (destination.indexOf('bower_components') != 0) {
    return builder.buildTree(tree.tree, 'dist/' + destination + '.js', {
      sourceMaps: config.sourceMaps,
      minify: config.minify
    })
  //}
}

module.exports = {
  build: build
};
<commit_msg>Don't include references to css files in the bundle configs<commit_after>var gulp = require('gulp');
var treeWalker = require('./tree-walker');
var builder = require('systemjs-builder');
var RSVP = require('rsvp');
var insert = require('gulp-insert');

var appTree;
var routeTrees = [];
var promises = [];
var treeCache = {};

var build = function(config){
  console.log('tracing source files...')
  return treeWalker.getTrees({
      main: config.main,
      config: config.config
  }, treeCache).then(function (tree) {
      appTree = tree;

      config.routes.forEach(function (route) {
        promises.push(new RSVP.Promise(function (resolve, reject) {
          treeWalker.getTrees({
            main: route,
            config: './system.config.js'
          }, treeCache).then(function (tree) {
            routeTrees.push(tree);
            resolve();
          });
        }));
      })

      return RSVP.all(promises).then(function () {
        // Remove app tree dependencies from route trees;
        removeDepsFromRoutes();

        // generate inverse index of dependencies
        var inverseIndex = generateInverseIndex();
        // generate bundles
        console.log('generating bundles...')
        var bundles = generateBundles(inverseIndex, config.bundleThreshold);
        // build trees
        console.log('building...')
        return buildTrees(bundles, config);
    });
  }, function(error){
    console.log('error')
  });
}

var removeDepsFromRoutes = function(){
  Object.keys(appTree).forEach(function (moduleName) {
    routeTrees.forEach(function (treeIndex) {
      if (treeIndex[moduleName]) {
        // deleting the dep tree
        delete treeIndex[moduleName];
        // removing dep from the other trees
        Object.keys(treeIndex).forEach(function (depName) {
          treeIndex[depName].tree = builder.subtractTrees(treeIndex[depName].tree, appTree[moduleName].tree);
        });
      }
    });
  });
}

var generateInverseIndex = function(){
  var inverseIndex = {};
  routeTrees.forEach(function (treeIndex, i) {
    Object.keys(treeIndex).forEach(function (depName) {
      if (inverseIndex[depName] === undefined) {
        inverseIndex[depName] = [i];
      } else {
        inverseIndex[depName].push(i);
      }
    });
  });
  return inverseIndex;
}

var generateBundles = function(inverseIndex, bundleThreshold){
  var bundles = {};
  // generating bundles
  Object.keys(inverseIndex).forEach(function (moduleName) {
    // if it's included in only one route, leave it there
    if (inverseIndex[moduleName].length == 1) {
      return;
    }

    var module = routeTrees[inverseIndex[moduleName][0]][moduleName];
    if (inverseIndex[moduleName].length / routeTrees.length >= bundleThreshold) {
      // if it's included in more than the threshold of the routes, put it in app
      //console.log('shared by more than ' + (bundleThreshold*100) + '% of routes - including in app');
      appTree['app/app'].tree = builder.addTrees(appTree['app/app'].tree, module.tree);
      appTree[moduleName] = module;

    } else {
      // otherwise, put it in a bundle
      var bundleName = inverseIndex[moduleName].sort().join('-');
      if (bundles[bundleName] === undefined) {
        bundles[bundleName] = module;
      } else {
        bundles[bundleName].tree = builder.addTrees(bundles[bundleName].tree, module.tree);
      }
    }

    // remove from other trees;
    inverseIndex[moduleName].forEach(function (index) {
      var treeIndex = routeTrees[index];
      delete treeIndex[moduleName];

      Object.keys(treeIndex).forEach(function (depName) {
        treeIndex[depName].tree = builder.subtractTrees(treeIndex[depName].tree, module.tree);
      });

    })
  });
  return bundles;
}

var buildTrees = function(bundles, config){
  // build bundles
  var bundlesConfig = {};
  console.log('building bundles...')
  Object.keys(bundles).forEach(function (bundleName) {
    buildTree(bundles[bundleName], "bundles/" + bundleName, config);
    bundlesConfig["bundles/" + bundleName] = Object.keys(bundles[bundleName].tree).filter(function(item){ return item.indexOf('.css!') == -1});
  });
  // build route trees
  console.log('building routes...')
  routeTrees.forEach(function (treeIndex) {
    Object.keys(treeIndex).forEach(function (moduleName) {
      buildTree(treeIndex[moduleName], moduleName, config);
    });
  });
  // build root app
  console.log('building app...')
  return Object.keys(appTree).forEach(function (moduleName) {
    buildTree(appTree[moduleName], moduleName, config).then(function () {
      if (moduleName === 'app/app') {
        var bundlesString = "System.bundles = " + JSON.stringify(bundlesConfig, null, 4) + ";";

        return gulp.src('dist/app/app.js')
          .pipe(insert.prepend(bundlesString))
          .pipe(gulp.dest('dist/app'));
      }
    })
  });
}

var buildTree = function (tree, destination, config) {
  //if (destination.indexOf('bower_components') != 0) {
    return builder.buildTree(tree.tree, 'dist/' + destination + '.js', {
      sourceMaps: config.sourceMaps,
      minify: config.minify
    })
  //}
}

module.exports = {
  build: build
};
<|endoftext|>


<commit_before>/**
 * Configures and starts express server via Let's Encrypt.
 *
 * Events are fired during initialisation to allow customisation, including:
 *   - onHttpServerCreated
 *
 * consumed by lib/core/start.js
 *
 * @api private
 */

var async = require('async');
var http = require('http');
var https;
try {
	// Use spdy if available
	https = require('spdy');
} catch (e) {
	https = require('https');
}
var path = require('path');
var letsencrypt = require('letsencrypt-express');
var letsencryptDir = path.join(require('os').homedir(), 'letsencrypt', 'etc');

function sslRedirect (req, res) {
	res.setHeader('Location', 'https://' + req.headers.host + req.url);
	res.statusCode = 302;
	res.end();
}

function autoRegister (domains, email) {
	if (!Array.isArray(domains)) {
		domains = [domains];
	}
	return function (hostname, approve) {
		if (domains.indexOf(hostname) !== -1) {
			console.warn("Keystone Let's Encrypt: Approving registration for " + hostname);
			approve(null, {
				domains: domains,
				email: email,
				agreeTos: true,
			});
		} else {
			console.log("Keystone Let's Encrypt: Denying registration for " + hostname);
			approve('Nope.');
		}
	};
}
module.exports = function (keystone, app, callback) {

	var name = keystone.get('name');
	var host = keystone.get('host') || '0.0.0.0';
	var port = keystone.get('port') || 3000;
	var forceSsl = (keystone.get('ssl') === 'force');
	var sslHost = keystone.get('ssl host') || host;
	var sslPort = keystone.get('ssl port') || port + 1;

	var options = keystone.get('letsencrypt');
	var email = options.email;
	var domains = options.domains;
	var approveRegistration;
	if (options.register) {
		if (options.tos && email && domains) {
			approveRegistration = autoRegister(domains, email);
		} else {
			callback("For auto registation with Let's Encrypt you should agree to the TOS, provide domains and a domain owner email");
			return;
		}
	}
	var instance = letsencrypt.create({
		configDir: options.configDir || letsencryptDir,
		onRequest: app,
		approveRegistration: approveRegistration,
		// TODO handleRenewFailure
	});

	async.parallel([
		function (done) {
			var serve = (forceSsl) ? sslRedirect : app;
			keystone.httpServer = http.createServer(
				letsencrypt.createAcmeResponder(instance, serve)
			).listen(port, host, done);
		},
		function (done) {
			keystone.httpsServer = https.createServer(
				instance.httpsOptions,
				letsencrypt.createAcmeResponder(instance, app)
			).listen(sslPort, sslHost, done);
		},
	], 	function ready (err) {
		if (err) { return callback(err); }

		var message = name + ' is ready on '
		+ 'http://' + host + ':' + port
		+ (forceSsl ? ' (SSL redirect)' : '')
		+ ' and ' + 'https://' + sslHost + ':' + sslPort;
		callback(null, message);
	});

};
<commit_msg>Allow local connections without forcing SSL<commit_after>/**
 * Configures and starts express server via Let's Encrypt.
 *
 * Events are fired during initialisation to allow customisation, including:
 *   - onHttpServerCreated
 *
 * consumed by lib/core/start.js
 *
 * @api private
 */

var async = require('async');
var http = require('http');
var https;
try {
	// Use spdy if available
	https = require('spdy');
} catch (e) {
	https = require('https');
}
var path = require('path');
var letsencrypt = require('letsencrypt-express');
var letsencryptDir = path.join(require('os').homedir(), 'letsencrypt', 'etc');

function makeSslRedirect (app) {
	return function sslRedirect (req, res) {
		// This runs outside Express, so use pure NodeJS only
		const s = req.socket
		if (s && s.remoteAddress === '127.0.0.1' && s.localAddress === '127.0.0.1' && !req.headers['x-forwarded-for']) {
			return app(req, res);
		} else {
			res.setHeader('Location', 'https://' + req.headers.host + req.url);
			res.statusCode = 302;
			res.end();
		}
	}
}

function autoRegister (domains, email) {
	if (!Array.isArray(domains)) {
		domains = [domains];
	}
	return function (hostname, approve) {
		if (domains.indexOf(hostname) !== -1) {
			console.warn("Keystone Let's Encrypt: Approving registration for " + hostname);
			approve(null, {
				domains: domains,
				email: email,
				agreeTos: true,
			});
		} else {
			console.log("Keystone Let's Encrypt: Denying registration for " + hostname);
			approve('Nope.');
		}
	};
}
module.exports = function (keystone, app, callback) {

	var name = keystone.get('name');
	var host = keystone.get('host') || '0.0.0.0';
	var port = keystone.get('port') || 3000;
	var forceSsl = (keystone.get('ssl') === 'force');
	var sslHost = keystone.get('ssl host') || host;
	var sslPort = keystone.get('ssl port') || port + 1;

	var options = keystone.get('letsencrypt');
	var email = options.email;
	var domains = options.domains;
	var approveRegistration;
	if (options.register) {
		if (options.tos && email && domains) {
			approveRegistration = autoRegister(domains, email);
		} else {
			callback("For auto registation with Let's Encrypt you should agree to the TOS, provide domains and a domain owner email");
			return;
		}
	}
	var instance = letsencrypt.create({
		configDir: options.configDir || letsencryptDir,
		onRequest: app,
		approveRegistration: approveRegistration,
		// TODO handleRenewFailure
	});

	async.parallel([
		function (done) {
			var serve = (forceSsl) ? makeSslRedirect(app) : app;
			keystone.httpServer = http.createServer(
				letsencrypt.createAcmeResponder(instance, serve)
			).listen(port, host, done);
		},
		function (done) {
			keystone.httpsServer = https.createServer(
				instance.httpsOptions,
				letsencrypt.createAcmeResponder(instance, app)
			).listen(sslPort, sslHost, done);
		},
	], 	function ready (err) {
		if (err) { return callback(err); }

		var message = name + ' is ready on '
		+ 'http://' + host + ':' + port
		+ (forceSsl ? ' (SSL redirect)' : '')
		+ ' and ' + 'https://' + sslHost + ':' + sslPort;
		callback(null, message);
	});

};
<|endoftext|>


<commit_before>'use strict';

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

var expressions = {};

var snippets = {

    /* Abs - The abs function returns the absolute value of x, i.e. x when x is positive or zero and -x for negative x. The input parameter can be a floating scalar or a float vector. In case of a float vector the operation is done component-wise.
     */

    abs: {glsl: 'abs(%1);', output: { 4: 4, 3: 3, 2: 2, 1: 1 }},
    /* Sign - The sign function returns 1.0 when x is positive, 0.0 when x is zero and -1.0 when x is negative. The input parameter can be a floating scalar or a float vector. In case of a float vector the operation is done component-wise. */

    sign: {glsl: 'sign(%1);', output: { 4: 4, 3: 3, 2: 2, 1: 1 }},

    /* Floor - The floor function returns the largest integer number that is smaller or equal to x. The input parameter can be a floating scalar or a float vector. In case of a float vector the operation is done component-wise. */

    floor: {glsl: 'floor(%1);', output: { 4: 4, 3: 3, 2: 2, 1: 1 }},

    /* Ceiling - The ceiling function returns the smallest number that is larger or equal to x. The input parameter can be a floating scalar or a float vector. In case of a float vector the operation is done component-wise. */

    ceiling: {glsl: 'ceil(%1);', output: { 4: 4, 3: 3, 2: 2, 1: 1 }},

    /* The mod expression returns the remained of the division operation of the two inputs. */

    mod: {glsl: 'mod(%1, %2);'},

    /* Min - The min function returns the smaller of the two arguments. The input parameters can be floating scalars or float vectors. In case of float vectors the operation is done component-wise. */

    min: {glsl: 'min(%1, %2);', output: { 4: 4, 3: 3, 2: 2, 1: 1 }},

    /* Max - The max function returns the larger of the two arguments. The input parameters can be floating scalars or float vectors. In case of float vectors the operation is done component-wise. */

    max: {glsl: 'max(%1, %2);', output: { 4: 4, 3: 3, 2: 2, 1: 1 }},

    /* Clamp - The clamp function returns x if it is larger than minVal and smaller than maxVal. In case x is smaller than minVal, minVal is returned. If x is larger than maxVal, maxVal is returned. The input parameters can be floating scalars or float vectors. In case of float vectors the operation is done component-wise. */

    clamp: {glsl: 'clamp(%1, %2, %3);', output: { '4,1,1': 4, '3,1,1': 3, '2,1,1': 2, '1,1,1': 1 }},

    /* Mix - The mix function returns the linear blend of x and y, i.e. the product of x and (1 - a) plus the product of y and a. The input parameters can be floating scalars or float vectors. In case of float vectors the operation is done component-wise. */

    mix: {glsl: 'mix(%1, %2, %3);', output: { '4,4,1': 4, '3,3,1': 3, '2,2,1': 2, '4,4,1': 4, '1,1,1': 1 }},

    /* Step - The step function returns 0.0 if x is smaller then edge and otherwise 1.0. The input parameters can be floating scalars or float vectors. In case of float vectors the operation is done component-wise. */

    step: {glsl: 'step(%1, %2, %3);', output: { '1,1': 1, '1,2': 2, '1,3': 3, '1,4': 4 }},

    /* Smoothstep - The smoothstep function returns 0.0 if x is smaller then edge0 and 1.0 if x is larger than edge1. Otherwise the return value is interpolated between 0.0 and 1.0 using Hermite polynomirals. The input parameters can be floating scalars or float vectors. In case of float vectors the operation is done component-wise. */

    smoothstep: {glsl: 'smoothstep(%1);', output: { '1,1,1':1, '2,2,2':2, '3,3,3':3, '4,4,4':4 }},

    /* fragCoord - The fragCoord function returns the fragment's position in screenspace. */

    fragCoord: {glsl: 'gl_FragColor;', output: 4 },

    /* Sin - The sin function returns the sine of an angle in radians. The input parameter can be a floating scalar or a float vector. In case of a float vector the sine is calculated separately for every component. */

    sin: {glsl: 'sin(%1);', output: {'1':1, '2':2, '3':3, '4':4}},

    /* Cos - The cos function returns the cosine of an angle in radians. The input parameter can be a floating scalar or a float vector. */

    cos: {glsl: 'cos(%1);', output: {'1':1, '2':2, '3':3, '4':4}},

    /* Pow - The power function returns x raised to the power of y. The input parameters can be floating scalars or float vectors. In case of float vectors the operation is done component-wise. */

    pow: {glsl: 'pow(%1, %2);', output: {'1,1':1, '2,2':2, '3,3':3, '1,4':4}},

    /* Sqrt - The sqrt function returns the square root of x. The input parameter can be a floating scalar or a float vector. In case of a float vector the operation is done component-wise. */

    sqrt: {glsl: 'sqrt(%1);', output: {'1,1':1, '2,2':2, '3,3':3, '1,4':4}},

    /* time - The time function returns the elapsed time in the unix epoch in milliseconds.*/

    time: {glsl: 'time;', output: 1},

    /* The Add function takes two inputs, adds them together and outputs the result. This addition operation is performed on a per channel basis, meaning that the inputs' R channels get added, G channels get added, B channels get added, etc. Both inputs must have the same number of channels unless one of them is a single Constant value. Constants can be added to a vector with any number of inputs. */

    add: {glsl: '%1 + %2;', output:  {'1,1':1, '2,2':2, '3,3':3, '4,4':4, '2,1':2, '3,1':3, '4,1':4}},

    /* The subtract function takes two inputs, subtracts the first from the second,  and outputs the result. This addition operation is performed on a per channel basis, meaning that the inputs' R channels get subtracted, G channels get subtracted, B channels get subtracted, etc. Both inputs must have the same number of channels unless one of them is a single Constant value. Constants can be added to a vector with any number of inputs. */

    subtract: {glsl: '%1 - %2;', output: {'1,1':1, '2,2':2, '3,3':3, '4,4':4, '2,1':2, '3,1':3, '4,1':4}},

    /* The Add function takes two inputs, adds them together and outputs the result. This addition operation is performed on a per channel basis, meaning that the inputs' R channels get added, G channels get added, B channels get added, etc. Both inputs must have the same number of channels unless one of them is a single Constant value. Constants can be added to a vector with any number of inputs. */

    multiply: {glsl: '%1 * %2;', output: {'1,1':1, '2,2':2, '3,3':3, '4,4':4, '2,1':2, '3,1':3, '4,1':4}},

    /* The normal function returns the 3-dimensional surface normal, which is a vector that is perpendicular to the tangent plane at that point.*/

    normal: { glsl: 'vec4((v_Normal + 1.0) * 0.5, 1.0);', output: 4 },

    /* The uv function returns the 2-dimensional vector that maps the object's 3-dimensional vertices to a 2D plane. */

    uv: {glsl:'v_TextureCoordinate;', output: 2},

    /* The mesh position function returns the transformed fragment's position in world-space.  */

    meshPosition: {glsl:'(v_Position + 1.0) * 0.5;', output: 3},

    normalize: {glsl: 'normalize(%1)', output: {1: 1, 2: 2, 3: 3, 4: 4}},

    dot: {glsl: 'dot(%1, %2);', output: {'1,1': 1,'2,2':1, '3,3': 1, '4,4':1 }},

    /* The image function fetches the model's */

    image: {glsl:'texture2D(u_Textures[0], v_TextureCoordinate);', output: 4 },

    /* The constant function returns a static value which is defined at compile-time that cannot be changed dynamically.*/

    constant: {glsl: '%1;'},

    /* The Parameter expression has values that can be modified (dynamically during runtime in some cases) in a MaterialInstance of the base material containing the parameter. These expressions should be given unique names, via the Parameter Name property, to be used when identifying the specific parameter in the MaterialInstance. If two parameters of the same type have the same name in the same material, they will be assumed to be the same parameter. Changing the value of the parameter in the MaterialInstance would change the value of both the parameter expressions in the material. A default value for the parameter will also be set in the base material. This will be the value of the parameter in the MaterialInstance unless it is overridden and modified there. */

    parameter: {uniforms: {parameter: 1}, glsl: 'parameter;'},
    vec3: {glsl: 'vec3(%1);', output: 3},
    vec2: {glsl: 'vec2(%1);', output: 2}
};

expressions.registerExpression = function registerExpression(name, schema) {
    this[name] = function (inputs, options) {
        return new Material(name, schema, inputs, options);
    };
};

for (var name in snippets) {
    expressions.registerExpression(name, snippets[name]);
}

/**
 * Material is a public class that composes a material-graph out of expressions
 *
 *
 * @class Material
 * @constructor
 *
 * @param {Object} definiton of nascent expression with shader code, inputs and uniforms
 * @param {Array} list of Material expressions, images, or constant
 * @param {Object} map of uniform data of float, vec2, vec3, vec4
 */

function Material(name, chunk, inputs, options) {
    options = options || {};

    this.name = name;
    this.chunk = chunk;
    this.inputs = inputs ? (Array.isArray(inputs) ? inputs : [inputs]): [];
    this.uniforms = options.uniforms || {};
    this.varyings = options.varyings;
    this.attributes = options.attributes;

    if (options.texture) {
        this.texture = options.texture.__isATexture__ ? options.texture : TextureRegistry.register(null, options.texture);
    }

    this._id = Material.id++;

    this.invalidations = [];
    this.__isAMaterial__ = true;
}

Material.id = 2;

/**
 * Iterates over material graph
 *
 * @method traverse
 * @chainable
 *
 * @param {Function} invoked upon every expression in the graph
 */

// Material.prototype.traverse = function traverse(callback) {
//     var len = this.inputs && this.inputs.length, idx = -1, save;

//     while (++idx < len) save = traverse.call(this.inputs[idx], callback, idx);

//     callback(this);

//     return this;
// };

Material.prototype.setUniform = function setUniform(name, value) {
    this.uniforms[name] = value;

    this.invalidations.push(name);
};

/**
 * Converts material graph into chunk
 *
 * @method _compile
 * @protected
 *
 */

// Material.prototype._compile = function _compile() {
//     var glsl = '';
//     var uniforms = {};
//     var varyings = {};
//     var attributes = {};
//     var defines = [];
//     var textures = [];

//     this.traverse(function (node, depth) {
//         if (! node.chunk) return;
//         var type = types[getType(node)];

//         glsl += type + makeLabel(node) + ' = ' + processGLSL(node.chunk.glsl, node.inputs) + '\n ';
//         if (node.uniforms) extend(uniforms, node.uniforms);
//         if (node.varyings) extend(varyings, node.varyings);
//         if (node.attributes) extend(attributes, node.attributes);
//         if (node.chunk.defines) defines.push(node.chunk.defines);
//         if (node.texture) textures.push(node.texture);
//     });

//     return {
//         _id: this._id,
//         glsl: glsl + 'return ' + makeLabel(this) + ';',
//         defines: defines.join('\n'),
//         uniforms: uniforms,
//         varyings: varyings,
//         attributes: attributes,
//         textures: textures
//     };
// };

// function getType(node) {

//     //input is a constant

//     if (typeof node == 'number') return '1';
//     if (Array.isArray(node)) return node.length;

//     var output = node.chunk.output;
//     if (typeof output === 'number') return output;
//     var key = node.inputs.map(function recurse(node) { return getType(node); }).join(',');

//     return output[key];
// }

// function extend (a, b) { for (var k in b) a[k] = b[k]; }

// function processGLSL(str, inputs) {
//     return str.replace(/%\d/g, function (s) {
//         return makeLabel(inputs[s[1]-1]);
//     });
// }

// function makeLabel (n) {
//     if (Array.isArray(n)) return arrayToVec(n);
//     if (typeof n == 'object') return 'fa_' + (n._id);
//     else return JSON.stringify(n.toFixed(6));
// }

// function arrayToVec(array) {
//     var len = array.length;
//     return 'vec' + len + '(' + array.join(',')  + ')';
// }

module.exports = expressions;
expressions.Material = Material;

expressions.Texture = function (source) {
    if (typeof window === 'undefined') return console.error('Texture constructor cannot be run inside of a worker');
    return expressions.image([], { texture: source });
};

expressions.Custom = function (schema, inputs, uniforms) {
    return new Material('custom', {glsl: schema, output: 1, uniforms: uniforms || {}} , inputs);
};

function typeofConst(c) {
    if (Array.isArray(c)) return 'vec' + c.length + ' ';
    else return 'float ';
}<commit_msg>fix: removing function that are no longer necessary<commit_after>'use strict';

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

var expressions = {};

var snippets = {

    /* Abs - The abs function returns the absolute value of x, i.e. x when x is positive or zero and -x for negative x. The input parameter can be a floating scalar or a float vector. In case of a float vector the operation is done component-wise.
     */

    abs: {glsl: 'abs(%1);', output: { 4: 4, 3: 3, 2: 2, 1: 1 }},
    /* Sign - The sign function returns 1.0 when x is positive, 0.0 when x is zero and -1.0 when x is negative. The input parameter can be a floating scalar or a float vector. In case of a float vector the operation is done component-wise. */

    sign: {glsl: 'sign(%1);', output: { 4: 4, 3: 3, 2: 2, 1: 1 }},

    /* Floor - The floor function returns the largest integer number that is smaller or equal to x. The input parameter can be a floating scalar or a float vector. In case of a float vector the operation is done component-wise. */

    floor: {glsl: 'floor(%1);', output: { 4: 4, 3: 3, 2: 2, 1: 1 }},

    /* Ceiling - The ceiling function returns the smallest number that is larger or equal to x. The input parameter can be a floating scalar or a float vector. In case of a float vector the operation is done component-wise. */

    ceiling: {glsl: 'ceil(%1);', output: { 4: 4, 3: 3, 2: 2, 1: 1 }},

    /* The mod expression returns the remained of the division operation of the two inputs. */

    mod: {glsl: 'mod(%1, %2);'},

    /* Min - The min function returns the smaller of the two arguments. The input parameters can be floating scalars or float vectors. In case of float vectors the operation is done component-wise. */

    min: {glsl: 'min(%1, %2);', output: { 4: 4, 3: 3, 2: 2, 1: 1 }},

    /* Max - The max function returns the larger of the two arguments. The input parameters can be floating scalars or float vectors. In case of float vectors the operation is done component-wise. */

    max: {glsl: 'max(%1, %2);', output: { 4: 4, 3: 3, 2: 2, 1: 1 }},

    /* Clamp - The clamp function returns x if it is larger than minVal and smaller than maxVal. In case x is smaller than minVal, minVal is returned. If x is larger than maxVal, maxVal is returned. The input parameters can be floating scalars or float vectors. In case of float vectors the operation is done component-wise. */

    clamp: {glsl: 'clamp(%1, %2, %3);', output: { '4,1,1': 4, '3,1,1': 3, '2,1,1': 2, '1,1,1': 1 }},

    /* Mix - The mix function returns the linear blend of x and y, i.e. the product of x and (1 - a) plus the product of y and a. The input parameters can be floating scalars or float vectors. In case of float vectors the operation is done component-wise. */

    mix: {glsl: 'mix(%1, %2, %3);', output: { '4,4,1': 4, '3,3,1': 3, '2,2,1': 2, '4,4,1': 4, '1,1,1': 1 }},

    /* Step - The step function returns 0.0 if x is smaller then edge and otherwise 1.0. The input parameters can be floating scalars or float vectors. In case of float vectors the operation is done component-wise. */

    step: {glsl: 'step(%1, %2, %3);', output: { '1,1': 1, '1,2': 2, '1,3': 3, '1,4': 4 }},

    /* Smoothstep - The smoothstep function returns 0.0 if x is smaller then edge0 and 1.0 if x is larger than edge1. Otherwise the return value is interpolated between 0.0 and 1.0 using Hermite polynomirals. The input parameters can be floating scalars or float vectors. In case of float vectors the operation is done component-wise. */

    smoothstep: {glsl: 'smoothstep(%1);', output: { '1,1,1':1, '2,2,2':2, '3,3,3':3, '4,4,4':4 }},

    /* fragCoord - The fragCoord function returns the fragment's position in screenspace. */

    fragCoord: {glsl: 'gl_FragColor;', output: 4 },

    /* Sin - The sin function returns the sine of an angle in radians. The input parameter can be a floating scalar or a float vector. In case of a float vector the sine is calculated separately for every component. */

    sin: {glsl: 'sin(%1);', output: {'1':1, '2':2, '3':3, '4':4}},

    /* Cos - The cos function returns the cosine of an angle in radians. The input parameter can be a floating scalar or a float vector. */

    cos: {glsl: 'cos(%1);', output: {'1':1, '2':2, '3':3, '4':4}},

    /* Pow - The power function returns x raised to the power of y. The input parameters can be floating scalars or float vectors. In case of float vectors the operation is done component-wise. */

    pow: {glsl: 'pow(%1, %2);', output: {'1,1':1, '2,2':2, '3,3':3, '1,4':4}},

    /* Sqrt - The sqrt function returns the square root of x. The input parameter can be a floating scalar or a float vector. In case of a float vector the operation is done component-wise. */

    sqrt: {glsl: 'sqrt(%1);', output: {'1,1':1, '2,2':2, '3,3':3, '1,4':4}},

    /* time - The time function returns the elapsed time in the unix epoch in milliseconds.*/

    time: {glsl: 'time;', output: 1},

    /* The Add function takes two inputs, adds them together and outputs the result. This addition operation is performed on a per channel basis, meaning that the inputs' R channels get added, G channels get added, B channels get added, etc. Both inputs must have the same number of channels unless one of them is a single Constant value. Constants can be added to a vector with any number of inputs. */

    add: {glsl: '%1 + %2;', output:  {'1,1':1, '2,2':2, '3,3':3, '4,4':4, '2,1':2, '3,1':3, '4,1':4}},

    /* The subtract function takes two inputs, subtracts the first from the second,  and outputs the result. This addition operation is performed on a per channel basis, meaning that the inputs' R channels get subtracted, G channels get subtracted, B channels get subtracted, etc. Both inputs must have the same number of channels unless one of them is a single Constant value. Constants can be added to a vector with any number of inputs. */

    subtract: {glsl: '%1 - %2;', output: {'1,1':1, '2,2':2, '3,3':3, '4,4':4, '2,1':2, '3,1':3, '4,1':4}},

    /* The Add function takes two inputs, adds them together and outputs the result. This addition operation is performed on a per channel basis, meaning that the inputs' R channels get added, G channels get added, B channels get added, etc. Both inputs must have the same number of channels unless one of them is a single Constant value. Constants can be added to a vector with any number of inputs. */

    multiply: {glsl: '%1 * %2;', output: {'1,1':1, '2,2':2, '3,3':3, '4,4':4, '2,1':2, '3,1':3, '4,1':4}},

    /* The normal function returns the 3-dimensional surface normal, which is a vector that is perpendicular to the tangent plane at that point.*/

    normal: { glsl: 'vec4((v_Normal + 1.0) * 0.5, 1.0);', output: 4 },

    /* The uv function returns the 2-dimensional vector that maps the object's 3-dimensional vertices to a 2D plane. */

    uv: {glsl:'v_TextureCoordinate;', output: 2},

    /* The mesh position function returns the transformed fragment's position in world-space.  */

    meshPosition: {glsl:'(v_Position + 1.0) * 0.5;', output: 3},

    normalize: {glsl: 'normalize(%1)', output: {1: 1, 2: 2, 3: 3, 4: 4}},

    dot: {glsl: 'dot(%1, %2);', output: {'1,1': 1,'2,2':1, '3,3': 1, '4,4':1 }},

    /* The image function fetches the model's */

    image: {glsl:'texture2D(u_Textures[0], v_TextureCoordinate);', output: 4 },

    /* The constant function returns a static value which is defined at compile-time that cannot be changed dynamically.*/

    constant: {glsl: '%1;'},

    /* The Parameter expression has values that can be modified (dynamically during runtime in some cases) in a MaterialInstance of the base material containing the parameter. These expressions should be given unique names, via the Parameter Name property, to be used when identifying the specific parameter in the MaterialInstance. If two parameters of the same type have the same name in the same material, they will be assumed to be the same parameter. Changing the value of the parameter in the MaterialInstance would change the value of both the parameter expressions in the material. A default value for the parameter will also be set in the base material. This will be the value of the parameter in the MaterialInstance unless it is overridden and modified there. */

    parameter: {uniforms: {parameter: 1}, glsl: 'parameter;'},
    vec3: {glsl: 'vec3(%1);', output: 3},
    vec2: {glsl: 'vec2(%1);', output: 2}
};

expressions.registerExpression = function registerExpression(name, schema) {
    this[name] = function (inputs, options) {
        return new Material(name, schema, inputs, options);
    };
};

for (var name in snippets) {
    expressions.registerExpression(name, snippets[name]);
}

/**
 * Material is a public class that composes a material-graph out of expressions
 *
 *
 * @class Material
 * @constructor
 *
 * @param {Object} definiton of nascent expression with shader code, inputs and uniforms
 * @param {Array} list of Material expressions, images, or constant
 * @param {Object} map of uniform data of float, vec2, vec3, vec4
 */

function Material(name, chunk, inputs, options) {
    options = options || {};

    this.name = name;
    this.chunk = chunk;
    this.inputs = inputs ? (Array.isArray(inputs) ? inputs : [inputs]): [];
    this.uniforms = options.uniforms || {};
    this.varyings = options.varyings;
    this.attributes = options.attributes;

    if (options.texture) {
        this.texture = options.texture.__isATexture__ ? options.texture : TextureRegistry.register(null, options.texture);
    }

    this._id = Material.id++;

    this.invalidations = [];
    this.__isAMaterial__ = true;
}

Material.id = 2;

Material.prototype.setUniform = function setUniform(name, value) {
    this.uniforms[name] = value;

    this.invalidations.push(name);
};

module.exports = expressions;
expressions.Material = Material;

expressions.Texture = function (source) {
    if (typeof window === 'undefined') return console.error('Texture constructor cannot be run inside of a worker');
    return expressions.image([], { texture: source });
};

expressions.Custom = function (schema, inputs, uniforms) {
    return new Material('custom', {glsl: schema, output: 1, uniforms: uniforms || {}} , inputs);
};

function typeofConst(c) {
    if (Array.isArray(c)) return 'vec' + c.length + ' ';
    else return 'float ';
}<|endoftext|>


<commit_before>'use strict';

var mongoose = require('mongoose');
var Detalle = mongoose.model('Detalle');

var getErrorMessage = function(err){
  if (err.errors){
    for(var errName in err.errors){
      if(err.errors[errName].message) return err.errors[errName].message;
    }
  } else {
    return 'Error de servidor desconocido';
  }
};

exports.create = function(req, res){
  var detalle = new Detalle(req.body);
  detalle.creador = req.session.usuario.id;

  detalle.save(function(err){
    if (err) {
      return res.status(400).send({
        message: getErrorMessage(err)
      })
    } else {
      res.json(detalle);
    }
  });
};

exports.list = function(req, res){
  Detalle.find({}, function(err, detalles){
    if (err) {
      return res.status(400).send({
        message: getErrorMessage(err)
      })
    } else {
      res.json(detalles);
    }
  });
};

exports.read = function(req, res){
  res.json(req.detalle);
};

exports.update = function(req, res){
  var detalle = req.detalle;

  detalle.valor = req.body.valor;
  detalle.categoria = req.body.categoria;
  detalle.entregado = req.body.entregado;
  detalle.cargado = req.body.cargado;
  detalle.fecha = req.body.fecha;
  detalle.descripcion = req.body.descripcion;
  detalle.tipo = req.body.tipo;
  detalle.anexo = req.body.anexo;

  detalle.save(function(err){
    if (err) {
      return res.status(400).send({
        message: getErrorMessage(err)
      });
    } else {
      res.json(detalle);
    }
  });
};

exports.delete = function(req, res){
  var detalle = req.detalle;

  detalle.remove(function(err){
    if (err) {
      return res.status(400).send({
        message: getErrorMessage(err)
      })
    } else {
      res.json(detalle);
    }
  });
};

exports.detalleByID = function(req, res, next, id){
  Detalle.findById(id, function(err, detalle){
    if (err) return next(err);
    if (!detalle){
      return res.status(404).send({
        message: 'No existe el detalle'
      })
    }
    req.detalle = detalle;
    next();
  });
};

exports.listByCaja = function(req, res) {
  var idCaja = req.params.idCaja;
  Detalle.find({'caja': idCaja}, function(err, detalles){
    if (err) {
      return res.status(400).send({
        message: getErrorMessage(err)
      })
    } else {
      res.json(detalles);
    }
  });
};

exports.deleteByCaja = function(req, res) {
  var idCaja = req.params.idCaja;
  Detalle.find({'caja': idCaja}, function(err, detalles){
    if (err) {
      return res.status(400).send({
        message: getErrorMessage(err)
      })
    } else {
      for(var i in detalles){
        detalles[i].remove();
      }
      return res.status(200).send({
        message: 'Todos los detalles de ésta caja han sido eliminados'
      })
    }
  });
};

exports.reporteXSucursal = function(req, res) {
  if(req.body.categoria == 'Todas'){
    Detalle.aggregate(
      [
        { $project: {
            cargado: "$cargado",
            categoria: "$categoria",
            mes: { $month: "$fecha"},
            anio: { $year: "$fecha" },
            valor: "$valor",
            estado: "$estado"
          }
        },
        { $match: {
            anio: {
              $eq: Number(req.body.anio)
            },
            estado: {
              $eq: 'Aprobado'
            }
          }
        },
        { $group: {
            _id: {
              sucursal: "$cargado",
              mes: "$mes"
            },
            total: {
              $sum: "$valor"
            }
          }
        },
        { $group: {
            _id: "$_id.sucursal",
            meses: {
              $push: {
                mes: "$_id.mes",
                total: "$total"
              }
            }
          }
        },
        {
          $sort: { _id: 1}
        }
      ]
      , function(err, reporte){
        if(err){
          return res.status(500).send({
            message: getErrorMessage(err)
          });
        } else {
          return res.status(200).json(reporte);
        }
      }
    );
  } else {
    Detalle.aggregate(
      [
        { $project: {
            cargado: "$cargado",
            categoria: "$categoria",
            mes: { $month: "$fecha"},
            anio: { $year: "$fecha" },
            valor: "$valor",
            estado: "$estado"
          }
        },
        { $match: {
            anio: {
              $eq: Number(req.body.anio)
            },
            categoria: {
              $eq: req.body.categoria
            },
            estado: {
              $eq: 'Aprobado'
            }
          }
        },
        { $group: {
            _id: {
              sucursal: "$cargado",
              mes: "$mes"
            },
            total: {
              $sum: "$valor"
            }
          }
        },
        { $group: {
            _id: "$_id.sucursal",
            meses: {
              $push: {
                mes: "$_id.mes",
                total: "$total"
              }
            }
          }
        },
        { $sort: { _id: 1}
        }
      ]
      , function(err, reporte){
        if(err){
          return res.status(500).send({
            message: getErrorMessage(err)
          });
        } else {
          return res.status(200).json(reporte);
        }
      }
    );
  }

}

exports.yearOfDetalles = function(req, res){
  Detalle.aggregate([
    { $group: {
        _id: { $year: "$fecha" }
      }
    },
    { $sort: { _id: 1}
    }
  ], function(err, anios){
    if(err){
      return res.status(500).send({
        message: getErrorMessage(err)
      });
    } else {
      return res.status(200).json(anios);
    }
  });
};

exports.categoriaDetallesXYear = function(req, res){
  console.log(req.params.anio);
  Detalle.aggregate([
    { $project: {
        categoria: "$categoria",
        anio: { $year: "$fecha" }
      }
    },
    {
      $match: {
        anio: {
          $eq: Number(req.params.anio)
        }
      }
    },
    {
      $group: {
        _id: "$categoria"
      }
    }
  ], function(err, categorias){
    if(err){
      return res.status(500).send({
        message: getErrorMessage(err)
      });
    } else {
      return res.status(200).json(categorias);
    }
  });
};

exports.estadoByCaja = function(req, res) {
  var idCaja = req.params.idCaja;
  var estado = req.body.estado;
  console.log(req.body.estado);
  Detalle.find({'caja': idCaja}, function(err, detalles){
    if (err) {
      return res.status(400).send({
        message: getErrorMessage(err)
      })
    } else {
      for(var i in detalles){
        detalles[i].estado = estado;
        detalles[i].save();
      }
      return res.status(200).json(detalles);
    }
  });
};
<commit_msg>reporte escoger categorias por detalles aprobados<commit_after>'use strict';

var mongoose = require('mongoose');
var Detalle = mongoose.model('Detalle');

var getErrorMessage = function(err){
  if (err.errors){
    for(var errName in err.errors){
      if(err.errors[errName].message) return err.errors[errName].message;
    }
  } else {
    return 'Error de servidor desconocido';
  }
};

exports.create = function(req, res){
  var detalle = new Detalle(req.body);
  detalle.creador = req.session.usuario.id;

  detalle.save(function(err){
    if (err) {
      return res.status(400).send({
        message: getErrorMessage(err)
      })
    } else {
      res.json(detalle);
    }
  });
};

exports.list = function(req, res){
  Detalle.find({}, function(err, detalles){
    if (err) {
      return res.status(400).send({
        message: getErrorMessage(err)
      })
    } else {
      res.json(detalles);
    }
  });
};

exports.read = function(req, res){
  res.json(req.detalle);
};

exports.update = function(req, res){
  var detalle = req.detalle;

  detalle.valor = req.body.valor;
  detalle.categoria = req.body.categoria;
  detalle.entregado = req.body.entregado;
  detalle.cargado = req.body.cargado;
  detalle.fecha = req.body.fecha;
  detalle.descripcion = req.body.descripcion;
  detalle.tipo = req.body.tipo;
  detalle.anexo = req.body.anexo;

  detalle.save(function(err){
    if (err) {
      return res.status(400).send({
        message: getErrorMessage(err)
      });
    } else {
      res.json(detalle);
    }
  });
};

exports.delete = function(req, res){
  var detalle = req.detalle;

  detalle.remove(function(err){
    if (err) {
      return res.status(400).send({
        message: getErrorMessage(err)
      })
    } else {
      res.json(detalle);
    }
  });
};

exports.detalleByID = function(req, res, next, id){
  Detalle.findById(id, function(err, detalle){
    if (err) return next(err);
    if (!detalle){
      return res.status(404).send({
        message: 'No existe el detalle'
      })
    }
    req.detalle = detalle;
    next();
  });
};

exports.listByCaja = function(req, res) {
  var idCaja = req.params.idCaja;
  Detalle.find({'caja': idCaja}, function(err, detalles){
    if (err) {
      return res.status(400).send({
        message: getErrorMessage(err)
      })
    } else {
      res.json(detalles);
    }
  });
};

exports.deleteByCaja = function(req, res) {
  var idCaja = req.params.idCaja;
  Detalle.find({'caja': idCaja}, function(err, detalles){
    if (err) {
      return res.status(400).send({
        message: getErrorMessage(err)
      })
    } else {
      for(var i in detalles){
        detalles[i].remove();
      }
      return res.status(200).send({
        message: 'Todos los detalles de ésta caja han sido eliminados'
      })
    }
  });
};

exports.reporteXSucursal = function(req, res) {
  if(req.body.categoria == 'Todas'){
    Detalle.aggregate(
      [
        { $project: {
            cargado: "$cargado",
            categoria: "$categoria",
            mes: { $month: "$fecha"},
            anio: { $year: "$fecha" },
            valor: "$valor",
            estado: "$estado"
          }
        },
        { $match: {
            anio: {
              $eq: Number(req.body.anio)
            },
            estado: {
              $eq: 'Aprobado'
            }
          }
        },
        { $group: {
            _id: {
              sucursal: "$cargado",
              mes: "$mes"
            },
            total: {
              $sum: "$valor"
            }
          }
        },
        { $group: {
            _id: "$_id.sucursal",
            meses: {
              $push: {
                mes: "$_id.mes",
                total: "$total"
              }
            }
          }
        },
        {
          $sort: { _id: 1}
        }
      ]
      , function(err, reporte){
        if(err){
          return res.status(500).send({
            message: getErrorMessage(err)
          });
        } else {
          return res.status(200).json(reporte);
        }
      }
    );
  } else {
    Detalle.aggregate(
      [
        { $project: {
            cargado: "$cargado",
            categoria: "$categoria",
            mes: { $month: "$fecha"},
            anio: { $year: "$fecha" },
            valor: "$valor",
            estado: "$estado"
          }
        },
        { $match: {
            anio: {
              $eq: Number(req.body.anio)
            },
            categoria: {
              $eq: req.body.categoria
            },
            estado: {
              $eq: 'Aprobado'
            }
          }
        },
        { $group: {
            _id: {
              sucursal: "$cargado",
              mes: "$mes"
            },
            total: {
              $sum: "$valor"
            }
          }
        },
        { $group: {
            _id: "$_id.sucursal",
            meses: {
              $push: {
                mes: "$_id.mes",
                total: "$total"
              }
            }
          }
        },
        { $sort: { _id: 1}
        }
      ]
      , function(err, reporte){
        if(err){
          return res.status(500).send({
            message: getErrorMessage(err)
          });
        } else {
          return res.status(200).json(reporte);
        }
      }
    );
  }

}

exports.yearOfDetalles = function(req, res){
  Detalle.aggregate([
    { $project: {
        fecha: "$fecha",
        estado: "$estado"
      }
    },
    {
      $match: {
        estado: {
          $eq: 'Aprobado'
        }
      }
    },
    { $group: {
        _id: { $year: "$fecha" }
      }
    },
    { $sort: { _id: 1}
    }
  ], function(err, anios){
    if(err){
      return res.status(500).send({
        message: getErrorMessage(err)
      });
    } else {
      return res.status(200).json(anios);
    }
  });
};

exports.categoriaDetallesXYear = function(req, res){
  console.log(req.params.anio);
  Detalle.aggregate([
    { $project: {
        categoria: "$categoria",
        anio: { $year: "$fecha" },
        estado: "$estado"
      }
    },
    {
      $match: {
        anio: {
          $eq: Number(req.params.anio)
        },
        estado: {
          $eq: 'Aprobado'
        }
      }
    },
    {
      $group: {
        _id: "$categoria"
      }
    }
  ], function(err, categorias){
    if(err){
      return res.status(500).send({
        message: getErrorMessage(err)
      });
    } else {
      return res.status(200).json(categorias);
    }
  });
};

exports.estadoByCaja = function(req, res) {
  var idCaja = req.params.idCaja;
  var estado = req.body.estado;
  console.log(req.body.estado);
  Detalle.find({'caja': idCaja}, function(err, detalles){
    if (err) {
      return res.status(400).send({
        message: getErrorMessage(err)
      })
    } else {
      for(var i in detalles){
        detalles[i].estado = estado;
        detalles[i].save();
      }
      return res.status(200).json(detalles);
    }
  });
};
<|endoftext|>


<commit_before>// dependencies
//
import React from 'react';
import classnames from 'classnames';

import TextInput from './form/TextInput';

class Form extends React.Component {
    render() {
        return (
            <form>
                {this.props.children}
            </form>
        );
    }
}

// add the "sub-components"
//
Form.TextInput = TextInput;

// export the component
//
export default Form;
<commit_msg>updated dependencies<commit_after>// dependencies
//
import React from 'react';
import update from 'react-addons-update';
import uniqueId from 'lodash/uniqueId';
import classnames from 'classnames';

import Alert from './Alert';
import TextInput from './form/TextInput';

class Form extends React.Component {
    render() {
        return (
            <form>
                {this.props.children}
            </form>
        );
    }
}

// add the "sub-components"
//
Form.TextInput = TextInput;

// export the component
//
export default Form;
<|endoftext|>


<commit_before>var Formats = require('../../Formats');
var MapData = require('../../mapdata/MapData');
var ParseTilesets = require('./ParseTilesets');
var ParseTileLayers = require('./ParseTileLayers');

/**
 * Parses a Weltmeister JSON object into a new MapData object.
 *
 * @param {string} name - The name of the tilemap, used to set the name on the MapData.
 * @param {object} json - The Weltmeister JSON object.
 * @param {boolean} insertNull - Controls how empty tiles, tiles with an index of -1, in the map
 * data are handled. If `true`, empty locations will get a value of `null`. If `false`, empty
 * location will get a Tile object with an index of -1. If you've a large sparsely populated map and
 * the tile data doesn't need to change then setting this value to `true` will help with memory
 * consumption. However if your map is small or you need to update the tiles dynamically, then leave
 * the default value set.
 */
var ParseWeltmeister = function (name, json, insertNull)
{
    if (json.layer.length === 0)
    {
        console.warn('No layers found in the Weltmeister map: ' + name);
        return null;
    }

    var width = 0;
    var height = 0;
    for (var i = 0; i < json.layer.length; i++)
    {
        if (json.layer.width > width) { width = json.layer.width; }
        if (json.layer.height > height) { height = json.layer.height; }
    }

    var mapData = new MapData({
        width: width,
        height: height,
        name: name,
        tileWidth: json.layer[0].tilesize,
        tileHeight: json.layer[0].tilesize,
        format: Formats.WELTMEISTER
    });

    mapData.layers = ParseTileLayers(json, insertNull);
    mapData.tilesets = ParseTilesets(json);

    return mapData;
};

module.exports = ParseWeltmeister;
<commit_msg>Bug fix: weltmeister parser<commit_after>var Formats = require('../../Formats');
var MapData = require('../../mapdata/MapData');
var ParseTilesets = require('./ParseTilesets');
var ParseTileLayers = require('./ParseTileLayers');

/**
 * Parses a Weltmeister JSON object into a new MapData object.
 *
 * @param {string} name - The name of the tilemap, used to set the name on the MapData.
 * @param {object} json - The Weltmeister JSON object.
 * @param {boolean} insertNull - Controls how empty tiles, tiles with an index of -1, in the map
 * data are handled. If `true`, empty locations will get a value of `null`. If `false`, empty
 * location will get a Tile object with an index of -1. If you've a large sparsely populated map and
 * the tile data doesn't need to change then setting this value to `true` will help with memory
 * consumption. However if your map is small or you need to update the tiles dynamically, then leave
 * the default value set.
 */
var ParseWeltmeister = function (name, json, insertNull)
{
    if (json.layer.length === 0)
    {
        console.warn('No layers found in the Weltmeister map: ' + name);
        return null;
    }

    var width = 0;
    var height = 0;
    for (var i = 0; i < json.layer.length; i++)
    {
        if (json.layer[i].width > width) { width = json.layer[i].width; }
        if (json.layer[i].height > height) { height = json.layer[i].height; }
    }

    var mapData = new MapData({
        width: width,
        height: height,
        name: name,
        tileWidth: json.layer[0].tilesize,
        tileHeight: json.layer[0].tilesize,
        format: Formats.WELTMEISTER
    });

    mapData.layers = ParseTileLayers(json, insertNull);
    mapData.tilesets = ParseTilesets(json);

    return mapData;
};

module.exports = ParseWeltmeister;
<|endoftext|>


<commit_before>function generateId() {
    var id = new Date().getTime();
    return id;
}

function addProject(projName, projVersion, iconPath, projDir) {
    var id = generateId();
    var projectObj = {};
    projectObj.id = id;
    projectObj.projDir = projDir;

    if (localStorage["projects"]) {
        // retrieve exsiting projects to appending a new project
        var projects = JSON.parse(localStorage["projects"]);
        projects.unshift(projectObj);
        localStorage["projects"] = JSON.stringify(projects);
        console.log(JSON.stringify(projects));
    } else {
        var myProjects = new Array();
        myProjects.push(projectObj);
        localStorage["projects"] = JSON.stringify(myProjects);
        console.log(JSON.stringify(myProjects));
    }

    // render newly added project to GUI & set it as the active widget
    addProjectWidget(id, projName, projVersion, iconPath, projDir);
    setActiveWidget(id, projDir);
}

function getProjects() {
    if (localStorage["projects"]) {
        var projects = JSON.parse(localStorage["projects"]);
        var index = projects.length;

        console.log(JSON.stringify(projects));

        for (var i=0;i<index;i++) {

            var id = projects[i].id;
            var projDir = projects[i].projDir

            getProjectConfig(id, projDir, i);
        }
    }
}

function getProjectConfig(id, projDir, i) {
    var filename = projDir + "/www/config.xml";

    fs.readFile(filename, 'utf8', function(err, data) {
        if (err) throw err;

        var iconPath = projDir + "/www/"

        global.jQuery.xmlDoc = global.jQuery.parseXML(data);
        global.jQuery.xml = global.jQuery(global.jQuery.xmlDoc);

        // get the project name
        var projectName = global.jQuery.xml.find("name").text();

        // get the project version
        var projectVersion = global.jQuery.xml.find("widget").attr("version");

        // get the app icon
        var projectIcon = global.jQuery.xml.find("icon").attr("src");
        iconPath += projectIcon;

        addProjectWidget(id, projectName, projectVersion, iconPath, projDir);

        if (i == 0) {
            setActiveWidget(id, projDir);
        }
    });
}

function removeProjectById(currentId) {

    // retrieve exsiting projects to find the project to remove
    var projects = JSON.parse(localStorage["projects"]);
    var index = projects.length;

    for (var i=0;i<index;i++) {

        var id = projects[i].id;

        if (id == currentId) {
            projects.splice(i, 1);
            break;
        }
    }

    localStorage["projects"] = JSON.stringify(projects);

    console.log(JSON.stringify(projects));

    // hide the remove project overlay
    global.jQuery("#removeProjectOverlay").hide();
    global.jQuery("#overlay-bg").hide();

    index = projects.length;

     // set new active widget if there are still projects, otherwise disable the remove button
    if (index > 0) {
        setActiveWidget(projects[0].id, projects[0].projDir);
    } else {
        global.jQuery("#minus").prop("disabled", true);
    }

}
<commit_msg>[#55] modified addProject to use array.push instead of array.unshift<commit_after>function generateId() {
    var id = new Date().getTime();
    return id;
}

function addProject(projName, projVersion, iconPath, projDir) {
    var id = generateId();
    var projectObj = {};
    projectObj.id = id;
    projectObj.projDir = projDir;

    if (localStorage["projects"]) {
        // retrieve exsiting projects to appending a new project
        var projects = JSON.parse(localStorage["projects"]);
        projects.push(projectObj);
        localStorage["projects"] = JSON.stringify(projects);
        console.log(JSON.stringify(projects));
    } else {
        var myProjects = new Array();
        myProjects.push(projectObj);
        localStorage["projects"] = JSON.stringify(myProjects);
        console.log(JSON.stringify(myProjects));
    }

    // render newly added project to GUI & set it as the active widget
    addProjectWidget(id, projName, projVersion, iconPath, projDir);
    setActiveWidget(id, projDir);
}

function getProjects() {
    if (localStorage["projects"]) {
        var projects = JSON.parse(localStorage["projects"]);
        var index = projects.length;

        console.log(JSON.stringify(projects));

        for (var i=0;i<index;i++) {

            var id = projects[i].id;
            var projDir = projects[i].projDir

            getProjectConfig(id, projDir, i);
        }
    }
}

function getProjectConfig(id, projDir, i) {
    var filename = projDir + "/www/config.xml";

    fs.readFile(filename, 'utf8', function(err, data) {
        if (err) throw err;

        var iconPath = projDir + "/www/"

        global.jQuery.xmlDoc = global.jQuery.parseXML(data);
        global.jQuery.xml = global.jQuery(global.jQuery.xmlDoc);

        // get the project name
        var projectName = global.jQuery.xml.find("name").text();

        // get the project version
        var projectVersion = global.jQuery.xml.find("widget").attr("version");

        // get the app icon
        var projectIcon = global.jQuery.xml.find("icon").attr("src");
        iconPath += projectIcon;

        addProjectWidget(id, projectName, projectVersion, iconPath, projDir);

        if (i == 0) {
            setActiveWidget(id, projDir);
        }
    });
}

function removeProjectById(currentId) {

    // retrieve exsiting projects to find the project to remove
    var projects = JSON.parse(localStorage["projects"]);
    var index = projects.length;

    for (var i=0;i<index;i++) {

        var id = projects[i].id;

        if (id == currentId) {
            projects.splice(i, 1);
            break;
        }
    }

    localStorage["projects"] = JSON.stringify(projects);

    console.log(JSON.stringify(projects));

    // hide the remove project overlay
    global.jQuery("#removeProjectOverlay").hide();
    global.jQuery("#overlay-bg").hide();

    index = projects.length;

     // set new active widget if there are still projects, otherwise disable the remove button
    if (index > 0) {
        setActiveWidget(projects[0].id, projects[0].projDir);
    } else {
        global.jQuery("#minus").prop("disabled", true);
    }

}
<|endoftext|>


<commit_before>/*global define: true */
/*jslint browser:true  vars: true */
define([
    'bluebird',
    'kb_common_asyncQueue'
],
    function (Promise, asyncQueue) {
        function factory(config) {
            // Very simple message system.
            var channels = {},
                listeners = {},
                subId = 0,
                queue = asyncQueue.make();

            function nextSubId() {
                subId += 1;
                return 'sub_' + subId;
            }
            function fail(msg) {
                throw new Error(msg);
            }
            function receive(subDef) {
                var channelName = subDef.chan || subDef.channel || 'default',
                    messageName = subDef.msg || subDef.message || fail('Message is required for a sub');

                // Get the channel, and create it if it doesn't exist.
                var channel = channels[channelName];
                if (!channel) {
                    channel = {
                        messages: {}
                    };
                    channels[channelName] = channel;
                }

                // Get the message definitions for this message, create if doesn't exist
                var messageListener = channel.messages[messageName];
                if (!messageListener) {
                    messageListener = {
                        listeners: [],
                        byId: {}
                    };
                    channel.messages[messageName] = messageListener;
                }

                // Add our message definition
                var subId = nextSubId();
                subDef.subId = subId;
                messageListener.byId[subId] = subDef;
                messageListener.listeners.push(subDef);
                return {
                    chan: channelName,
                    msg: messageName,
                    id: subId
                };
            }
            function unreceive(sub) {
                var channel = channels[sub.chan];
                if (!channel) {
                    return false;
                }
                var messageListener = channel.messages[sub.msg];
                if (!messageListener) {
                    return false;
                }

                var subDef = messageListener.byId[sub.id];
                if (!subDef) {
                    return false;
                }
                delete messageListener.byId[sub.id];
                messageListener.listeners = messageListener.listeners.filter(function (item) {
                    if (item.subId === sub.id) {
                        return false;
                    }
                    return true;
                });
                return true;
            }
            // syncronous publication
            // TODO: async version.
            function emptyPromiseList() {
                return [Promise.resolve()];
            }
            function send(pubDef) {
                var channelName = pubDef.chan || pubDef.channel,
                    messageName = pubDef.msg || pubDef.message;

                var channel = channels[channelName];
                if (!channel) {
                    return emptyPromiseList();
                }
                var messageListener = channel.messages[messageName];
                if (!messageListener) {
                    return emptyPromiseList();
                }

                var listeners = messageListener.listeners;
                var ps = Promise.all(listeners.map(function (subDef) {
                    return new Promise(function (resolve, reject) {
                        queue.addItem({
                            channel: channelName,
                            message: messageName,
                            onRun: function () {
                                try {
                                    resolve(subDef.handler(pubDef.data));
                                } catch (ex) {
                                    reject(new UIError{
                                        type: 'RuntimeError',
                                        reason: 'MessageHandlerError',
                                        message: 'Exception running message ' + messageName + ', sub ' + subId,
                                        data: ex,
                                        suggestion: 'This is an application error, not your fault'
                                    });
                                }
                            },
                            onError: function (err) {
                                reject(err);
                            }
                        });
                    });
                }).map(function (promise) {
                    return promise.reflect();
                }));
                if (pubDef.propogate) {
                    return ps;
                } else {
                    return ps.catch(function (err) {
                        console.log('messenger send error');
                        console.log(err);
                    });
                }
            }
            return {
                receive: receive,
                unreceive: unreceive,
                send: send
            };
        }
        ;

        return {
            make: function (config) {
                return factory(config);
            }
        };

    });<commit_msg>fix reject without proper error object<commit_after>/*global define: true */
/*jslint browser:true  vars: true */
define([
    'bluebird',
    'kb_common_asyncQueue',
    'kb_common_lang'
],
    function (Promise, asyncQueue, lang) {
        function factory(config) {
            // Very simple message system.
            var channels = {},
                listeners = {},
                subId = 0,
                queue = asyncQueue.make();

            function nextSubId() {
                subId += 1;
                return 'sub_' + subId;
            }
            function fail(msg) {
                throw new Error(msg);
            }
            function receive(subDef) {
                var channelName = subDef.chan || subDef.channel || 'default',
                    messageName = subDef.msg || subDef.message || fail('Message is required for a sub');

                // Get the channel, and create it if it doesn't exist.
                var channel = channels[channelName];
                if (!channel) {
                    channel = {
                        messages: {}
                    };
                    channels[channelName] = channel;
                }

                // Get the message definitions for this message, create if doesn't exist
                var messageListener = channel.messages[messageName];
                if (!messageListener) {
                    messageListener = {
                        listeners: [],
                        byId: {}
                    };
                    channel.messages[messageName] = messageListener;
                }

                // Add our message definition
                var subId = nextSubId();
                subDef.subId = subId;
                messageListener.byId[subId] = subDef;
                messageListener.listeners.push(subDef);
                return {
                    chan: channelName,
                    msg: messageName,
                    id: subId
                };
            }
            function unreceive(sub) {
                var channel = channels[sub.chan];
                if (!channel) {
                    return false;
                }
                var messageListener = channel.messages[sub.msg];
                if (!messageListener) {
                    return false;
                }

                var subDef = messageListener.byId[sub.id];
                if (!subDef) {
                    return false;
                }
                delete messageListener.byId[sub.id];
                messageListener.listeners = messageListener.listeners.filter(function (item) {
                    if (item.subId === sub.id) {
                        return false;
                    }
                    return true;
                });
                return true;
            }
            // syncronous publication
            // TODO: async version.
            function emptyPromiseList() {
                return [Promise.resolve()];
            }
            function send(pubDef) {
                var channelName = pubDef.chan || pubDef.channel,
                    messageName = pubDef.msg || pubDef.message;

                var channel = channels[channelName];
                if (!channel) {
                    return emptyPromiseList();
                }
                var messageListener = channel.messages[messageName];
                if (!messageListener) {
                    return emptyPromiseList();
                }

                var listeners = messageListener.listeners;
                var ps = Promise.all(listeners.map(function (subDef) {
                    return new Promise(function (resolve, reject) {
                        queue.addItem({
                            channel: channelName,
                            message: messageName,
                            onRun: function () {
                                try {
                                    resolve(subDef.handler(pubDef.data));
                                } catch (ex) {
                                    reject(new lang.UIError({
                                        type: 'RuntimeError',
                                        reason: 'MessageHandlerError',
                                        message: 'Exception running message ' + messageName + ', sub ' + subId,
                                        data: ex,
                                        suggestion: 'This is an application error, not your fault'
                                    }));
                                }
                            },
                            onError: function (err) {
                                reject(err);
                            }
                        });
                    });
                }).map(function (promise) {
                    return promise.reflect();
                }));
                if (pubDef.propogate) {
                    return ps;
                } else {
                    return ps.catch(function (err) {
                        console.log('messenger send error');
                        console.log(err);
                    });
                }
            }
            return {
                receive: receive,
                unreceive: unreceive,
                send: send
            };
        }
        ;

        return {
            make: function (config) {
                return factory(config);
            }
        };

    });<|endoftext|>