<commit_before>var buildConfig = require('./scripts/build/config');
var gulp = require('gulp');
var path = require('path');
var argv = require('yargs').argv;
var del = require('del');
var rename = require('gulp-rename');
var through2 = require('through2');
var runSequence = require('run-sequence');
var watch = require('gulp-watch');
var babel = require('gulp-babel');
var tsc = require('gulp-typescript');
var cache = require('gulp-cached');
var minimist = require('minimist');

function getBabelOptions(moduleName, moduleType) {
  return {
    optional: ['es7.decorators'],
    modules: moduleType || "system",
    moduleIds: true,
    getModuleId: function(name) {
      if (moduleName == "e2e"){
        return name.replace(/^.*\/test\/[^\/]*\//, '');
      }
      else if (moduleName == "demos"){
        return name.replace(/^(.*?)\//, '')
      }

      return moduleName + '/' + name.split('/test').join('');
    }
  }
}

var tscOptions = {
  target: 'ES6',
  allowNonTsExtensions: true,
  isolatedModules: true,
  emitDecoratorMetadata: true,
  experimentalDecorators: true,
  noEmitOnError: false,  // ignore errors
  rootDir: '.'
}
var tscReporter = {
  error: function (error) {
    console.error(error.message);
  }
};

var flagConfig = {
  string: ['port', 'version', 'ngVersion', 'animations'],
  alias: {'p': 'port', 'v': 'version', 'a': 'ngVersion'},
  default: { port: 8000 }
};

var flags = minimist(process.argv.slice(2), flagConfig);

gulp.task('build', function(done) {
  runSequence(
    'bundle',
    'e2e',
    'demos',
    'sass',
    'fonts',
    done
  );
})

gulp.task('clean.build', function(done) {
  runSequence('clean', 'build', done);
})

gulp.task('watch', function(done) {
  runSequence(
    'build',
    'serve',
    function() {
      watch([
          'ionic/**/*.ts',
          '!ionic/components/*/test/**/*',
          '!ionic/util/test/*'
        ],
        function(file) {
          if (file.event === "unlink") {
            var basePath = file.base.substring(0, file.base.lastIndexOf("ionic/"));
            var relPath = file.history[0].replace(basePath, "").replace(".ts", ".js");

            var es6Path = basePath + "dist/src/es6/" + relPath;
            var commonPath = basePath + "dist/src/es5/common/" + relPath;
            var systemPath = basePath + "dist/src/es5/system/" + relPath;

            delete cache.caches.transpile[file.history[0]];

            del([es6Path, commonPath, systemPath], function(){
              gulp.start('bundle');
            });
          } else {
            gulp.start('bundle');
          }
        }
      );

      watch('demos/**/*', function() {
        gulp.start('demos');
      });

      watch('ionic/components/*/test/**/*', function(file) {
        if (file.event === "unlink") {
          var paths = file.history[0].split("ionic/components/");
          var basePath = paths[0],
              relPath = paths[1].split("/test").join("").replace(".ts", ".js");

          var distPath = basePath + "dist/e2e/" + relPath;

          delete cache.caches.e2e[file.history[0]];

          del([distPath], function(){
            gulp.start('e2e');
          });
        } else {
          gulp.start('e2e');
        }
      });

      watch('ionic/**/*.scss', function() {
        gulp.start('sass');
      });

      done();
    }
  );
});

gulp.task('serve', function() {
  var connect = require('gulp-connect');
  connect.server({
    root: 'dist',
    port: flags.port,
    livereload: false
  });
});

gulp.task('clean', function(done) {
  del(['dist/**', '!dist', '!dist/ionic-site', '!dist/ionic-site/**/*'], done);
});

function transpile(moduleType) {
  var stream = gulp.src([
      'ionic/**/*.ts',
      '!ionic/components/*/test/**/*',
      '!ionic/util/test/*'
    ])
   .pipe(cache('transpile', { optimizeMemory: true }))
   .pipe(tsc(tscOptions, null, tscReporter))
   .on('error', function(error) {
     stream.emit('end');
   })
   .pipe(gulp.dest('dist/src/es6/ionic'))
   .pipe(babel(getBabelOptions('ionic', moduleType)))
   .on('error', function (err) {
     console.log("ERROR: " + err.message);
     this.emit('end');
   })
   .pipe(gulp.dest('dist/src/es5/' + moduleType + '/ionic'))

  return stream;
}

gulp.task('transpile.system', function() { return transpile("system"); });
gulp.task('transpile.common', function() {
  // necessary for publish task, remove if we ever do incremental builds with cjs
  cache.caches && delete cache.caches.transpile;
  return transpile("common");
});
gulp.task('transpile', ['transpile.system']);

gulp.task('bundle.ionic', ['transpile'], function() {
  var insert = require('gulp-insert');
  var concat = require('gulp-concat');

  var prepend = [];

  // force the web animations api polyfill to kick in
  if (flags.animations == 'polyfill') {
    prepend.push('window.Element.prototype.animate=undefined;');
  }

  return gulp.src([
      'dist/src/es5/system/ionic/**/*.js'
    ])
    .pipe(concat('ionic.js'))
    .pipe(insert.prepend(prepend.join('\n')))
    .pipe(gulp.dest('dist/js/'));
    //TODO minify + sourcemaps
});

gulp.task('bundle', ['bundle.ionic'], function() {
  var concat = require('gulp-concat');

  return gulp.src(buildConfig.scripts)
    .pipe(concat('ionic.bundle.js'))
    .pipe(gulp.dest('dist/js'));
})

gulp.task('tests', function() {
  return gulp.src('ionic/**/test/**/*.spec.ts')
    .pipe(tsc(tscOptions, null, tscReporter))
    .pipe(babel(getBabelOptions('dist/tests')))
    .pipe(rename(function(file) {
      var regex = new RegExp(path.sep + 'test(' + path.sep + '|$)');
      file.dirname = file.dirname.replace(regex, path.sep);
    }))
    .pipe(gulp.dest('dist/tests'))
})

gulp.task('e2e', function() {
  var gulpif = require('gulp-if');
  var lazypipe = require('lazypipe');
  var _ = require('lodash');
  var fs = require('fs');
  var VinylFile = require('vinyl');

  var buildTest = lazypipe()
             //.pipe(traceur, traceurOptions)
             .pipe(tsc, tscOptions, null, tscReporter)
             .pipe(babel, getBabelOptions('e2e'))

  var buildE2ETest = lazypipe()
             //.pipe(traceur, traceurOptions)
             .pipe(tsc, tscOptions, null, tscReporter)
             .pipe(babel)

  var indexTemplate = _.template(
   fs.readFileSync('scripts/e2e/e2e.template.html')
  )({
   buildConfig: buildConfig

  })
  var testTemplate = _.template( fs.readFileSync('scripts/e2e/e2e.template.js') )

  var platforms = [
    'android',
    'ios',
  ];

  // Get each test folder with gulp.src
  return gulp.src(['ionic/components/*/test/*/**/*', '!ionic/components/*/test/*/**/*.spec.ts'])
    .pipe(cache('e2e', { optimizeMemory: true }))
    .pipe(gulpif(/e2e.ts$/, buildE2ETest()))
    .pipe(gulpif(/.ts$/, buildTest()))
    .on('error', function (err) {
      console.log("ERROR: " + err.message);
      this.emit('end');
    })
    .pipe(gulpif(/index.js$/, createIndexHTML())) //TSC changes .ts to .js
    .pipe(rename(function(file) {
      file.dirname = file.dirname.replace(path.sep + 'test' + path.sep, path.sep)
    }))
    .pipe(gulpif(/e2e.js$/, createPlatformTests()))
    .pipe(gulp.dest('dist/e2e/'))

  function createIndexHTML() {
    return through2.obj(function(file, enc, next) {
      this.push(new VinylFile({
        base: file.base,
        contents: new Buffer(indexTemplate),
        path: path.join(path.dirname(file.path), 'index.html'),
      }));
      next(null, file);
    });
  }

  function createPlatformTests(file) {
    return through2.obj(function(file, enc, next) {
      var self = this
      var relativePath = path.dirname(file.path.replace(/^.*?ionic(\/|\\)components(\/|\\)/, ''))
      var contents = file.contents.toString()
      platforms.forEach(function(platform) {
        var platformContents = testTemplate({
          contents: contents,
          buildConfig: buildConfig,
          relativePath: relativePath,
          platform: platform
        })
        self.push(new VinylFile({
          base: file.base,
          contents: new Buffer(platformContents),
          path: file.path.replace(/e2e.js$/, platform + '.e2e.js')
        }))
      })
      next()
    })
  }
});

gulp.task('sass', function() {
  var sass = require('gulp-sass');
  var autoprefixer = require('gulp-autoprefixer');
  return gulp.src('ionic/ionic.scss')
    .pipe(sass()
      .on('error', sass.logError)
    )
    .pipe(autoprefixer(buildConfig.autoprefixer))
    .pipe(gulp.dest('dist/css/'));
});

gulp.task('fonts', function() {
  return gulp.src(['ionic/fonts/**/*.ttf', 'ionic/fonts/**/*.woff'])
    .pipe(gulp.dest('dist/fonts'));
});

require('./scripts/snapshot/snapshot.task')(gulp, argv, buildConfig);

gulp.task('karma', ['tests'], function() {
  var karma = require('karma').server;
  return karma.start({ configFile: __dirname + '/scripts/karma/karma.conf.js' })
});

gulp.task('karma-watch', function() {
  var karma = require('karma').server;
  return karma.start({ configFile: __dirname + '/scripts/karma/karma-watch.conf.js' })
});

gulp.task('copy.ts', function() {
  return gulp.src([
      'ionic/**/*.ts',
      '!ionic/components/*/test/**/*',
      '!ionic/util/test/*'
    ])
    .pipe(gulp.dest('dist/src/typescript'));
})

gulp.task('copy.scss', function() {
  return gulp.src([
      'ionic/**/*.scss',
      '!ionic/components/*/test/**/*',
      '!ionic/util/test/*'
    ])
    .pipe(gulp.dest('dist/src/scss'));
})

gulp.task('src', function(done){
  runSequence(
    'clean',
    ['bundle', 'sass', 'fonts', 'copy.ts', 'copy.scss'],
    'transpile.common',
    done
  );
})

require('./scripts/docs/gulp-tasks')(gulp, flags)

gulp.task('demos', function(){
  var gulpif = require('gulp-if');
  var lazypipe = require('lazypipe');
  var _ = require('lodash');
  var fs = require('fs');
  var VinylFile = require('vinyl');

  var buildTest = lazypipe()
    .pipe(tsc, tscOptions, null, tscReporter)
    .pipe(babel, getBabelOptions('demos'))

  var indexTemplate = _.template(fs.readFileSync('scripts/demos/index.template.html'))();

  return gulp.src(['demos/**/*'])
    .pipe(cache('demos', { optimizeMemory: true }))
    .pipe(gulpif(/.ts$/, buildTest()))
    .pipe(gulpif(/index.js$/, createIndexHTML())) //TSC changes .ts to .js
    .pipe(gulp.dest('dist/demos'))

  function createIndexHTML() {
    return through2.obj(function(file, enc, next) {
      this.push(new VinylFile({
        base: file.base,
        contents: new Buffer(indexTemplate),
        path: path.join(path.dirname(file.path), 'index.html'),
      }));
      next(null, file);
    });
  }
})

gulp.task('publish', function(done) {
  var version = flags.version;
  var ngVersion = flags.ngVersion;
  if (!version || !ngVersion) {
    console.error("\nERR: You need to provide a version for Ionic as well as " +
                  "the version of Angular it depends on.\n\n" +
                  "gulp publish -v {version} -a {ngVersion}\n");
    return
  }
  if (version.indexOf("alpha") + version.indexOf("-") > -2 ||
      ngVersion.indexOf("alpha") + ngVersion.indexOf("-") > -2)
  {
    console.error("\n ERR: Just provide version number. Instead of 2.0.0-alpha.10, just enter 10\n");
    return
  }

  var exec = require('child_process').exec;
  var _ = require('lodash');
  var fs = require('fs');

  runSequence(
    'clean',
    ['bundle', 'sass', 'fonts', 'copy.ts', 'copy.scss'],
    'transpile.common',
    function() {
      var packageJSONTemplate = _.template(fs.readFileSync('scripts/npm/package.json'));
      packageJSONContents = packageJSONTemplate({ 'version': version, 'ngVersion': ngVersion });
      fs.writeFileSync("dist/package.json", packageJSONContents);

      // publish to npm
      exec('cd dist && npm publish', function (err, stdout, stderr) {
        console.log(stdout);
        console.error(stderr);
        done();
      });
    }
  )
})
<commit_msg>add web-animations to ionic package<commit_after>var buildConfig = require('./scripts/build/config');
var gulp = require('gulp');
var path = require('path');
var argv = require('yargs').argv;
var del = require('del');
var rename = require('gulp-rename');
var through2 = require('through2');
var runSequence = require('run-sequence');
var watch = require('gulp-watch');
var babel = require('gulp-babel');
var tsc = require('gulp-typescript');
var cache = require('gulp-cached');
var minimist = require('minimist');

function getBabelOptions(moduleName, moduleType) {
  return {
    optional: ['es7.decorators'],
    modules: moduleType || "system",
    moduleIds: true,
    getModuleId: function(name) {
      if (moduleName == "e2e"){
        return name.replace(/^.*\/test\/[^\/]*\//, '');
      }
      else if (moduleName == "demos"){
        return name.replace(/^(.*?)\//, '')
      }

      return moduleName + '/' + name.split('/test').join('');
    }
  }
}

var tscOptions = {
  target: 'ES6',
  allowNonTsExtensions: true,
  isolatedModules: true,
  emitDecoratorMetadata: true,
  experimentalDecorators: true,
  noEmitOnError: false,  // ignore errors
  rootDir: '.'
}
var tscReporter = {
  error: function (error) {
    console.error(error.message);
  }
};

var flagConfig = {
  string: ['port', 'version', 'ngVersion', 'animations'],
  alias: {'p': 'port', 'v': 'version', 'a': 'ngVersion'},
  default: { port: 8000 }
};

var flags = minimist(process.argv.slice(2), flagConfig);

gulp.task('build', function(done) {
  runSequence(
    'bundle',
    'e2e',
    'demos',
    'sass',
    'fonts',
    done
  );
})

gulp.task('clean.build', function(done) {
  runSequence('clean', 'build', done);
})

gulp.task('watch', function(done) {
  runSequence(
    'build',
    'serve',
    function() {
      watch([
          'ionic/**/*.ts',
          '!ionic/components/*/test/**/*',
          '!ionic/util/test/*'
        ],
        function(file) {
          if (file.event === "unlink") {
            var basePath = file.base.substring(0, file.base.lastIndexOf("ionic/"));
            var relPath = file.history[0].replace(basePath, "").replace(".ts", ".js");

            var es6Path = basePath + "dist/src/es6/" + relPath;
            var commonPath = basePath + "dist/src/es5/common/" + relPath;
            var systemPath = basePath + "dist/src/es5/system/" + relPath;

            delete cache.caches.transpile[file.history[0]];

            del([es6Path, commonPath, systemPath], function(){
              gulp.start('bundle');
            });
          } else {
            gulp.start('bundle');
          }
        }
      );

      watch('demos/**/*', function() {
        gulp.start('demos');
      });

      watch('ionic/components/*/test/**/*', function(file) {
        if (file.event === "unlink") {
          var paths = file.history[0].split("ionic/components/");
          var basePath = paths[0],
              relPath = paths[1].split("/test").join("").replace(".ts", ".js");

          var distPath = basePath + "dist/e2e/" + relPath;

          delete cache.caches.e2e[file.history[0]];

          del([distPath], function(){
            gulp.start('e2e');
          });
        } else {
          gulp.start('e2e');
        }
      });

      watch('ionic/**/*.scss', function() {
        gulp.start('sass');
      });

      done();
    }
  );
});

gulp.task('serve', function() {
  var connect = require('gulp-connect');
  connect.server({
    root: 'dist',
    port: flags.port,
    livereload: false
  });
});

gulp.task('clean', function(done) {
  del(['dist/**', '!dist', '!dist/ionic-site', '!dist/ionic-site/**/*'], done);
});

function transpile(moduleType) {
  var stream = gulp.src([
      'ionic/**/*.ts',
      '!ionic/components/*/test/**/*',
      '!ionic/util/test/*'
    ])
   .pipe(cache('transpile', { optimizeMemory: true }))
   .pipe(tsc(tscOptions, null, tscReporter))
   .on('error', function(error) {
     stream.emit('end');
   })
   .pipe(gulp.dest('dist/src/es6/ionic'))
   .pipe(babel(getBabelOptions('ionic', moduleType)))
   .on('error', function (err) {
     console.log("ERROR: " + err.message);
     this.emit('end');
   })
   .pipe(gulp.dest('dist/src/es5/' + moduleType + '/ionic'))

  return stream;
}

gulp.task('transpile.system', function() { return transpile("system"); });
gulp.task('transpile.common', function() {
  // necessary for publish task, remove if we ever do incremental builds with cjs
  cache.caches && delete cache.caches.transpile;
  return transpile("common");
});
gulp.task('transpile', ['transpile.system']);

gulp.task('bundle.ionic', ['transpile'], function() {
  var insert = require('gulp-insert');
  var concat = require('gulp-concat');

  var prepend = [];

  // force the web animations api polyfill to kick in
  if (flags.animations == 'polyfill') {
    prepend.push('window.Element.prototype.animate=undefined;');
  }

  return gulp.src([
      'dist/src/es5/system/ionic/**/*.js'
    ])
    .pipe(concat('ionic.js'))
    .pipe(insert.prepend(prepend.join('\n')))
    .pipe(gulp.dest('dist/js/'));
    //TODO minify + sourcemaps
});

gulp.task('bundle', ['bundle.ionic'], function() {
  var concat = require('gulp-concat');

  return gulp.src(buildConfig.scripts)
    .pipe(concat('ionic.bundle.js'))
    .pipe(gulp.dest('dist/js'));
})

gulp.task('tests', function() {
  return gulp.src('ionic/**/test/**/*.spec.ts')
    .pipe(tsc(tscOptions, null, tscReporter))
    .pipe(babel(getBabelOptions('dist/tests')))
    .pipe(rename(function(file) {
      var regex = new RegExp(path.sep + 'test(' + path.sep + '|$)');
      file.dirname = file.dirname.replace(regex, path.sep);
    }))
    .pipe(gulp.dest('dist/tests'))
})

gulp.task('e2e', function() {
  var gulpif = require('gulp-if');
  var lazypipe = require('lazypipe');
  var _ = require('lodash');
  var fs = require('fs');
  var VinylFile = require('vinyl');

  var buildTest = lazypipe()
             //.pipe(traceur, traceurOptions)
             .pipe(tsc, tscOptions, null, tscReporter)
             .pipe(babel, getBabelOptions('e2e'))

  var buildE2ETest = lazypipe()
             //.pipe(traceur, traceurOptions)
             .pipe(tsc, tscOptions, null, tscReporter)
             .pipe(babel)

  var indexTemplate = _.template(
   fs.readFileSync('scripts/e2e/e2e.template.html')
  )({
   buildConfig: buildConfig

  })
  var testTemplate = _.template( fs.readFileSync('scripts/e2e/e2e.template.js') )

  var platforms = [
    'android',
    'ios',
  ];

  // Get each test folder with gulp.src
  return gulp.src(['ionic/components/*/test/*/**/*', '!ionic/components/*/test/*/**/*.spec.ts'])
    .pipe(cache('e2e', { optimizeMemory: true }))
    .pipe(gulpif(/e2e.ts$/, buildE2ETest()))
    .pipe(gulpif(/.ts$/, buildTest()))
    .on('error', function (err) {
      console.log("ERROR: " + err.message);
      this.emit('end');
    })
    .pipe(gulpif(/index.js$/, createIndexHTML())) //TSC changes .ts to .js
    .pipe(rename(function(file) {
      file.dirname = file.dirname.replace(path.sep + 'test' + path.sep, path.sep)
    }))
    .pipe(gulpif(/e2e.js$/, createPlatformTests()))
    .pipe(gulp.dest('dist/e2e/'))

  function createIndexHTML() {
    return through2.obj(function(file, enc, next) {
      this.push(new VinylFile({
        base: file.base,
        contents: new Buffer(indexTemplate),
        path: path.join(path.dirname(file.path), 'index.html'),
      }));
      next(null, file);
    });
  }

  function createPlatformTests(file) {
    return through2.obj(function(file, enc, next) {
      var self = this
      var relativePath = path.dirname(file.path.replace(/^.*?ionic(\/|\\)components(\/|\\)/, ''))
      var contents = file.contents.toString()
      platforms.forEach(function(platform) {
        var platformContents = testTemplate({
          contents: contents,
          buildConfig: buildConfig,
          relativePath: relativePath,
          platform: platform
        })
        self.push(new VinylFile({
          base: file.base,
          contents: new Buffer(platformContents),
          path: file.path.replace(/e2e.js$/, platform + '.e2e.js')
        }))
      })
      next()
    })
  }
});

gulp.task('sass', function() {
  var sass = require('gulp-sass');
  var autoprefixer = require('gulp-autoprefixer');
  return gulp.src('ionic/ionic.scss')
    .pipe(sass()
      .on('error', sass.logError)
    )
    .pipe(autoprefixer(buildConfig.autoprefixer))
    .pipe(gulp.dest('dist/css/'));
});

gulp.task('fonts', function() {
  return gulp.src(['ionic/fonts/**/*.ttf', 'ionic/fonts/**/*.woff'])
    .pipe(gulp.dest('dist/fonts'));
});

require('./scripts/snapshot/snapshot.task')(gulp, argv, buildConfig);

gulp.task('karma', ['tests'], function() {
  var karma = require('karma').server;
  return karma.start({ configFile: __dirname + '/scripts/karma/karma.conf.js' })
});

gulp.task('karma-watch', function() {
  var karma = require('karma').server;
  return karma.start({ configFile: __dirname + '/scripts/karma/karma-watch.conf.js' })
});

gulp.task('copy.ts', function() {
  return gulp.src([
      'ionic/**/*.ts',
      '!ionic/components/*/test/**/*',
      '!ionic/util/test/*'
    ])
    .pipe(gulp.dest('dist/src/typescript'));
})

gulp.task('copy.scss', function() {
  return gulp.src([
      'ionic/**/*.scss',
      '!ionic/components/*/test/**/*',
      '!ionic/util/test/*'
    ])
    .pipe(gulp.dest('dist/src/scss'));
})

gulp.task('copy.web-animations', function() {
  return gulp.src([
      'scripts/resources/web-animations-js/web-animations.min.js'
    ])
    .pipe(gulp.dest('dist/js'));
})

gulp.task('src', function(done){
  runSequence(
    'clean',
    ['bundle', 'sass', 'fonts', 'copy.ts', 'copy.scss', 'copy.web-animations'],
    'transpile.common',
    done
  );
})

require('./scripts/docs/gulp-tasks')(gulp, flags)

gulp.task('demos', function(){
  var gulpif = require('gulp-if');
  var lazypipe = require('lazypipe');
  var _ = require('lodash');
  var fs = require('fs');
  var VinylFile = require('vinyl');

  var buildTest = lazypipe()
    .pipe(tsc, tscOptions, null, tscReporter)
    .pipe(babel, getBabelOptions('demos'))

  var indexTemplate = _.template(fs.readFileSync('scripts/demos/index.template.html'))();

  return gulp.src(['demos/**/*'])
    .pipe(cache('demos', { optimizeMemory: true }))
    .pipe(gulpif(/.ts$/, buildTest()))
    .pipe(gulpif(/index.js$/, createIndexHTML())) //TSC changes .ts to .js
    .pipe(gulp.dest('dist/demos'))

  function createIndexHTML() {
    return through2.obj(function(file, enc, next) {
      this.push(new VinylFile({
        base: file.base,
        contents: new Buffer(indexTemplate),
        path: path.join(path.dirname(file.path), 'index.html'),
      }));
      next(null, file);
    });
  }
})

gulp.task('publish', function(done) {
  var version = flags.version;
  var ngVersion = flags.ngVersion;
  if (!version || !ngVersion) {
    console.error("\nERR: You need to provide a version for Ionic as well as " +
                  "the version of Angular it depends on.\n\n" +
                  "gulp publish -v {version} -a {ngVersion}\n");
    return
  }
  if (version.indexOf("alpha") + version.indexOf("-") > -2 ||
      ngVersion.indexOf("alpha") + ngVersion.indexOf("-") > -2)
  {
    console.error("\n ERR: Just provide version number. Instead of 2.0.0-alpha.10, just enter 10\n");
    return
  }

  var exec = require('child_process').exec;
  var _ = require('lodash');
  var fs = require('fs');

  runSequence(
    'clean',
    ['bundle', 'sass', 'fonts', 'copy.ts', 'copy.scss', 'copy.web-animations'],
    'transpile.common',
    function() {
      var packageJSONTemplate = _.template(fs.readFileSync('scripts/npm/package.json'));
      packageJSONContents = packageJSONTemplate({ 'version': version, 'ngVersion': ngVersion });
      fs.writeFileSync("dist/package.json", packageJSONContents);

      // publish to npm
      exec('cd dist && npm publish', function (err, stdout, stderr) {
        console.log(stdout);
        console.error(stderr);
        done();
      });
    }
  )
})
<|endoftext|>


<commit_before>'use strict';

// Include Gulp & tools we'll use
var gulp = require('gulp');
var $ = require('gulp-load-plugins')();
var del = require('del');
var runSequence = require('run-sequence');
var browserSync = require('browser-sync');
var reload = browserSync.reload;
var merge = require('merge-stream');
var path = require('path');
var fs = require('fs');
var glob = require('glob-all');
var historyApiFallback = require('connect-history-api-fallback');
var packageJson = require('./package.json');
var crypto = require('crypto');
var tsc = require('gulp-typescript');
var tsProject = tsc.createProject('tsconfig.json');
var tslint = require('gulp-tslint');
var sourcemaps = require('gulp-sourcemaps');
// var ghPages = require('gulp-gh-pages');
var _ = require('lodash');
var nodemon = require('gulp-nodemon');
var Karma = require('karma').Server;

var AUTOPREFIXER_BROWSERS = [
  'ie >= 10',
  'ie_mob >= 10',
  'ff >= 30',
  'chrome >= 34',
  'safari >= 7',
  'opera >= 23',
  'ios >= 7',
  'android >= 4.4',
  'bb >= 10'
];

var DIST = 'dist';
var tsSrc = [
  'app/components/**/*.ts',
  'app/services/**/*.ts',
  '!app/**/*.d.ts'
];

var dist = function(subpath) {
  return !subpath ? DIST : path.join(DIST, subpath);
};

var styleTask = function(stylesPath, srcs) {
  return gulp.src(srcs.map(function(src) {
      return path.join('app', stylesPath, src);
    }))
    .pipe($.changed(stylesPath, {extension: '.css'}))
    .pipe($.autoprefixer(AUTOPREFIXER_BROWSERS))
    .pipe(gulp.dest('.tmp/' + stylesPath))
    .pipe($.minifyCss())
    .pipe(gulp.dest(dist(stylesPath)))
    .pipe($.size({title: stylesPath}));
};

var imageOptimizeTask = function(src, dest) {
  return gulp.src(src)
    .pipe($.imagemin({
      progressive: true,
      interlaced: true
    }))
    .pipe(gulp.dest(dest))
    .pipe($.size({title: 'images'}));
};

var optimizeHtmlTask = function(src, dest) {
  var assets = $.useref.assets({
    searchPath: ['.tmp', 'app', dist()]
  });

  return gulp.src(src)
    // Replace path for vulcanized assets
    .pipe($.if('*.html', $.replace('elements/elements.html', 'elements/elements.vulcanized.html')))
    .pipe(assets)
    // Concatenate and minify JavaScript
    .pipe($.if('*.js', $.uglify({
      preserveComments: 'some'
    })))
    // Concatenate and minify styles
    // In case you are still using useref build blocks
    .pipe($.if('*.css', $.minifyCss()))
    .pipe(assets.restore())
    .pipe($.useref())
    // Minify any HTML
    .pipe($.if('*.html', $.minifyHtml({
      quotes: true,
      empty: true,
      spare: true
    })))
    // Output files
    .pipe(gulp.dest(dest))
    .pipe($.size({
      title: 'html'
    }));
};

var compileTypeScriptTask = function(src) {
  var tsResult = gulp.src(_.concat(['typings/tsd.d.ts'], src), {base: './'})
    .pipe(sourcemaps.init())
    .pipe(tsc(tsProject));

  return merge([
    tsResult.dts.pipe(gulp.dest('.')),
    tsResult.js.pipe(sourcemaps.write()).pipe(gulp.dest('.'))
  ]);
};

// Compile and automatically prefix stylesheets
gulp.task('styles', function() {
  return styleTask('styles', ['**/*.css']);
});

gulp.task('elements', function() {
  return styleTask('elements', ['**/*.css']);
});

// Lint JavaScript
gulp.task('lint', function() {
  return gulp.src([
      'app/{scripts,elements}/**/*.js',
      //'app/**/*.html',
      'gulpfile.js'
    ])
    .pipe(reload({
      stream: true,
      once: true
    }))

  // JSCS has not yet a extract option
  .pipe($.if('*.html', $.htmlExtract()))
  .pipe($.jshint())
  .pipe($.jscs())
  .pipe($.jscsStylish.combineWithHintResults())
  .pipe($.jshint.reporter('jshint-stylish'))
  .pipe($.if(!browserSync.active, $.jshint.reporter('fail')));
});

// Lint Typescript
gulp.task('ts-lint', function() {
  return gulp.src(tsSrc)
    .pipe(tslint()).pipe(tslint.report('prose'));
});

/**
 * Compile TypeScript and include references to library and app .d.ts files.
 */
gulp.task('compile-ts', function() {
  return compileTypeScriptTask(tsSrc);
});

/**
 * Remove all generated JavaScript files from TypeScript compilation.
 */
//gulp.task('clean-ts', function (cb) {
//  var typeScriptGenFiles = [
//    'app/components/**/*.js',    // path to all JS files auto gen'd by editor
//    'app/components/**/*.js.map', // path to all sourcemap files auto gen'd by editor
//  ];
//
//  // delete the files
//  del(typeScriptGenFiles, cb);
//});

// Optimize images
gulp.task('images', function() {
  return imageOptimizeTask('app/images/**/*', dist('images'));
});

// Copy all files at the root level (app)
gulp.task('copy', function() {
  var app = gulp.src([
    'app/*',
    '!app/test',
    '!app/cache-config.json'
  ], {
    dot: true
  }).pipe(gulp.dest(dist()));

  var bower = gulp.src([
    'bower_components/**/*'
  ]).pipe(gulp.dest(dist('bower_components')));

  var elements = gulp.src(['app/elements/**/*.html',
      'app/elements/**/*.css',
      'app/elements/**/*.js'
    ])
    .pipe(gulp.dest(dist('elements')));

  var swBootstrap = gulp.src(['bower_components/platinum-sw/bootstrap/*.js'])
    .pipe(gulp.dest(dist('elements/bootstrap')));

  var swToolbox = gulp.src(['bower_components/sw-toolbox/*.js'])
    .pipe(gulp.dest(dist('sw-toolbox')));

  var vulcanized = gulp.src(['app/elements/elements.html'])
    .pipe($.rename('elements.vulcanized.html'))
    .pipe(gulp.dest(dist('elements')));

  return merge(app, bower, elements, vulcanized, swBootstrap, swToolbox)
    .pipe($.size({
      title: 'copy'
    }));
});

// Copy web fonts to dist
gulp.task('fonts', function() {
  return gulp.src(['app/fonts/**'])
    .pipe(gulp.dest(dist('fonts')))
    .pipe($.size({
      title: 'fonts'
    }));
});

// Scan your HTML for assets & optimize them
gulp.task('html', function() {
  return optimizeHtmlTask(
    ['app/**/*.html', '!app/{elements,test}/**/*.html'],
    dist());
});

// Vulcanize granular configuration
gulp.task('vulcanize', function() {
  var DEST_DIR = dist('elements');
  return gulp.src(dist('elements/elements.vulcanized.html'))
    .pipe($.vulcanize({
      stripComments: true,
      inlineCss: true,
      inlineScripts: true
    }))
    .pipe(gulp.dest(DEST_DIR))
    .pipe($.size({title: 'vulcanize'}));
});

// Generate config data for the <sw-precache-cache> element.
// This include a list of files that should be precached, as well as a (hopefully unique) cache
// id that ensure that multiple PSK projects don't share the same Cache Storage.
// This task does not run by default, but if you are interested in using service worker caching
// in your project, please enable it within the 'default' task.
// See https://github.com/PolymerElements/polymer-starter-kit#enable-service-worker-support
// for more context.
gulp.task('cache-config', function(callback) {
  var dir = dist();
  var config = {
    cacheId: packageJson.name || path.basename(__dirname),
    disabled: false
  };

  glob([
    'index.html',
    './',
    'bower_components/webcomponentsjs/webcomponents-lite.min.js',
    '{elements,scripts,styles}/**/*.*'],
    {cwd: dir}, function(error, files) {
    if (error) {
      callback(error);
    } else {
      config.precache = files;

      var md5 = crypto.createHash('md5');
      md5.update(JSON.stringify(config.precache));
      config.precacheFingerprint = md5.digest('hex');

      var configPath = path.join(dir, 'cache-config.json');
      fs.writeFile(configPath, JSON.stringify(config), callback);
    }
  });
});

// Clean output directory
gulp.task('clean', function() {
  return del(['.tmp', dist()]);
});

// Watch files for changes & reload
gulp.task(
  'serve', ['ts-lint', 'lint', 'styles', 'elements', 'images', 'compile-ts', 'gen-config'],
  function(cb) {
  browserSync({
    port: 5000,
    notify: false,
    logPrefix: 'IDM',
    snippetOptions: {
      rule: {
        match: '',
        fn: function(snippet) {
          return snippet;
        }
      }
    },
    // Run as an https by uncommenting 'https: true'
    // Note: this uses an unsigned certificate which on first access
    //       will present a certificate warning in the browser.
    // https: true,
    server: {
      baseDir: ['.tmp', 'app'],
      middleware: [historyApiFallback()],
      routes: {
        '/bower_components': 'bower_components',
        '/node_modules': 'node_modules'
      }
    }
  }).emitter.on('service:running', function() {
    // use running event to notify browser ready/task completed
    cb();
  });

  gulp.watch(['app/**/*.html'], reload);
  gulp.watch(['app/styles/**/*.css'], ['styles', reload]);
  gulp.watch(['app/elements/**/*.css'], ['elements', reload]);
  gulp.watch(['app/{scripts,elements}/**/*.js', 'gulpfile.js'], ['lint']);
  gulp.watch(['app/images/**/*'], reload);
  gulp.watch(tsSrc, function(e) {
    return compileTypeScriptTask(e.path);
  });
  //  .on('change', function(event) { // for debug
  //  console.log('File ' + event.path + ' was ' + event.type + ', running tasks...');
  //});
});

gulp.task('mockapi', function() {
  nodemon({
    script: 'app/test/server.js',
    ext: 'js json',
    watch: 'app/test/'
  }).on('restart', function() {
    console.log('Mock API server restarted!');
  });
});

// start dev servers: frontend and mock backend servers, and run TDD for tests
gulp.task('dev', function(cb) {
  if (!process.env.BACKEND_URL) {
    gulp.start.apply(gulp, ['mockapi']);
  }
  runSequence('serve', 'tdd', cb);
});

// Build and serve the output from the dist build
gulp.task('serve:dist', ['default'], function() {
  browserSync({
    port: 5001,
    notify: false,
    logPrefix: 'IDM',
    snippetOptions: {
      rule: {
        match: '',
        fn: function(snippet) {
          return snippet;
        }
      }
    },
    // Run as an https by uncommenting 'https: true'
    // Note: this uses an unsigned certificate which on first access
    //       will present a certificate warning in the browser.
    // https: true,
    server: dist(),
    middleware: [historyApiFallback()]
  });
});

// Build production files, the default task
gulp.task('default', ['clean'], function(cb) {
  // Uncomment 'cache-config' if you are going to use service workers.
  runSequence(
    ['copy', 'styles'],
    'elements',
    ['ts-lint', 'lint', 'images', 'fonts', 'html'],
    'vulcanize', // 'cache-config',
    cb);
});

// Build then deploy to GitHub pages gh-pages branch
gulp.task('build-deploy-gh-pages', function(cb) {
  runSequence(
    'default',
    'deploy-gh-pages',
    cb);
});

// Deploy to GitHub pages gh-pages branch
gulp.task('deploy-gh-pages', function() {
  return gulp.src(dist('**/*'))
    // Check if running task from Travis Cl, if so run using GH_TOKEN
    // otherwise run using ghPages defaults.
    .pipe($.if(process.env.TRAVIS === 'true', $.ghPages({
      remoteUrl: 'https://$GH_TOKEN@github.com/ubc/idmap-front.git',
      silent: true,
      branch: 'gh-pages'
    }), $.ghPages()));
});

// generate a config file for frontend, the value can be from env variables or old config file
gulp.task('gen-config', function(cb) {
  var config = {};
  var newConfig = {};
  try {
    config = require('./app/config.js');
  } catch (err) {}
  newConfig.BACKEND_URL = process.env.BACKEND_URL || config.BACKEND_URL || 'http://localhost:8000';
  if (!_.isEqual(config, newConfig)) {
    fs.writeFileSync('app/config.js',
      'module.exports = ' + JSON.stringify(newConfig, null, 4) + ';', 'utf8');
  }
  cb();
});

// Load tasks for web-component-tester
// Adds tasks for `gulp test:local` and `gulp test:remote`
//require('web-component-tester').gulp.init(gulp);
function getKarmaOpts(singleRun) {
  var karmaOpts = {
    configFile: __dirname + '/karma.conf.js',
    singleRun: singleRun
  };

  var browsers = process.env.BROWSERS;
  if (browsers) {
    karmaOpts.browsers = _.split(browsers, ',');
  }

  return karmaOpts;
}
gulp.task('test', ['compile-ts', 'gen-config'], function(cb) {
  new Karma(getKarmaOpts(true), cb).start();
});

gulp.task('tdd', ['compile-ts', 'gen-config'], function() {
  new Karma(getKarmaOpts(false)).start();
});

// Load custom tasks from the `tasks` directory
try {
  require('require-dir')('tasks');
} catch (err) {}
<commit_msg>Changed mock back-end to run on 8080 as expected<commit_after>'use strict';

// Include Gulp & tools we'll use
var gulp = require('gulp');
var $ = require('gulp-load-plugins')();
var del = require('del');
var runSequence = require('run-sequence');
var browserSync = require('browser-sync');
var reload = browserSync.reload;
var merge = require('merge-stream');
var path = require('path');
var fs = require('fs');
var glob = require('glob-all');
var historyApiFallback = require('connect-history-api-fallback');
var packageJson = require('./package.json');
var crypto = require('crypto');
var tsc = require('gulp-typescript');
var tsProject = tsc.createProject('tsconfig.json');
var tslint = require('gulp-tslint');
var sourcemaps = require('gulp-sourcemaps');
// var ghPages = require('gulp-gh-pages');
var _ = require('lodash');
var nodemon = require('gulp-nodemon');
var Karma = require('karma').Server;

var AUTOPREFIXER_BROWSERS = [
  'ie >= 10',
  'ie_mob >= 10',
  'ff >= 30',
  'chrome >= 34',
  'safari >= 7',
  'opera >= 23',
  'ios >= 7',
  'android >= 4.4',
  'bb >= 10'
];

var DIST = 'dist';
var tsSrc = [
  'app/components/**/*.ts',
  'app/services/**/*.ts',
  '!app/**/*.d.ts'
];

var dist = function(subpath) {
  return !subpath ? DIST : path.join(DIST, subpath);
};

var styleTask = function(stylesPath, srcs) {
  return gulp.src(srcs.map(function(src) {
      return path.join('app', stylesPath, src);
    }))
    .pipe($.changed(stylesPath, {extension: '.css'}))
    .pipe($.autoprefixer(AUTOPREFIXER_BROWSERS))
    .pipe(gulp.dest('.tmp/' + stylesPath))
    .pipe($.minifyCss())
    .pipe(gulp.dest(dist(stylesPath)))
    .pipe($.size({title: stylesPath}));
};

var imageOptimizeTask = function(src, dest) {
  return gulp.src(src)
    .pipe($.imagemin({
      progressive: true,
      interlaced: true
    }))
    .pipe(gulp.dest(dest))
    .pipe($.size({title: 'images'}));
};

var optimizeHtmlTask = function(src, dest) {
  var assets = $.useref.assets({
    searchPath: ['.tmp', 'app', dist()]
  });

  return gulp.src(src)
    // Replace path for vulcanized assets
    .pipe($.if('*.html', $.replace('elements/elements.html', 'elements/elements.vulcanized.html')))
    .pipe(assets)
    // Concatenate and minify JavaScript
    .pipe($.if('*.js', $.uglify({
      preserveComments: 'some'
    })))
    // Concatenate and minify styles
    // In case you are still using useref build blocks
    .pipe($.if('*.css', $.minifyCss()))
    .pipe(assets.restore())
    .pipe($.useref())
    // Minify any HTML
    .pipe($.if('*.html', $.minifyHtml({
      quotes: true,
      empty: true,
      spare: true
    })))
    // Output files
    .pipe(gulp.dest(dest))
    .pipe($.size({
      title: 'html'
    }));
};

var compileTypeScriptTask = function(src) {
  var tsResult = gulp.src(_.concat(['typings/tsd.d.ts'], src), {base: './'})
    .pipe(sourcemaps.init())
    .pipe(tsc(tsProject));

  return merge([
    tsResult.dts.pipe(gulp.dest('.')),
    tsResult.js.pipe(sourcemaps.write()).pipe(gulp.dest('.'))
  ]);
};

// Compile and automatically prefix stylesheets
gulp.task('styles', function() {
  return styleTask('styles', ['**/*.css']);
});

gulp.task('elements', function() {
  return styleTask('elements', ['**/*.css']);
});

// Lint JavaScript
gulp.task('lint', function() {
  return gulp.src([
      'app/{scripts,elements}/**/*.js',
      //'app/**/*.html',
      'gulpfile.js'
    ])
    .pipe(reload({
      stream: true,
      once: true
    }))

  // JSCS has not yet a extract option
  .pipe($.if('*.html', $.htmlExtract()))
  .pipe($.jshint())
  .pipe($.jscs())
  .pipe($.jscsStylish.combineWithHintResults())
  .pipe($.jshint.reporter('jshint-stylish'))
  .pipe($.if(!browserSync.active, $.jshint.reporter('fail')));
});

// Lint Typescript
gulp.task('ts-lint', function() {
  return gulp.src(tsSrc)
    .pipe(tslint()).pipe(tslint.report('prose'));
});

/**
 * Compile TypeScript and include references to library and app .d.ts files.
 */
gulp.task('compile-ts', function() {
  return compileTypeScriptTask(tsSrc);
});

/**
 * Remove all generated JavaScript files from TypeScript compilation.
 */
//gulp.task('clean-ts', function (cb) {
//  var typeScriptGenFiles = [
//    'app/components/**/*.js',    // path to all JS files auto gen'd by editor
//    'app/components/**/*.js.map', // path to all sourcemap files auto gen'd by editor
//  ];
//
//  // delete the files
//  del(typeScriptGenFiles, cb);
//});

// Optimize images
gulp.task('images', function() {
  return imageOptimizeTask('app/images/**/*', dist('images'));
});

// Copy all files at the root level (app)
gulp.task('copy', function() {
  var app = gulp.src([
    'app/*',
    '!app/test',
    '!app/cache-config.json'
  ], {
    dot: true
  }).pipe(gulp.dest(dist()));

  var bower = gulp.src([
    'bower_components/**/*'
  ]).pipe(gulp.dest(dist('bower_components')));

  var elements = gulp.src(['app/elements/**/*.html',
      'app/elements/**/*.css',
      'app/elements/**/*.js'
    ])
    .pipe(gulp.dest(dist('elements')));

  var swBootstrap = gulp.src(['bower_components/platinum-sw/bootstrap/*.js'])
    .pipe(gulp.dest(dist('elements/bootstrap')));

  var swToolbox = gulp.src(['bower_components/sw-toolbox/*.js'])
    .pipe(gulp.dest(dist('sw-toolbox')));

  var vulcanized = gulp.src(['app/elements/elements.html'])
    .pipe($.rename('elements.vulcanized.html'))
    .pipe(gulp.dest(dist('elements')));

  return merge(app, bower, elements, vulcanized, swBootstrap, swToolbox)
    .pipe($.size({
      title: 'copy'
    }));
});

// Copy web fonts to dist
gulp.task('fonts', function() {
  return gulp.src(['app/fonts/**'])
    .pipe(gulp.dest(dist('fonts')))
    .pipe($.size({
      title: 'fonts'
    }));
});

// Scan your HTML for assets & optimize them
gulp.task('html', function() {
  return optimizeHtmlTask(
    ['app/**/*.html', '!app/{elements,test}/**/*.html'],
    dist());
});

// Vulcanize granular configuration
gulp.task('vulcanize', function() {
  var DEST_DIR = dist('elements');
  return gulp.src(dist('elements/elements.vulcanized.html'))
    .pipe($.vulcanize({
      stripComments: true,
      inlineCss: true,
      inlineScripts: true
    }))
    .pipe(gulp.dest(DEST_DIR))
    .pipe($.size({title: 'vulcanize'}));
});

// Generate config data for the <sw-precache-cache> element.
// This include a list of files that should be precached, as well as a (hopefully unique) cache
// id that ensure that multiple PSK projects don't share the same Cache Storage.
// This task does not run by default, but if you are interested in using service worker caching
// in your project, please enable it within the 'default' task.
// See https://github.com/PolymerElements/polymer-starter-kit#enable-service-worker-support
// for more context.
gulp.task('cache-config', function(callback) {
  var dir = dist();
  var config = {
    cacheId: packageJson.name || path.basename(__dirname),
    disabled: false
  };

  glob([
    'index.html',
    './',
    'bower_components/webcomponentsjs/webcomponents-lite.min.js',
    '{elements,scripts,styles}/**/*.*'],
    {cwd: dir}, function(error, files) {
    if (error) {
      callback(error);
    } else {
      config.precache = files;

      var md5 = crypto.createHash('md5');
      md5.update(JSON.stringify(config.precache));
      config.precacheFingerprint = md5.digest('hex');

      var configPath = path.join(dir, 'cache-config.json');
      fs.writeFile(configPath, JSON.stringify(config), callback);
    }
  });
});

// Clean output directory
gulp.task('clean', function() {
  return del(['.tmp', dist()]);
});

// Watch files for changes & reload
gulp.task(
  'serve', ['ts-lint', 'lint', 'styles', 'elements', 'images', 'compile-ts', 'gen-config'],
  function(cb) {
  browserSync({
    port: 5000,
    notify: false,
    logPrefix: 'IDM',
    snippetOptions: {
      rule: {
        match: '',
        fn: function(snippet) {
          return snippet;
        }
      }
    },
    // Run as an https by uncommenting 'https: true'
    // Note: this uses an unsigned certificate which on first access
    //       will present a certificate warning in the browser.
    // https: true,
    server: {
      baseDir: ['.tmp', 'app'],
      middleware: [historyApiFallback()],
      routes: {
        '/bower_components': 'bower_components',
        '/node_modules': 'node_modules'
      }
    }
  }).emitter.on('service:running', function() {
    // use running event to notify browser ready/task completed
    cb();
  });

  gulp.watch(['app/**/*.html'], reload);
  gulp.watch(['app/styles/**/*.css'], ['styles', reload]);
  gulp.watch(['app/elements/**/*.css'], ['elements', reload]);
  gulp.watch(['app/{scripts,elements}/**/*.js', 'gulpfile.js'], ['lint']);
  gulp.watch(['app/images/**/*'], reload);
  gulp.watch(tsSrc, function(e) {
    return compileTypeScriptTask(e.path);
  });
  //  .on('change', function(event) { // for debug
  //  console.log('File ' + event.path + ' was ' + event.type + ', running tasks...');
  //});
});

gulp.task('mockapi', function() {
  nodemon({
    script: 'app/test/server.js',
    ext: 'js json',
    watch: 'app/test/'
  }).on('restart', function() {
    console.log('Mock API server restarted!');
  });
});

// start dev servers: frontend and mock backend servers, and run TDD for tests
gulp.task('dev', function(cb) {
  if (!process.env.BACKEND_URL) {
    gulp.start.apply(gulp, ['mockapi']);
  }
  runSequence('serve', 'tdd', cb);
});

// Build and serve the output from the dist build
gulp.task('serve:dist', ['default'], function() {
  browserSync({
    port: 5001,
    notify: false,
    logPrefix: 'IDM',
    snippetOptions: {
      rule: {
        match: '',
        fn: function(snippet) {
          return snippet;
        }
      }
    },
    // Run as an https by uncommenting 'https: true'
    // Note: this uses an unsigned certificate which on first access
    //       will present a certificate warning in the browser.
    // https: true,
    server: dist(),
    middleware: [historyApiFallback()]
  });
});

// Build production files, the default task
gulp.task('default', ['clean'], function(cb) {
  // Uncomment 'cache-config' if you are going to use service workers.
  runSequence(
    ['copy', 'styles'],
    'elements',
    ['ts-lint', 'lint', 'images', 'fonts', 'html'],
    'vulcanize', // 'cache-config',
    cb);
});

// Build then deploy to GitHub pages gh-pages branch
gulp.task('build-deploy-gh-pages', function(cb) {
  runSequence(
    'default',
    'deploy-gh-pages',
    cb);
});

// Deploy to GitHub pages gh-pages branch
gulp.task('deploy-gh-pages', function() {
  return gulp.src(dist('**/*'))
    // Check if running task from Travis Cl, if so run using GH_TOKEN
    // otherwise run using ghPages defaults.
    .pipe($.if(process.env.TRAVIS === 'true', $.ghPages({
      remoteUrl: 'https://$GH_TOKEN@github.com/ubc/idmap-front.git',
      silent: true,
      branch: 'gh-pages'
    }), $.ghPages()));
});

// generate a config file for frontend, the value can be from env variables or old config file
gulp.task('gen-config', function(cb) {
  var config = {};
  var newConfig = {};
  try {
    config = require('./app/config.js');
  } catch (err) {}
  newConfig.BACKEND_URL = process.env.BACKEND_URL || config.BACKEND_URL || 'http://localhost:8080';
  if (!_.isEqual(config, newConfig)) {
    fs.writeFileSync('app/config.js',
      'module.exports = ' + JSON.stringify(newConfig, null, 4) + ';', 'utf8');
  }
  cb();
});

// Load tasks for web-component-tester
// Adds tasks for `gulp test:local` and `gulp test:remote`
//require('web-component-tester').gulp.init(gulp);
function getKarmaOpts(singleRun) {
  var karmaOpts = {
    configFile: __dirname + '/karma.conf.js',
    singleRun: singleRun
  };

  var browsers = process.env.BROWSERS;
  if (browsers) {
    karmaOpts.browsers = _.split(browsers, ',');
  }

  return karmaOpts;
}
gulp.task('test', ['compile-ts', 'gen-config'], function(cb) {
  new Karma(getKarmaOpts(true), cb).start();
});

gulp.task('tdd', ['compile-ts', 'gen-config'], function() {
  new Karma(getKarmaOpts(false)).start();
});

// Load custom tasks from the `tasks` directory
try {
  require('require-dir')('tasks');
} catch (err) {}
<|endoftext|>


<commit_before>const fs = require("fs");

const gulp = require("gulp");
const changed = require("gulp-changed");
const replace = require("gulp-replace");
const del = require("del");

const distillerCore = "src/external/chromium/components/dom-distiller/core";
const allChildren = "/**/*"

gulp.task("clean", () => {
   return;
   return del(["out"]);
});

gulp.task("extract:distillerCore", ["clean"], () => {
    return gulp.src([
        distillerCore + "/css" + allChildren,
        distillerCore + "/html" + allChildren,
        distillerCore + "/images" + allChildren,
        distillerCore + "/javascript" + allChildren
    ], {base: distillerCore})
    .pipe(changed("out/dom-distiller"))
    .pipe(gulp.dest("out/dom-distiller"));
});

gulp.task("extract:internal-src", ["clean"], () => {
    return gulp.src(["./**/*", "!./external/**/*"], {base: "./src"})
    .pipe(changed("./out/"))
    .pipe(gulp.dest("./out/"));
});

gulp.task("extract", ["extract:distillerCore", "extract:internal-src"]);

gulp.task("build:dom_distiller_viewer", ["extract"], () => {
    const spinner = fs.readFileSync("out/dom-distiller/images/dom_distiller_material_spinner.svg", "utf8");
    return gulp.src("out/dom-distiller/html/dom_distiller_viewer.html", {base: "./"})
    .pipe(changed("./"))
    .pipe(replace("$6", spinner))
    .pipe(replace("$2", "" +
`<link href="../css/distilledpage.css" rel="stylesheet" type="text/css">
<script src="../javascript/dom_distiller_viewer.js" defer></script>
<script src="../../viewer.js" defer></script>`))
    .pipe(gulp.dest("./"));
});

gulp.task("build:domdistiller", ["extract"], () => {
    const js = fs.readFileSync("src/external/dom-distiller/out/package/js/domdistiller.js", "utf8");
    return gulp.src("out/dom-distiller/javascript/domdistiller.js", {base: "./"})
    .pipe(changed("./"))
    .pipe(replace(`<include src="../../../../third_party/dom_distiller_js/dist/js/domdistiller.js"/>`, js))
    .pipe(gulp.dest("./"));
});

gulp.task("build", ["build:dom_distiller_viewer", "build:domdistiller"]);
<commit_msg>Use the dom-distiller-dist repo<commit_after>const fs = require("fs");

const gulp = require("gulp");
const changed = require("gulp-changed");
const replace = require("gulp-replace");
const del = require("del");

const distillerCore = "src/external/chromium/components/dom-distiller/core";
const allChildren = "/**/*"

gulp.task("clean", () => {
   return;
   return del(["out"]);
});

gulp.task("extract:distillerCore", ["clean"], () => {
    return gulp.src([
        distillerCore + "/css" + allChildren,
        distillerCore + "/html" + allChildren,
        distillerCore + "/images" + allChildren,
        distillerCore + "/javascript" + allChildren
    ], {base: distillerCore})
    .pipe(changed("out/dom-distiller"))
    .pipe(gulp.dest("out/dom-distiller"));
});

gulp.task("extract:internal-src", ["clean"], () => {
    return gulp.src(["./**/*", "!./external/**/*"], {base: "./src"})
    .pipe(changed("./out/"))
    .pipe(gulp.dest("./out/"));
});

gulp.task("extract", ["extract:distillerCore", "extract:internal-src"]);

gulp.task("build:dom_distiller_viewer", ["extract"], () => {
    const spinner = fs.readFileSync("out/dom-distiller/images/dom_distiller_material_spinner.svg", "utf8");
    return gulp.src("out/dom-distiller/html/dom_distiller_viewer.html", {base: "./"})
    .pipe(changed("./"))
    .pipe(replace("$6", spinner))
    .pipe(replace("$2", "" +
`<link href="../css/distilledpage.css" rel="stylesheet" type="text/css">
<script src="../javascript/dom_distiller_viewer.js" defer></script>
<script src="../../viewer.js" defer></script>`))
    .pipe(gulp.dest("./"));
});

gulp.task("build:domdistiller", ["extract"], () => {
    const js = fs.readFileSync("src/external/dom-distiller/out/package/js/domdistiller.js", "utf8");
    return gulp.src("out/dom-distiller-dist/js/domdistiller.js", {base: "./"})
    .pipe(changed("./"))
    .pipe(replace(`<include src="../../../../third_party/dom_distiller_js/dist/js/domdistiller.js"/>`, js))
    .pipe(gulp.dest("./"));
});

gulp.task("build", ["build:dom_distiller_viewer", "build:domdistiller"]);
<|endoftext|>


<commit_before>var gulp = require('gulp'),
    minifyCss = require("gulp-minify-css"),
    plumber = require("gulp-plumber"),
    sourceMaps = require("gulp-sourcemaps"),
    uglify = require("gulp-uglify"),
    browserSync = require("browser-sync");

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

gulp.task('libs', function () {
    return gulp.src([
        './bower_components/jquery/dist/jquery.min.js'
    ])
        .pipe(gulp.dest('./dist/js/libs'));
});

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

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

gulp.task('watch', function () {

});

gulp.task('default', ['build', 'watch']);
gulp.task('build', ['html', 'libs', 'js', 'css']);
<commit_msg>builds and watches files<commit_after>/*jslint node: true */
/*jshint node: true */
'use strict';

var gulp = require('gulp'),
    rename = require('gulp-rename'),
    minifyCss = require("gulp-minify-css"),
    plumber = require("gulp-plumber"),
    uglify = require("gulp-uglify"),
    browserSync = require("browser-sync").create(),
    reload = browserSync.reload;

gulp.task('html', function () {
    return gulp.src('./autocomplete.html')
        .pipe(gulp.dest('./dist'))
        .pipe(browserSync.stream());
});

gulp.task('libs', function () {
    return gulp.src([
        './bower_components/jquery/dist/jquery.min.js'
    ])
        .pipe(gulp.dest('./dist/js/libs'));
});

gulp.task('js', function () {
    return gulp.src('./autocomplete.js')
        .pipe(plumber())
        .pipe(uglify())
        .pipe(rename('autocomplete.min.js'))
        .pipe(gulp.dest('./dist/js'))
        .pipe(browserSync.stream());
});

gulp.task('css', function () {
    return gulp.src('./autocomplete.css')
        .pipe(plumber())
        .pipe(minifyCss())
        .pipe(rename('autocomplete.min.css'))
        .pipe(gulp.dest('./dist/css'))
        .pipe(browserSync.stream());
});

gulp.task('serve', function () {
    browserSync.init({
        server: {
            baseDir: "./dist",
            index: 'autocomplete.html'
        }
    });

    gulp.watch('autocomplete.html', ['html']).on('change', reload);
    gulp.watch('autocomplete.js', ['js']).on('change', reload);
    gulp.watch('autocomplete.css', ['css']).on('change', reload);
});

gulp.task('default', ['build', 'serve']);
gulp.task('build', ['html', 'libs', 'js', 'css']);
<|endoftext|>


<commit_before>"use strict";
/**
 * Webpack frontend test configuration.
 */
var path = require("path");
var prodCfg = require("./webpack.config");

var archDevRequire = require("builder-victory-component-dev/require");
var _ = archDevRequire("lodash");

// Replace with `__dirname` if using in project root.
var ROOT = process.cwd();

module.exports = {
  cache: true,
  context: path.join(ROOT, "test/client"),
  entry: "./main",
  output: {
    filename: "main.js",
    publicPath: "/assets/"
  },
  resolve: _.merge({}, prodCfg.resolve, {
    // enzyme webpack issue https://github.com/airbnb/enzyme/issues/47
    // Necessary for `cheerio` to load
    extensions: prodCfg.resolve.extensions.concat([".json"]),
    alias: {
      // enzyme webpack issue https://github.com/airbnb/enzyme/issues/47
      sinon: "node_modules/sinon/pkg/sinon.js",
      // Allow root import of `src/FOO` from ROOT/src.
      src: path.join(ROOT, "src")
    }
  }),
  // enzyme webpack issue https://github.com/airbnb/enzyme/issues/47
  // Please note that externals may have to change for versions of React
  // other than 0.14.x
  externals: {
    "react/lib/ExecutionEnvironment": true,
    "react/lib/ReactContext": true,
    "text-encoding": "window"
  },
  module: _.assign({}, prodCfg.module, {
    // enzyme webpack issue https://github.com/airbnb/enzyme/issues/47
    noParse: [
      /\/sinon\.js/
    ],
    // enzyme webpack issue https://github.com/airbnb/enzyme/issues/47
    loaders: (prodCfg.module.loaders || []).concat([
      {
        test: /\.json$/,
        loader: "json"
      }
    ])
  }),
  devtool: "source-map"
};
<commit_msg>Resolve loader using full path & module pattern per @ryan-roemer's suggestion<commit_after>"use strict";
/**
 * Webpack frontend test configuration.
 */
var path = require("path");
var prodCfg = require("./webpack.config");

var archDevRequire = require("builder-victory-component-dev/require");
var _ = archDevRequire("lodash");

// Replace with `__dirname` if using in project root.
var ROOT = process.cwd();

module.exports = {
  cache: true,
  context: path.join(ROOT, "test/client"),
  entry: "./main",
  output: {
    filename: "main.js",
    publicPath: "/assets/"
  },
  resolve: _.merge({}, prodCfg.resolve, {
    // enzyme webpack issue https://github.com/airbnb/enzyme/issues/47
    // Necessary for `cheerio` to load
    extensions: prodCfg.resolve.extensions.concat([".json"]),
    alias: {
      // enzyme webpack issue https://github.com/airbnb/enzyme/issues/47
      sinon: "node_modules/sinon/pkg/sinon.js",
      // Allow root import of `src/FOO` from ROOT/src.
      src: path.join(ROOT, "src")
    }
  }),
  // enzyme webpack issue https://github.com/airbnb/enzyme/issues/47
  // Please note that externals may have to change for versions of React
  // other than 0.14.x
  externals: {
    "react/lib/ExecutionEnvironment": true,
    "react/lib/ReactContext": true,
    "text-encoding": "window"
  },
  module: _.assign({}, prodCfg.module, {
    // enzyme webpack issue https://github.com/airbnb/enzyme/issues/47
    noParse: [
      /\/sinon\.js/
    ],
    // enzyme webpack issue https://github.com/airbnb/enzyme/issues/47
    loaders: (prodCfg.module.loaders || []).concat([
      {
        test: /\.json$/,
        loader: archDevRequire.resolve("json-loader")
      }
    ])
  }),
  devtool: "source-map"
};
<|endoftext|>


<commit_before>var fs = require("file-system"),
    glob = require("glob"),
    path = require("path-posix"),
    merge = require("merge-stream"),
    gulp = require("gulp"),
    gulpif = require("gulp-if"),
    print = require("gulp-print"),
    debug = require("gulp-debug"),
    newer = require("gulp-newer"),
    plumber = require("gulp-plumber"),
    sourcemaps = require("gulp-sourcemaps"),
    less = require("gulp-less"),
    scss = require("gulp-sass"),
    cssnano = require("gulp-cssnano"),
    typescript = require("gulp-typescript"),
    uglify = require("gulp-uglify"),
    rename = require("gulp-rename"),
    concat = require("gulp-concat"),
    header = require("gulp-header"),
    eol = require("gulp-eol");
    util = require('gulp-util');

// For compat with older versions of Node.js.
require("es6-promise").polyfill();

// To suppress memory leak warning from gulp.watch().
require("events").EventEmitter.prototype._maxListeners = 100;

/*
** GULP TASKS
*/

// Incremental build (each asset group is built only if one or more inputs are newer than the output).
gulp.task("build", function () {
    var assetGroupTasks = getAssetGroups().map(function (assetGroup) {
        var doRebuild = false;
        return createAssetGroupTask(assetGroup, doRebuild);
    });
    return merge(assetGroupTasks);
});

// Full rebuild (all assets groups are built regardless of timestamps).
gulp.task("rebuild", function () {
    var assetGroupTasks = getAssetGroups().map(function (assetGroup) {
        var doRebuild = true;
        return createAssetGroupTask(assetGroup, doRebuild);
    });
    return merge(assetGroupTasks);
});

// Continuous watch (each asset group is built whenever one of its inputs changes).
gulp.task("watch", function () {
    var pathWin32 = require("path");
    getAssetGroups().forEach(function (assetGroup) {
        var watchPaths = assetGroup.inputPaths.concat(assetGroup.watchPaths);
        var inputWatcher;
        function createWatcher() {
            inputWatcher = gulp.watch(watchPaths, function (event) {
                var isConcat = path.basename(assetGroup.outputFileName, path.extname(assetGroup.outputFileName)) !== "@";
                if (isConcat)
                    console.log("Asset file '" + event.path + "' was " + event.type + ", rebuilding asset group with output '" + assetGroup.outputPath + "'.");
                else
                    console.log("Asset file '" + event.path + "' was " + event.type + ", rebuilding asset group.");
                var doRebuild = true;
                var task = createAssetGroupTask(assetGroup, doRebuild);
            });
        }
        createWatcher();
        gulp.watch(assetGroup.manifestPath, function (event) {
            console.log("Asset manifest file '" + event.path + "' was " + event.type + ", restarting watcher.");
            inputWatcher.remove();
            inputWatcher.end();
            createWatcher();
        });
    });
});

gulp.task( 'default',  gulp.series([ 'build' ]) )

gulp.task('help', function() {
    util.log(`
  Usage: gulp [TASK]
  Tasks:
      build     Incremental build (each asset group is built only if one or more inputs are newer than the output).
      rebuild   Full rebuild (all assets groups are built regardless of timestamps).
      watch     Continuous watch (each asset group is built whenever one of its inputs changes).
    `);
  });

/*
** ASSET GROUPS
*/

function getAssetGroups() {
    var assetManifestPaths = glob.sync("./src/OrchardCore.{Modules,Themes}/*/Assets.json", {});
    var assetGroups = [];
    assetManifestPaths.forEach(function (assetManifestPath) {
        var assetManifest = require("./" + assetManifestPath);
        assetManifest.forEach(function (assetGroup) {
            resolveAssetGroupPaths(assetGroup, assetManifestPath);
            assetGroups.push(assetGroup);
        });
    });
    return assetGroups;
}

function resolveAssetGroupPaths(assetGroup, assetManifestPath) {
    assetGroup.manifestPath = assetManifestPath;
    assetGroup.basePath = path.dirname(assetManifestPath);
    assetGroup.inputPaths = assetGroup.inputs.map(function (inputPath) {
        return path.resolve(path.join(assetGroup.basePath, inputPath));
    });
    assetGroup.watchPaths = [];
    if (!!assetGroup.watch) {
        assetGroup.watchPaths = assetGroup.watch.map(function (watchPath) {
            return path.resolve(path.join(assetGroup.basePath, watchPath));
        });
    }
    assetGroup.outputPath = path.resolve(path.join(assetGroup.basePath, assetGroup.output));
    assetGroup.outputDir = path.dirname(assetGroup.outputPath);
    assetGroup.outputFileName = path.basename(assetGroup.output);
    // Uncomment to copy assets to wwwroot
    //assetGroup.webroot = path.join("./src/OrchardCore.Cms.Web/wwwroot/", path.basename(assetGroup.basePath), path.dirname(assetGroup.output));
}

function createAssetGroupTask(assetGroup, doRebuild) {
    var outputExt = path.extname(assetGroup.output).toLowerCase();
    var doConcat = path.basename(assetGroup.outputFileName, outputExt) !== "@";
    if (doConcat && !doRebuild) {
        // Force a rebuild of this asset group is the asset manifest file itself is newer than the output.
        var assetManifestStats = fs.statSync(assetGroup.manifestPath);
        var outputStats = fs.existsSync(assetGroup.outputPath) ? fs.statSync(assetGroup.outputPath) : null;
        doRebuild = !outputStats || assetManifestStats.mtime > outputStats.mtime;
    }

    if(assetGroup.copy === true){
        return buildCopyPipeline(assetGroup, doRebuild);
    }
    else{
        switch (outputExt) {
            case ".css":
                return buildCssPipeline(assetGroup, doConcat, doRebuild);
            case ".js":
                return buildJsPipeline(assetGroup, doConcat, doRebuild);
        }
    }
}

/*
** PROCESSING PIPELINES
*/

function buildCssPipeline(assetGroup, doConcat, doRebuild) {
    assetGroup.inputPaths.forEach(function (inputPath) {
        var ext = path.extname(inputPath).toLowerCase();
        if (ext !== ".scss" && ext !== ".less" && ext !== ".css")
            throw "Input file '" + inputPath + "' is not of a valid type for output file '" + assetGroup.outputPath + "'.";
    });
    var generateSourceMaps = assetGroup.hasOwnProperty("generateSourceMaps") ? assetGroup.generateSourceMaps : true;
    var containsLessOrScss = assetGroup.inputPaths.some(function (inputPath) {
        var ext = path.extname(inputPath).toLowerCase();
        return ext === ".less" || ext === ".scss";
    });
    // Source maps are useless if neither concatenating nor transforming.
    if ((!doConcat || assetGroup.inputPaths.length < 2) && !containsLessOrScss)
        generateSourceMaps = false;

    var minifiedStream = gulp.src(assetGroup.inputPaths) // Minified output, source mapping completely disabled.
        .pipe(gulpif(!doRebuild,
            gulpif(doConcat,
                newer(assetGroup.outputPath),
                newer({
                    dest: assetGroup.outputDir,
                    ext: ".css"
                }))))
        .pipe(plumber())
        .pipe(gulpif("*.less", less()))
        .pipe(gulpif("*.scss", scss({
            precision: 10,

        })))
        .pipe(gulpif(doConcat, concat(assetGroup.outputFileName)))
        .pipe(cssnano({
            autoprefixer: { browsers: ["last 2 versions"] },
            discardComments: { removeAll: true },
            discardUnused: false,
            mergeIdents: false,
            reduceIdents: false,
            zindex: false
        }))
        .pipe(rename({
            suffix: ".min"
        }))
        .pipe(eol())
        .pipe(gulp.dest(assetGroup.outputDir))
        // Uncomment to copy assets to wwwroot
        //.pipe(gulp.dest(assetGroup.webroot));
    var devStream = gulp.src(assetGroup.inputPaths) // Non-minified output, with source mapping
        .pipe(gulpif(!doRebuild,
            gulpif(doConcat,
                newer(assetGroup.outputPath),
                newer({
                    dest: assetGroup.outputDir,
                    ext: ".css"
                }))))
        .pipe(plumber())
        .pipe(gulpif(generateSourceMaps, sourcemaps.init()))
        .pipe(gulpif("*.less", less()))
        .pipe(gulpif("*.scss", scss({
            precision: 10
        })))
        .pipe(gulpif(doConcat, concat(assetGroup.outputFileName)))
        .pipe(header(
            "/*\n" +
            "** NOTE: This file is generated by Gulp and should not be edited directly!\n" +
            "** Any changes made directly to this file will be overwritten next time its asset group is processed by Gulp.\n" +
            "*/\n\n"))
        .pipe(gulpif(generateSourceMaps, sourcemaps.write()))
        .pipe(eol())
        .pipe(gulp.dest(assetGroup.outputDir))
        // Uncomment to copy assets to wwwroot
        //.pipe(gulp.dest(assetGroup.webroot));
    return merge([minifiedStream, devStream]);
}

function buildJsPipeline(assetGroup, doConcat, doRebuild) {
    assetGroup.inputPaths.forEach(function (inputPath) {
        var ext = path.extname(inputPath).toLowerCase();
        if (ext !== ".ts" && ext !== ".js")
            throw "Input file '" + inputPath + "' is not of a valid type for output file '" + assetGroup.outputPath + "'.";
    });
    var generateSourceMaps = assetGroup.hasOwnProperty("generateSourceMaps") ? assetGroup.generateSourceMaps : true;
    // Source maps are useless if neither concatenating nor transforming.
    if ((!doConcat || assetGroup.inputPaths.length < 2) && !assetGroup.inputPaths.some(function (inputPath) { return path.extname(inputPath).toLowerCase() === ".ts"; }))
        generateSourceMaps = false;

    console.log(assetGroup.inputPaths);
    return gulp.src(assetGroup.inputPaths)
        .pipe(gulpif(!doRebuild,
            gulpif(doConcat,
                newer(assetGroup.outputPath),
                newer({
                    dest: assetGroup.outputDir,
                    ext: ".js"
                }))))
        .pipe(plumber())
        .pipe(gulpif(generateSourceMaps, sourcemaps.init()))
        .pipe(gulpif("*.ts", typescript({
            declaration: false,
            noImplicitAny: true,
            noEmitOnError: true,
            lib: [
                "dom",
                "es5",
                "scripthost",
                "es2015.iterable"
            ],
            target: "es5",
        })))
        .pipe(gulpif(doConcat, concat(assetGroup.outputFileName)))
        .pipe(header(
            "/*\n" +
            "** NOTE: This file is generated by Gulp and should not be edited directly!\n" +
            "** Any changes made directly to this file will be overwritten next time its asset group is processed by Gulp.\n" +
            "*/\n\n"))
        .pipe(gulpif(generateSourceMaps, sourcemaps.write()))
        .pipe(gulp.dest(assetGroup.outputDir))
        // Uncomment to copy assets to wwwroot
        //.pipe(gulp.dest(assetGroup.webroot))
        .pipe(uglify())
        .pipe(rename({
            suffix: ".min"
        }))
        .pipe(eol())
        .pipe(gulp.dest(assetGroup.outputDir))
        // Uncomment to copy assets to wwwroot
        //.pipe(gulp.dest(assetGroup.webroot));
}

function buildCopyPipeline(assetGroup, doRebuild) {
    var stream = gulp.src(assetGroup.inputPaths);

    if(!doRebuild) {
        stream = stream.pipe(newer(assetGroup.outputDir))
    }

    var renameFile = assetGroup.outputFileName != "@";

    stream = stream
                .pipe(gulpif(renameFile, rename(assetGroup.outputFileName)))
                .pipe(gulp.dest(assetGroup.outputDir));
    // Uncomment to copy assets to wwwroot
    //.pipe(gulp.dest(assetGroup.webroot));

    return stream;
}<commit_msg>Fixing gulpfile watcher after gulp upgrade<commit_after>var fs = require("file-system"),
    glob = require("glob"),
    path = require("path-posix"),
    merge = require("merge-stream"),
    gulp = require("gulp"),
    gulpif = require("gulp-if"),
    print = require("gulp-print"),
    debug = require("gulp-debug"),
    newer = require("gulp-newer"),
    plumber = require("gulp-plumber"),
    sourcemaps = require("gulp-sourcemaps"),
    less = require("gulp-less"),
    scss = require("gulp-sass"),
    cssnano = require("gulp-cssnano"),
    typescript = require("gulp-typescript"),
    uglify = require("gulp-uglify"),
    rename = require("gulp-rename"),
    concat = require("gulp-concat"),
    header = require("gulp-header"),
    eol = require("gulp-eol");
    util = require('gulp-util');

// For compat with older versions of Node.js.
require("es6-promise").polyfill();

// To suppress memory leak warning from gulp.watch().
require("events").EventEmitter.prototype._maxListeners = 100;

/*
** GULP TASKS
*/

// Incremental build (each asset group is built only if one or more inputs are newer than the output).
gulp.task("build", function () {
    var assetGroupTasks = getAssetGroups().map(function (assetGroup) {
        var doRebuild = false;
        return createAssetGroupTask(assetGroup, doRebuild);
    });
    return merge(assetGroupTasks);
});

// Full rebuild (all assets groups are built regardless of timestamps).
gulp.task("rebuild", function () {
    var assetGroupTasks = getAssetGroups().map(function (assetGroup) {
        var doRebuild = true;
        return createAssetGroupTask(assetGroup, doRebuild);
    });
    return merge(assetGroupTasks);
});

// Continuous watch (each asset group is built whenever one of its inputs changes).
gulp.task("watch", function () {
    var pathWin32 = require("path");
    getAssetGroups().forEach(function (assetGroup) {
        var watchPaths = assetGroup.inputPaths.concat(assetGroup.watchPaths);
        var inputWatcher;
        function createWatcher() {
            inputWatcher = gulp.watch(watchPaths);
            inputWatcher.on('change', function (watchedPath) {
                var isConcat = path.basename(assetGroup.outputFileName, path.extname(assetGroup.outputFileName)) !== "@";
                if (isConcat)
                    console.log("Asset file '" + watchedPath + "' was changed, rebuilding asset group with output '" + assetGroup.outputPath + "'.");
                else
                    console.log("Asset file '" + watchedPath + "' was changed, rebuilding asset group.");
                var doRebuild = true;
                var task = createAssetGroupTask(assetGroup, doRebuild);
            });
        }

        createWatcher();

        gulp.watch(assetGroup.manifestPath).on('change', function (watchedPath) {
            console.log("Asset manifest file '" + watchedPath + "' was changed, restarting watcher.");
            inputWatcher.close();
            createWatcher();
        });
    });
});

gulp.task( 'default',  gulp.series([ 'build' ]) )

gulp.task('help', function() {
    util.log(`
  Usage: gulp [TASK]
  Tasks:
      build     Incremental build (each asset group is built only if one or more inputs are newer than the output).
      rebuild   Full rebuild (all assets groups are built regardless of timestamps).
      watch     Continuous watch (each asset group is built whenever one of its inputs changes).
    `);
  });

/*
** ASSET GROUPS
*/

function getAssetGroups() {
    var assetManifestPaths = glob.sync("./src/OrchardCore.{Modules,Themes}/*/Assets.json", {});
    var assetGroups = [];
    assetManifestPaths.forEach(function (assetManifestPath) {
        var assetManifest = require("./" + assetManifestPath);
        assetManifest.forEach(function (assetGroup) {
            resolveAssetGroupPaths(assetGroup, assetManifestPath);
            assetGroups.push(assetGroup);
        });
    });
    return assetGroups;
}

function resolveAssetGroupPaths(assetGroup, assetManifestPath) {
    assetGroup.manifestPath = assetManifestPath;
    assetGroup.basePath = path.dirname(assetManifestPath);
    assetGroup.inputPaths = assetGroup.inputs.map(function (inputPath) {
        return path.resolve(path.join(assetGroup.basePath, inputPath));
    });
    assetGroup.watchPaths = [];
    if (!!assetGroup.watch) {
        assetGroup.watchPaths = assetGroup.watch.map(function (watchPath) {
            return path.resolve(path.join(assetGroup.basePath, watchPath));
        });
    }
    assetGroup.outputPath = path.resolve(path.join(assetGroup.basePath, assetGroup.output));
    assetGroup.outputDir = path.dirname(assetGroup.outputPath);
    assetGroup.outputFileName = path.basename(assetGroup.output);
    // Uncomment to copy assets to wwwroot
    //assetGroup.webroot = path.join("./src/OrchardCore.Cms.Web/wwwroot/", path.basename(assetGroup.basePath), path.dirname(assetGroup.output));
}

function createAssetGroupTask(assetGroup, doRebuild) {
    var outputExt = path.extname(assetGroup.output).toLowerCase();
    var doConcat = path.basename(assetGroup.outputFileName, outputExt) !== "@";
    if (doConcat && !doRebuild) {
        // Force a rebuild of this asset group is the asset manifest file itself is newer than the output.
        var assetManifestStats = fs.statSync(assetGroup.manifestPath);
        var outputStats = fs.existsSync(assetGroup.outputPath) ? fs.statSync(assetGroup.outputPath) : null;
        doRebuild = !outputStats || assetManifestStats.mtime > outputStats.mtime;
    }

    if(assetGroup.copy === true){
        return buildCopyPipeline(assetGroup, doRebuild);
    }
    else{
        switch (outputExt) {
            case ".css":
                return buildCssPipeline(assetGroup, doConcat, doRebuild);
            case ".js":
                return buildJsPipeline(assetGroup, doConcat, doRebuild);
        }
    }
}

/*
** PROCESSING PIPELINES
*/

function buildCssPipeline(assetGroup, doConcat, doRebuild) {
    assetGroup.inputPaths.forEach(function (inputPath) {
        var ext = path.extname(inputPath).toLowerCase();
        if (ext !== ".scss" && ext !== ".less" && ext !== ".css")
            throw "Input file '" + inputPath + "' is not of a valid type for output file '" + assetGroup.outputPath + "'.";
    });
    var generateSourceMaps = assetGroup.hasOwnProperty("generateSourceMaps") ? assetGroup.generateSourceMaps : true;
    var containsLessOrScss = assetGroup.inputPaths.some(function (inputPath) {
        var ext = path.extname(inputPath).toLowerCase();
        return ext === ".less" || ext === ".scss";
    });
    // Source maps are useless if neither concatenating nor transforming.
    if ((!doConcat || assetGroup.inputPaths.length < 2) && !containsLessOrScss)
        generateSourceMaps = false;

    var minifiedStream = gulp.src(assetGroup.inputPaths) // Minified output, source mapping completely disabled.
        .pipe(gulpif(!doRebuild,
            gulpif(doConcat,
                newer(assetGroup.outputPath),
                newer({
                    dest: assetGroup.outputDir,
                    ext: ".css"
                }))))
        .pipe(plumber())
        .pipe(gulpif("*.less", less()))
        .pipe(gulpif("*.scss", scss({
            precision: 10,

        })))
        .pipe(gulpif(doConcat, concat(assetGroup.outputFileName)))
        .pipe(cssnano({
            autoprefixer: { browsers: ["last 2 versions"] },
            discardComments: { removeAll: true },
            discardUnused: false,
            mergeIdents: false,
            reduceIdents: false,
            zindex: false
        }))
        .pipe(rename({
            suffix: ".min"
        }))
        .pipe(eol())
        .pipe(gulp.dest(assetGroup.outputDir))
        // Uncomment to copy assets to wwwroot
        //.pipe(gulp.dest(assetGroup.webroot));
    var devStream = gulp.src(assetGroup.inputPaths) // Non-minified output, with source mapping
        .pipe(gulpif(!doRebuild,
            gulpif(doConcat,
                newer(assetGroup.outputPath),
                newer({
                    dest: assetGroup.outputDir,
                    ext: ".css"
                }))))
        .pipe(plumber())
        .pipe(gulpif(generateSourceMaps, sourcemaps.init()))
        .pipe(gulpif("*.less", less()))
        .pipe(gulpif("*.scss", scss({
            precision: 10
        })))
        .pipe(gulpif(doConcat, concat(assetGroup.outputFileName)))
        .pipe(header(
            "/*\n" +
            "** NOTE: This file is generated by Gulp and should not be edited directly!\n" +
            "** Any changes made directly to this file will be overwritten next time its asset group is processed by Gulp.\n" +
            "*/\n\n"))
        .pipe(gulpif(generateSourceMaps, sourcemaps.write()))
        .pipe(eol())
        .pipe(gulp.dest(assetGroup.outputDir))
        // Uncomment to copy assets to wwwroot
        //.pipe(gulp.dest(assetGroup.webroot));
    return merge([minifiedStream, devStream]);
}

function buildJsPipeline(assetGroup, doConcat, doRebuild) {
    assetGroup.inputPaths.forEach(function (inputPath) {
        var ext = path.extname(inputPath).toLowerCase();
        if (ext !== ".ts" && ext !== ".js")
            throw "Input file '" + inputPath + "' is not of a valid type for output file '" + assetGroup.outputPath + "'.";
    });
    var generateSourceMaps = assetGroup.hasOwnProperty("generateSourceMaps") ? assetGroup.generateSourceMaps : true;
    // Source maps are useless if neither concatenating nor transforming.
    if ((!doConcat || assetGroup.inputPaths.length < 2) && !assetGroup.inputPaths.some(function (inputPath) { return path.extname(inputPath).toLowerCase() === ".ts"; }))
        generateSourceMaps = false;

    console.log(assetGroup.inputPaths);
    return gulp.src(assetGroup.inputPaths)
        .pipe(gulpif(!doRebuild,
            gulpif(doConcat,
                newer(assetGroup.outputPath),
                newer({
                    dest: assetGroup.outputDir,
                    ext: ".js"
                }))))
        .pipe(plumber())
        .pipe(gulpif(generateSourceMaps, sourcemaps.init()))
        .pipe(gulpif("*.ts", typescript({
            declaration: false,
            noImplicitAny: true,
            noEmitOnError: true,
            lib: [
                "dom",
                "es5",
                "scripthost",
                "es2015.iterable"
            ],
            target: "es5",
        })))
        .pipe(gulpif(doConcat, concat(assetGroup.outputFileName)))
        .pipe(header(
            "/*\n" +
            "** NOTE: This file is generated by Gulp and should not be edited directly!\n" +
            "** Any changes made directly to this file will be overwritten next time its asset group is processed by Gulp.\n" +
            "*/\n\n"))
        .pipe(gulpif(generateSourceMaps, sourcemaps.write()))
        .pipe(gulp.dest(assetGroup.outputDir))
        // Uncomment to copy assets to wwwroot
        //.pipe(gulp.dest(assetGroup.webroot))
        .pipe(uglify())
        .pipe(rename({
            suffix: ".min"
        }))
        .pipe(eol())
        .pipe(gulp.dest(assetGroup.outputDir))
        // Uncomment to copy assets to wwwroot
        //.pipe(gulp.dest(assetGroup.webroot));
}

function buildCopyPipeline(assetGroup, doRebuild) {
    var stream = gulp.src(assetGroup.inputPaths);

    if(!doRebuild) {
        stream = stream.pipe(newer(assetGroup.outputDir))
    }

    var renameFile = assetGroup.outputFileName != "@";

    stream = stream
                .pipe(gulpif(renameFile, rename(assetGroup.outputFileName)))
                .pipe(gulp.dest(assetGroup.outputDir));
    // Uncomment to copy assets to wwwroot
    //.pipe(gulp.dest(assetGroup.webroot));

    return stream;
}<|endoftext|>


<commit_before>/**
 * Created by prof.BOLA on 13/03/2017.
 */

"use strict";

var gulp = require("gulp"),

    // gulp flow control
    gulpIf = require("gulp-if"),
    sync = require("gulp-sync")(gulp),

    // build tools
    del = require("del"),
    debug = require("debug"),
    sass = require("gulp-sass"),
    sourcemaps = require("gulp-sourcemaps"),
    replace = require("gulp-replace"),

    // distribution minification
    useref = require("gulp-useref"),
    uglify = require("gulp-uglify"),
    cssMin = require("gulp-clean-css"),
    htmlMin = require("gulp-htmlmin"),

    // runtime tools
    browserSync = require("browser-sync").create();

 // source code path
var srcPath = "developemnt/src";

// vendor/processed code path
var buildPath = "development/build";

// vendor specific location for use in development
var vendorBuildPath = buildPath + "/vendor";

// distribution folder
var distPath = "dist";

// location of vendor packages
var bowerPath = "bower_components";

var config = {
    // sourcecode globs and build path
    root_html : { src: srcPath + "/index.html", bld: buildPath },
    css :       { src: srcPath + "/stylesheets/**/*.css", bld: buildPath + "/stylesheets" },
    js :        { src: srcPath + "/javascripts/**/*.js" },
    html :      { src: [srcPath + "/**/*.html", "!" + srcPath + "/*.html" ]},

    // vendor css src globs
    bootstrap_sass :   {src: bowerPath + "/bootstrap-sass/assets/stylesheets/" },

    // vendor fonts src globs
    bootstrap_fonts :  {src: bowerPath + "/bootstrap-sass/assets/fonts/**/*" },

    // vendor js src globs
    jquery :           {src: bowerPath + "/jquery2/jquery.js" },
    bootstrap_js :     {src: bowerPath + "/bootstrap-sass/assets/javascripts/bootstrap.js" },
    angular :          {src: bowerPath + "/angular/angular.js" },
    angular_ui_router :{src: bowerPath + "/angular-ui-router/release/angular-ui-router.js" },

    // vendor build locations
    vendor_js :    { bld: vendorBuildPath + "/javascripts" },
    vendor_css :   { bld: vendorBuildPath + "/stylesheets" },
    vendor_fonts : { bld: vendorBuildPath + "/stylesheets/fonts" },

    // TODO: Fix the API
    paymentUrl : { dev: "http://localhost:3000",
                   prd: "http://localhost:3000" },

}

// files within hese paths will be saved as a root-level resources in this priority order
var devResourcePath = [
    cfg.vendor_js.bld,
    cfg.vendor_css.bld,
    buildPath + "/javascripts",
    buildPath + "/stylesheets",
    srcPath,
    srcPath + "/javascripts",
    srcPath + "/styleheets"
];<commit_msg>Added gulp build tasks<commit_after>/**
 * Created by prof.BOLA on 13/03/2017.
 */

"use strict";

var gulp = require("gulp"),

    // gulp flow control
    gulpIf = require("gulp-if"),
    sync = require("gulp-sync")(gulp),

    // build tools
    del = require("del"),
    debug = require("debug"),
    sass = require("gulp-sass"),
    sourcemaps = require("gulp-sourcemaps"),
    replace = require("gulp-replace"),

    // distribution minification
    useref = require("gulp-useref"),
    uglify = require("gulp-uglify"),
    cssMin = require("gulp-clean-css"),
    htmlMin = require("gulp-htmlmin"),

    // runtime tools
    browserSync = require("browser-sync").create();

 // source code path
var srcPath = "developemnt/src";

// vendor/processed code path
var buildPath = "development/build";

// vendor specific location for use in development
var vendorBuildPath = buildPath + "/vendor";

// distribution folder
var distPath = "dist";

// location of vendor packages
var bowerPath = "bower_components";

var config = {
    // sourcecode globs and build path
    root_html : { src: srcPath + "/index.html", bld: buildPath },
    css :       { src: srcPath + "/stylesheets/**/*.css", bld: buildPath + "/stylesheets" },
    js :        { src: srcPath + "/javascripts/**/*.js" },
    html :      { src: [srcPath + "/**/*.html", "!" + srcPath + "/*.html" ]},

    // vendor css src globs
    bootstrap_sass :   {src: bowerPath + "/bootstrap-sass/assets/stylesheets/" },

    // vendor fonts src globs
    bootstrap_fonts :  {src: bowerPath + "/bootstrap-sass/assets/fonts/**/*" },

    // vendor js src globs
    jquery :           {src: bowerPath + "/jquery2/jquery.js" },
    bootstrap_js :     {src: bowerPath + "/bootstrap-sass/assets/javascripts/bootstrap.js" },
    angular :          {src: bowerPath + "/angular/angular.js" },
    angular_ui_router :{src: bowerPath + "/angular-ui-router/release/angular-ui-router.js" },

    // vendor build locations
    vendor_js :    { bld: vendorBuildPath + "/javascripts" },
    vendor_css :   { bld: vendorBuildPath + "/stylesheets" },
    vendor_fonts : { bld: vendorBuildPath + "/stylesheets/fonts" },

    // TODO: Fix the API
    paymentUrl : { dev: "http://localhost:3000",
                   prd: "http://localhost:3000" },

};

// files within hese paths will be saved as a root-level resources in this priority order
var devResourcePath = [
    config.vendor_js.bld,
    config.vendor_css.bld,
    buildPath + "/javascripts",
    buildPath + "/stylesheets",
    srcPath,
    srcPath + "/javascripts",
    srcPath + "/styleheets"
];

// TODO: DRY-out tasks

// Remove all files below the build tree
gulp.task("clean:build", function () {
    return del(buildPath);
});

// remove all files below the dist area
gulp.task("clean:dist", function () {
    return del(distPath);
});

// remove all files below both the build and dist area
gulp.task("clean", ["clean:build", "clean:dist"]);

// place vendor css files in build area
gulp.task("vendor_css", function () {
    return gulp.src([
        // config.bootstrap_css.src,
        ])
        .pipe(gulp.dest(config.vendor_css.bld));
});

// place vendor js files in build area
gulp.task("vendor_js", function () {
    return gulp.src([
        config.jquery.src,
        config.bootstrap_js.src,
        config.angular.src,
        config.angular_ui_router.src
        ])
        .pipe(gulp.dest(config.vendor_js.bld));
});

// place all vendor font files in build area
gulp.task("vendor_fonts", function () {
    return gulp.src([
        config.bootstrap_fonts.src,
        ])
        .pipe(gulp.dest(config.vendor_fonts.bld));
});

// compile sass files
gulp.task("css", function () {
    return gulp.src(config.css.src).pipe(debug())
        .pipe(sourcemaps.init())
        .pipe(sass({ includePaths: [config.bootstrap_sass.src ] }))
        .pipe(sourcemaps.write("./maps"))
        .pipe(gulp.dest(config.css.bld)).pipe(debug());
});

// prepare the development area
gulp.task("build", sync.sync(["clean:build", ["vendor_css", "vendor_js", "vendor_fonts", "css"]]));<|endoftext|>


<commit_before>var gulp = require('gulp');
//var bower = require('bower');
var concat = require('gulp-concat');
//var sass = require('gulp-sass');
var minifyCss = require('gulp-minify-css');
var rename = require('gulp-rename');
//var sh = require('shelljs');
var addsrc = require('gulp-add-src');
var replace = require('gulp-replace');
var jsifyTemplates = require('gulp-jsify-html-templates');
//var cat  = require('gulp-cat');
var uglify = require('gulp-uglify');
var order = require("gulp-order");

gulp.task('color-picker', function() {
    return  gulp.src( [
      './src/modal-template-*.html',

      ])
    .pipe(jsifyTemplates())
    .pipe(replace("htmlTemplates", 'colorPickerTemplates'))
    .pipe(concat('templates.js'))

    .pipe(addsrc( './src/ionic-color-picker.js'))
    .pipe(order(['templates.js', 'src/ionic-color-picker.js']))
    .pipe(concat('ionic-color-picker.js'))
    //.pipe(gulp.dest( 'ColorPickerExample/www/lib/ionic-color-picker/' ) )
    .pipe(gulp.dest('./dist/'))
    .pipe(uglify({mangle:false}))
    .pipe(rename({ extname: '.min.js' }))
    //.pipe(gulp.dest('ColorPickerExample/www/lib/ionic-color-picker/'))
    .pipe(gulp.dest('./dist/'))

});

gulp.task('css-color-picker', function() {
    return gulp.src( './src/ionic-color-picker.css')
    //.pipe(gulp.dest( 'ColorPickerExample/www/lib/ionic-color-picker' ) )
    .pipe(gulp.dest('./dist/'))
    .pipe(minifyCss({
      keepSpecialComments: 0
    }))
    .pipe(rename({ extname: '.min.css' }))
    //.pipe( gulp.dest( 'ColorPickerExample/www/lib/ionic-color-picker' ) )
    .pipe(gulp.dest('./dist/'))

});

gulp.task('watch', function() {
  gulp.watch(['./src/*.*'], ['color-picker', 'css-color-picker']);

});

gulp.task('default', ['color-picker', 'css-color-picker']);

<commit_msg>cleaned gulpfile<commit_after>var gulp = require('gulp');
var concat = require('gulp-concat');
var minifyCss = require('gulp-minify-css');
var rename = require('gulp-rename');
var addsrc = require('gulp-add-src');
var replace = require('gulp-replace');
var jsifyTemplates = require('gulp-jsify-html-templates');
var uglify = require('gulp-uglify');
var order = require("gulp-order");

gulp.task('color-picker', function() {
    return  gulp.src( [
      './src/modal-template-*.html',

      ])
    .pipe(jsifyTemplates())
    .pipe(replace("htmlTemplates", 'colorPickerTemplates'))
    .pipe(concat('templates.js'))

    .pipe(addsrc( './src/ionic-color-picker.js'))
    .pipe(order(['templates.js', 'src/ionic-color-picker.js']))
    .pipe(concat('ionic-color-picker.js'))
    .pipe(gulp.dest('./dist/'))
    .pipe(uglify({mangle:false}))
    .pipe(rename({ extname: '.min.js' }))
    .pipe(gulp.dest('./dist/'))

});

gulp.task('css-color-picker', function() {
    return gulp.src( './src/ionic-color-picker.css')
    .pipe(gulp.dest('./dist/'))
    .pipe(minifyCss({
      keepSpecialComments: 0
    }))
    .pipe(rename({ extname: '.min.css' }))
    .pipe(gulp.dest('./dist/'))

});

gulp.task('watch', function() {
  gulp.watch(['./src/*.*'], ['color-picker', 'css-color-picker']);

});

gulp.task('default', ['color-picker', 'css-color-picker']);

<|endoftext|>


<commit_before>/* Workaround for `possible EventEmitter memory leak detected. 11 listeners added`` */
process.stdout.setMaxListeners(Infinity)

/* Dependencies */
var gulp        = require('gulp')
var jshint      = require('gulp-jshint')
var mocha       = require('gulp-mocha')
var to5         = require('gulp-6to5')
var plumber     = require('gulp-plumber')
var runSequence = require('run-sequence')
var del         = require('del')

/* Directories to watch */
var sourceDir = 'src/**/*.js'
var testDir   = 'test/scripts/**/*.js'
var distDir   = 'dist'

/* if watching, do not exit the application if a test failed */
var watching = false

gulp.task('clean', function(callback) {
  del([
    distDir+'/**'
  ], callback)
})

/* Compile ES6 to ES5 */
gulp.task('6to5', function() {
  return gulp
    .src([sourceDir])
    .pipe(plumber())
    .pipe(to5())
    .pipe(gulp.dest(distDir))
})

/* Mocha Unit Tests */
gulp.task('mocha', function(){
  var reporter = 'spec'

  if (watching) {
    reporter = 'nyan'
  }
  return gulp
    .src('test/index.js')
    .pipe(mocha({
      reporter    : reporter,
      ignoreLeaks : true,
      asyncOnly   : true,
      timeout     : 5000,
      debug       : true
    }).on('error', function(err) {
      console.log(err.toString())

      if (watching) {
        this.emit('end') // will not close the watcher
      } else {
        process.exit(1) // return an error code. useful for CI
      }
    }))
})

/* JSHint */
gulp.task('jshint', function(){
  return gulp
    .src(sourceDir)
    .pipe(jshint())
    .pipe(jshint.reporter('jshint-stylish'))
    .pipe(jshint.reporter('default'))
})

/* Execute in order */
gulp.task('compile-then-test', function(callback) {
  runSequence(
    'clean',
    '6to5',
    'jshint',
    'mocha',
    callback
  )
})

/* Watch for file changes, then perform the tests */
gulp.task('watch', function(){
  watching = true
  gulp.watch(sourceDir, ['compile-then-test']) // on every change, run tasks in order
  gulp.watch(['test/index.js', testDir], ['compile-then-test'])
})

gulp.task('test', ['compile-then-test'])

gulp.task('default', ['6to5', 'watch'])
<commit_msg>add comment for 'clean' task<commit_after>/* Workaround for `possible EventEmitter memory leak detected. 11 listeners added`` */
process.stdout.setMaxListeners(Infinity)

/* Dependencies */
var gulp        = require('gulp')
var jshint      = require('gulp-jshint')
var mocha       = require('gulp-mocha')
var to5         = require('gulp-6to5')
var plumber     = require('gulp-plumber')
var runSequence = require('run-sequence')
var del         = require('del')

/* Directories to watch */
var sourceDir = 'src/**/*.js'
var testDir   = 'test/scripts/**/*.js'
var distDir   = 'dist'

/* if watching, do not exit the application if a test failed */
var watching = false

/* remove everything inside dist/ directory */
gulp.task('clean', function(callback) {
  del([
    distDir+'/**'
  ], callback)
})

/* Compile ES6 to ES5 */
gulp.task('6to5', function() {
  return gulp
    .src([sourceDir])
    .pipe(plumber())
    .pipe(to5())
    .pipe(gulp.dest(distDir))
})

/* Mocha Unit Tests */
gulp.task('mocha', function(){
  var reporter = 'spec'

  if (watching) {
    reporter = 'nyan'
  }
  return gulp
    .src('test/index.js')
    .pipe(mocha({
      reporter    : reporter,
      ignoreLeaks : true,
      asyncOnly   : true,
      timeout     : 5000,
      debug       : true
    }).on('error', function(err) {
      console.log(err.toString())

      if (watching) {
        this.emit('end') // will not close the watcher
      } else {
        process.exit(1) // return an error code. useful for CI
      }
    }))
})

/* JSHint */
gulp.task('jshint', function(){
  return gulp
    .src(sourceDir)
    .pipe(jshint())
    .pipe(jshint.reporter('jshint-stylish'))
    .pipe(jshint.reporter('default'))
})

/* Execute in order */
gulp.task('compile-then-test', function(callback) {
  runSequence(
    'clean',
    '6to5',
    'jshint',
    'mocha',
    callback
  )
})

/* Watch for file changes, then perform the tests */
gulp.task('watch', function(){
  watching = true
  gulp.watch(sourceDir, ['compile-then-test']) // on every change, run tasks in order
  gulp.watch(['test/index.js', testDir], ['compile-then-test'])
})

gulp.task('test', ['compile-then-test'])

gulp.task('default', ['6to5', 'watch'])
<|endoftext|>