<commit_before>'use strict';

var gulp = require('gulp');
var inject = require('gulp-inject');
var less = require('gulp-less');
var del = require('del');
var runSequence = require('run-sequence');
var browserify = require('browserify');
var reactify = require('reactify'); // for browserify
var tsify = require('tsify');
var ts = require('gulp-typescript');
var source = require('vinyl-source-stream');
var buffer = require('vinyl-buffer');
var uglify = require('gulp-uglify');
var jshint = require('gulp-jshint');
var jscs = require('gulp-jscs');
var stylish = require('gulp-jscs-stylish');
var react = require('gulp-react'); // for jshint
var concat = require('gulp-concat');
var cssmin = require('gulp-minify-css');
var plumber = require('gulp-plumber');
var notify = require('gulp-notify');
var lr = require('tiny-lr')();
var nightwatch = require('gulp-nightwatch');

var config = require('./config/config.js');

// from http://rhumaric.com/2014/01/livereload-magic-gulp-style/
var app;
function startExpress() {
  app = require('./app.js');
  app.use(require('connect-livereload')());
  app.listen(config.port);
}

function stopExpress() {
  app.close();
}

function startLivereload() {
  lr.listen(35729);
}

function notifyLivereload(event) {
  // this should, but does not work, so using the solution below
  //gulp.src(event.path, {read: false}).pipe(require('gulp-livereload')(lr));

  var fileName = require('path').relative(__dirname, event.path);
  lr.changed({
    body: {
      files: [fileName]
    }
  });
}

gulp.task('clean', function(cb) {
  return del(['./frontend/build/'], cb);
});

gulp.task('img', function() {
  return gulp.src('./frontend/src/img/**/*.{jpg,gif,png}')
  .pipe(gulp.dest('./frontend/build/public/img/'));
});

gulp.task('fonts', function() {
  return gulp.src('./frontend/src/bootstrap/fonts/*')
  .pipe(gulp.dest('./frontend/build/public/fonts/'));
});

gulp.task('css:store', function() {
  return gulp.src(['./frontend/src/css/*.less', '!./frontend/src/css/admin*.less'])
      .pipe(less())
      .pipe(concat('style.css'))
      .pipe(gulp.dest('./frontend/build/public/css/'));
});

gulp.task('css:admin', function() {
  return gulp.src('./frontend/src/css/admin*.less')
      .pipe(less())
      .pipe(concat('admin.css'))
      .pipe(gulp.dest('./frontend/build/public/css/'));
});

gulp.task('css:min', function() {
  gulp.src(['./frontend/src/css/*.less', '!./frontend/src/css/admin*.less'])
      .pipe(less())
      .pipe(concat('style.css'))
      .pipe(cssmin())
      .pipe(gulp.dest('./frontend/build/public/css/'));
});

gulp.task('css', ['css:store', 'css:admin']);

gulp.task('lint', function() {
  return gulp.src(['frontend/src/**/*.{js,jsx}', '!./frontend/src/bootstrap/**/*.js']) // lint reactified JS
  .pipe(plumber())
  .pipe(jscs())
  .pipe(react())
  .pipe(jshint())
  .pipe(stylish.combineWithHintResults())
  .pipe(jshint.reporter('jshint-stylish'));
});

function js(startPath, targetFile) {
  return function() {
    return browserify(startPath)
    .add(startPath)
    .add('typings/tsd.d.ts')
    .transform(reactify)
    .plugin(tsify)
    .bundle()
    .on('error', function(err) {
      notify.onError({
        message: '<%= error.message %>'
      }).apply(this, arguments);
      this.emit('end');
    })
    .pipe(source(targetFile))
    .pipe(gulp.dest('./frontend/build/public/js/'));
  };
}

function jsMin(startPath, targetFile) {
  return function() {
    return browserify()
    .add(startPath)
    .add('typings/tsd.d.ts')
    .transform(reactify)
    .bundle()
    .pipe(source(targetFile))
    .pipe(buffer())
    .pipe(uglify())
    .pipe(gulp.dest('./frontend/build/public/js/'));
  };
}

gulp.task('js:store', ['lint'], js('./frontend/src/js/App.tsx', 'App.js'));
gulp.task('js:admin', js('./frontend/src/js-admin/AdminApp.tsx', 'adminApp.js'));

gulp.task('js', ['js:store', 'js:admin']);

gulp.task('js:store:min', jsMin('./frontend/src/js/App.jsx', 'App.js'));
gulp.task('js:admin:min', jsMin('./frontend/src/js-admin/AdminApp.jsx', 'adminApp.js'));

gulp.task('js:min', ['js:store:min', 'js:admin:min']);

gulp.task('backend', function() {
  return gulp.src(['backend/src/**/*.ts', 'typings/tsd.d.ts'])
    .pipe(ts({
      module: 'commonjs'
    }))
    .pipe(gulp.dest('backend/build/'));
});

gulp.task('app', function() {
  return gulp.src(['app.ts', 'typings/tsd.d.ts'])
    .pipe(ts({
      module: 'commonjs'
    }))
    .pipe(gulp.dest('./'));
});

gulp.task('index', function() {
  return gulp.src('./frontend/src/index.html')
      .pipe(inject(gulp.src(['./public/**/*.{css,js}', '!./public/**/admin*'], {read: false, cwd: './frontend/build/'}), {addRootSlash: false}))
      .pipe(inject(gulp.src('./config/google-analytics.js'), {name: 'analytics', transform: function(path, file) { return file.contents.toString('utf8'); }}))
      .pipe(gulp.dest('./frontend/build/'));
});

gulp.task('admin', function() {
  return gulp.src('./frontend/src/admin.html')
      .pipe(inject(gulp.src('./public/**/admin*.{css,js}', {read: false, cwd: './frontend/build/'}), {addRootSlash: false}))
      .pipe(gulp.dest('./frontend/build/'));
});

gulp.task('lint-backend', function() {
  return gulp.src('backend/**/*.js') // lint reactified JS
  .pipe(plumber())
  .pipe(jscs())
  .pipe(jshint())
  .pipe(stylish.combineWithHintResults())
  .pipe(jshint.reporter('jshint-stylish'));
});

gulp.task('ete-test', function() {
  return gulp.src('')
    .pipe(nightwatch({
      configFile: 'nightwatch.json'
    }));
});

gulp.task('test', function() {
  runSequence(
    ['build-dev'],
    ['start-dev'],
    ['ete-test'],
    stopExpress
  );
});

gulp.task('build-dev', function(cb) {
  runSequence(
    ['clean'],
    ['app', 'backend', 'css', 'js', 'img', 'fonts'],
    ['index', 'admin'],
    cb);
});

gulp.task('build', function(cb) {
  runSequence(
    ['clean'],
    ['app', 'backend', 'css:min', 'js:min', 'img', 'fonts'],
    ['index', 'admin'],
    cb);
});

gulp.task('start-dev', function() {
  startExpress();
  startLivereload();
  gulp.watch('frontend/src/css/**/*.{css,less}', ['css', 'index', 'admin']);
  gulp.watch('frontend/src/js*/**/*.{js,jsx,ts,tsx}', ['js', 'index', 'admin']);
  gulp.watch('frontend/src/img/**/*.{jpg,gif,png}', ['img']);
  gulp.watch('frontend/src/index.html', ['index']);
  gulp.watch('frontend/src/admin.html', ['admin']);
  gulp.watch('frontend/build/**/*.{html,css,js,jpg,gif,png}', notifyLivereload);
});

gulp.task('start', function() {
  startExpress();
});

gulp.task('default', function(cb) {
  runSequence(
    ['build-dev'],
    ['start-dev'],
    cb);
});
<commit_msg>fix minified build<commit_after>'use strict';

var gulp = require('gulp');
var inject = require('gulp-inject');
var less = require('gulp-less');
var del = require('del');
var runSequence = require('run-sequence');
var browserify = require('browserify');
var reactify = require('reactify'); // for browserify
var tsify = require('tsify');
var ts = require('gulp-typescript');
var source = require('vinyl-source-stream');
var buffer = require('vinyl-buffer');
var uglify = require('gulp-uglify');
var jshint = require('gulp-jshint');
var jscs = require('gulp-jscs');
var stylish = require('gulp-jscs-stylish');
var react = require('gulp-react'); // for jshint
var concat = require('gulp-concat');
var cssmin = require('gulp-minify-css');
var plumber = require('gulp-plumber');
var notify = require('gulp-notify');
var lr = require('tiny-lr')();
var nightwatch = require('gulp-nightwatch');

var config = require('./config/config.js');

// from http://rhumaric.com/2014/01/livereload-magic-gulp-style/
var app;
function startExpress() {
  app = require('./app.js');
  app.use(require('connect-livereload')());
  app.listen(config.port);
}

function stopExpress() {
  app.close();
}

function startLivereload() {
  lr.listen(35729);
}

function notifyLivereload(event) {
  // this should, but does not work, so using the solution below
  //gulp.src(event.path, {read: false}).pipe(require('gulp-livereload')(lr));

  var fileName = require('path').relative(__dirname, event.path);
  lr.changed({
    body: {
      files: [fileName]
    }
  });
}

gulp.task('clean', function(cb) {
  return del(['./frontend/build/'], cb);
});

gulp.task('img', function() {
  return gulp.src('./frontend/src/img/**/*.{jpg,gif,png}')
  .pipe(gulp.dest('./frontend/build/public/img/'));
});

gulp.task('fonts', function() {
  return gulp.src('./frontend/src/bootstrap/fonts/*')
  .pipe(gulp.dest('./frontend/build/public/fonts/'));
});

gulp.task('css:store', function() {
  return gulp.src(['./frontend/src/css/*.less', '!./frontend/src/css/admin*.less'])
      .pipe(less())
      .pipe(concat('style.css'))
      .pipe(gulp.dest('./frontend/build/public/css/'));
});

gulp.task('css:admin', function() {
  return gulp.src('./frontend/src/css/admin*.less')
      .pipe(less())
      .pipe(concat('admin.css'))
      .pipe(gulp.dest('./frontend/build/public/css/'));
});

gulp.task('css:min', function() {
  gulp.src(['./frontend/src/css/*.less', '!./frontend/src/css/admin*.less'])
      .pipe(less())
      .pipe(concat('style.css'))
      .pipe(cssmin())
      .pipe(gulp.dest('./frontend/build/public/css/'));
});

gulp.task('css', ['css:store', 'css:admin']);

gulp.task('lint', function() {
  return gulp.src(['frontend/src/**/*.{js,jsx}', '!./frontend/src/bootstrap/**/*.js']) // lint reactified JS
  .pipe(plumber())
  .pipe(jscs())
  .pipe(react())
  .pipe(jshint())
  .pipe(stylish.combineWithHintResults())
  .pipe(jshint.reporter('jshint-stylish'));
});

function js(startPath, targetFile) {
  return function() {
    return browserify(startPath)
    .add(startPath)
    .add('typings/tsd.d.ts')
    .transform(reactify)
    .plugin(tsify)
    .bundle()
    .on('error', function(err) {
      notify.onError({
        message: '<%= error.message %>'
      }).apply(this, arguments);
      this.emit('end');
    })
    .pipe(source(targetFile))
    .pipe(gulp.dest('./frontend/build/public/js/'));
  };
}

function jsMin(startPath, targetFile) {
  return function() {
    return browserify()
    .add(startPath)
    .add('typings/tsd.d.ts')
    .transform(reactify)
    .plugin(tsify)
    .bundle()
    .pipe(source(targetFile))
    .pipe(buffer())
    .pipe(uglify())
    .pipe(gulp.dest('./frontend/build/public/js/'));
  };
}

gulp.task('js:store', ['lint'], js('./frontend/src/js/App.tsx', 'App.js'));
gulp.task('js:admin', js('./frontend/src/js-admin/AdminApp.tsx', 'adminApp.js'));

gulp.task('js', ['js:store', 'js:admin']);

gulp.task('js:store:min', jsMin('./frontend/src/js/App.tsx', 'App.js'));
gulp.task('js:admin:min', jsMin('./frontend/src/js-admin/AdminApp.tsx', 'adminApp.js'));

gulp.task('js:min', ['js:store:min', 'js:admin:min']);

gulp.task('backend', function() {
  return gulp.src(['backend/src/**/*.ts', 'typings/tsd.d.ts'])
    .pipe(ts({
      module: 'commonjs'
    }))
    .pipe(gulp.dest('backend/build/'));
});

gulp.task('app', function() {
  return gulp.src(['app.ts', 'typings/tsd.d.ts'])
    .pipe(ts({
      module: 'commonjs'
    }))
    .pipe(gulp.dest('./'));
});

gulp.task('index', function() {
  return gulp.src('./frontend/src/index.html')
      .pipe(inject(gulp.src(['./public/**/*.{css,js}', '!./public/**/admin*'], {read: false, cwd: './frontend/build/'}), {addRootSlash: false}))
      .pipe(inject(gulp.src('./config/google-analytics.js'), {name: 'analytics', transform: function(path, file) { return file.contents.toString('utf8'); }}))
      .pipe(gulp.dest('./frontend/build/'));
});

gulp.task('admin', function() {
  return gulp.src('./frontend/src/admin.html')
      .pipe(inject(gulp.src('./public/**/admin*.{css,js}', {read: false, cwd: './frontend/build/'}), {addRootSlash: false}))
      .pipe(gulp.dest('./frontend/build/'));
});

gulp.task('lint-backend', function() {
  return gulp.src('backend/**/*.js') // lint reactified JS
  .pipe(plumber())
  .pipe(jscs())
  .pipe(jshint())
  .pipe(stylish.combineWithHintResults())
  .pipe(jshint.reporter('jshint-stylish'));
});

gulp.task('ete-test', function() {
  return gulp.src('')
    .pipe(nightwatch({
      configFile: 'nightwatch.json'
    }));
});

gulp.task('test', function() {
  runSequence(
    ['build-dev'],
    ['start-dev'],
    ['ete-test'],
    stopExpress
  );
});

gulp.task('build-dev', function(cb) {
  runSequence(
    ['clean'],
    ['app', 'backend', 'css', 'js', 'img', 'fonts'],
    ['index', 'admin'],
    cb);
});

gulp.task('build', function(cb) {
  runSequence(
    ['clean'],
    ['app', 'backend', 'css:min', 'js:min', 'img', 'fonts'],
    ['index', 'admin'],
    cb);
});

gulp.task('start-dev', function() {
  startExpress();
  startLivereload();
  gulp.watch('frontend/src/css/**/*.{css,less}', ['css', 'index', 'admin']);
  gulp.watch('frontend/src/js*/**/*.{js,jsx,ts,tsx}', ['js', 'index', 'admin']);
  gulp.watch('frontend/src/img/**/*.{jpg,gif,png}', ['img']);
  gulp.watch('frontend/src/index.html', ['index']);
  gulp.watch('frontend/src/admin.html', ['admin']);
  gulp.watch('frontend/build/**/*.{html,css,js,jpg,gif,png}', notifyLivereload);
});

gulp.task('start', function() {
  startExpress();
});

gulp.task('default', function(cb) {
  runSequence(
    ['build-dev'],
    ['start-dev'],
    cb);
});
<|endoftext|>


<commit_before>"use strict";

var del = require('del');
var exec = require('child_process').exec;
var gulp = require('gulp');
var os = require('os');
var tslint = require('gulp-tslint');

// Build.

gulp.task('build', ['transpile:ts']);

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

    gulp.watch([
        './index.ts',
        './src/*.ts',
        '!*/**/*.d.ts',
        '!*/**/*.ngfactory.ts',
    ], [
        'build'
    ]);
});

// Typescript --> Javascript.

gulp.task('clean:js', function() {

    return del([
        './index.d.ts',
        './index.js.map',
        './index.js',
        './index.metadata.json',
        './index.ngfactory.ts',
        './src/**/*.d.ts',
        './src/**/*.js.map',
        './src/**/*.js',
        './src/**/*.metadata.json',
        './src/**/*.ngfactory.ts',
    ]);
});

gulp.task('lint:ts', function() {
    return gulp.src([
        './index.ts',
        './src/*.ts',
        '!*/**/*.d.ts',
        '!*/**/*.ngfactory.ts'
    ])
        .pipe(tslint({
            formatter: "verbose"
        }))
        .pipe(tslint.report())
});

gulp.task('transpile:ts', ['clean:js', 'lint:ts'], function (cb) {

    var cmd = os.platform() === 'win32' ?
        'node_modules\\.bin\\ngc' : './node_modules/.bin/ngc';

    exec(cmd, function (err, stdout, stderr) {
        console.log(stdout);
        console.log(stderr);
        cb(err);
    });
});
<commit_msg>Build file update.<commit_after>"use strict";

var del = require('del');
var exec = require('child_process').exec;
var gulp = require('gulp');
var os = require('os');
var tslint = require('gulp-tslint');

// Build.

gulp.task('build', ['transpile:ts']);

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

    gulp.watch([
        './index.ts',
        './src/*.ts',
        '!*/**/*.d.ts',
        '!*/**/*.ngfactory.ts',
    ], [
        'build'
    ]);
});

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

    return del([
        './index.d.ts',
        './index.js',
        './index.metadata.json',
        './index.ngfactory.ts',
        './src/**/*.d.ts',
        './src/**/*.js',
        './src/**/*.metadata.json',
        './src/**/*.ngfactory.ts',
    ]);
});

// Typescript --> Javascript.

gulp.task('lint:ts', function() {
    return gulp.src([
        './index.ts',
        './src/*.ts',
        '!*/**/*.d.ts',
        '!*/**/*.ngfactory.ts'
    ])
        .pipe(tslint({
            formatter: "verbose"
        }))
        .pipe(tslint.report())
});

gulp.task('transpile:ts', ['clean', 'lint:ts'], function (cb) {

    var cmd = os.platform() === 'win32' ?
        'node_modules\\.bin\\ngc' : './node_modules/.bin/ngc';

    exec(cmd, function (err, stdout, stderr) {
        console.log(stdout);
        console.log(stderr);
        cb(err);
    });
});
<|endoftext|>


<commit_before>var gulp = require('gulp');
var path = require('path');
var open = require('open');
var csso = require('gulp-csso');
var express = require ('express');
var lr = require('tiny-lr');
var es = require('event-stream');
var extend = require('extend');
var replace = require('gulp-replace');
var rjs = require('gulp-requirejs');
var uglify = require('gulp-uglify');

var server = lr();
var app = express();

var APP_ROOT = __dirname + '/source';
var APP_PORT = 4000;

// Opens a browser with the application path.
gulp.task('open', ['serve'], function(){
  open('http://localhost:' + APP_PORT);
});

// Statically serves files and adds the LiveReload script.
gulp.task('serve', function () {
  app.use(require('connect-livereload')());
  app.use(express.static(APP_ROOT));
  app.listen(APP_PORT);
});

// Watches for file changes and reloads browser pages.
gulp.task('watch', function () {
  server.listen(35729, function (err) {
    if (err) {
      return console.log(err);
    }

    gulp.watch([
      'source/index.html',
      'source/assets/**/*',
      'source/js/**/*',
      '!source/js/**/*.spec.js'
    ], function (evt) {
      server.changed({
        body: {
          files: [path.relative(APP_ROOT, evt.path)]
        }
      });
    });
  });
});

// Builds the project for production.
gulp.task('build', function () {
  return es.concat(
    // Build main sources.
    gulp.src(['source/index.html'])
      .pipe(replace("require(['./js/main.js'])", "require(['./js/main.js'], function () { require(['main']); })"))
      .pipe(gulp.dest('build')),
    gulp.src(['source/js/config-require.js'])
      .pipe(uglify())
      .pipe(gulp.dest('build/js')),
    // Build assets.
    gulp.src(['source/assets/css/*'])
      .pipe(csso())
      .pipe(gulp.dest('build/assets/css')),
    gulp.src(['source/assets/fonts/*'])
      .pipe(gulp.dest('build/assets/fonts')),
    gulp.src(['source/assets/images/*'])
      .pipe(gulp.dest('build/assets/images')),
    // Build vendor files.
    gulp.src(['source/vendor/**/*'])
      .pipe(gulp.dest('build/vendor')),
    gulp.src(['build/vendor/requirejs/require.js'])
      .pipe(uglify())
      .pipe(gulp.dest('build/vendor/requirejs')),
    gulp.src(['build/vendor/requirejs-domready/domReady.js'])
      .pipe(uglify())
      .pipe(gulp.dest('build/vendor/requirejs-domready'))
  );
});

// Compiles with RequireJS' r.js.
gulp.task('compile', function () {
  var configRequire = require('./source/js/config-require.js');
  var config = {
    baseUrl: 'source/js',
    name: 'main',
    optimize: 'none',
    out: 'main.js',
    wrap: true
  };
  extend(config, configRequire);

  return rjs(config)
    .pipe(uglify())
    .pipe(gulp.dest('./build/js/'));
});

// Default developer working task.
gulp.task('work', ['watch', 'open']);

gulp.task('default', ['work']);
<commit_msg>Add stubModules option to r.js<commit_after>var gulp = require('gulp');
var path = require('path');
var open = require('open');
var csso = require('gulp-csso');
var express = require ('express');
var lr = require('tiny-lr');
var es = require('event-stream');
var extend = require('extend');
var replace = require('gulp-replace');
var rjs = require('gulp-requirejs');
var uglify = require('gulp-uglify');

var server = lr();
var app = express();

var APP_ROOT = __dirname + '/source';
var APP_PORT = 4000;

// Opens a browser with the application path.
gulp.task('open', ['serve'], function(){
  open('http://localhost:' + APP_PORT);
});

// Statically serves files and adds the LiveReload script.
gulp.task('serve', function () {
  app.use(require('connect-livereload')());
  app.use(express.static(APP_ROOT));
  app.listen(APP_PORT);
});

// Watches for file changes and reloads browser pages.
gulp.task('watch', function () {
  server.listen(35729, function (err) {
    if (err) {
      return console.log(err);
    }

    gulp.watch([
      'source/index.html',
      'source/assets/**/*',
      'source/js/**/*',
      '!source/js/**/*.spec.js'
    ], function (evt) {
      server.changed({
        body: {
          files: [path.relative(APP_ROOT, evt.path)]
        }
      });
    });
  });
});

// Builds the project for production.
gulp.task('build', function () {
  return es.concat(
    // Build main sources.
    gulp.src(['source/index.html'])
      .pipe(replace("require(['./js/main.js'])", "require(['./js/main.js'], function () { require(['main']); })"))
      .pipe(gulp.dest('build')),
    gulp.src(['source/js/config-require.js'])
      .pipe(uglify())
      .pipe(gulp.dest('build/js')),
    // Build assets.
    gulp.src(['source/assets/css/*'])
      .pipe(csso())
      .pipe(gulp.dest('build/assets/css')),
    gulp.src(['source/assets/fonts/*'])
      .pipe(gulp.dest('build/assets/fonts')),
    gulp.src(['source/assets/images/*'])
      .pipe(gulp.dest('build/assets/images')),
    // Build vendor files.
    gulp.src(['source/vendor/**/*'])
      .pipe(gulp.dest('build/vendor')),
    gulp.src(['build/vendor/requirejs/require.js'])
      .pipe(uglify())
      .pipe(gulp.dest('build/vendor/requirejs')),
    gulp.src(['build/vendor/requirejs-domready/domReady.js'])
      .pipe(uglify())
      .pipe(gulp.dest('build/vendor/requirejs-domready'))
  );
});

// Compiles with RequireJS' r.js.
gulp.task('compile', function () {
  var configRequire = require('./source/js/config-require.js');
  var config = {
    baseUrl: 'source/js',
    name: 'main',
    optimize: 'none',
    out: 'main.js',
    wrap: true,
    stubModules : ['text']
  };
  extend(config, configRequire);

  return rjs(config)
    .pipe(uglify())
    .pipe(gulp.dest('./build/js/'));
});

// Default developer working task.
gulp.task('work', ['watch', 'open']);

gulp.task('default', ['work']);
<|endoftext|>


<commit_before>/**
 *
 *  Web Starter Kit
 *  Copyright 2014 Google Inc. All rights reserved.
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License
 *
 */

'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 pagespeed = require('psi');
var reload = browserSync.reload;

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

// Lint JavaScript
gulp.task('jshint', function () {
  return gulp.src('app/scripts/**/*.js')
    .pipe(reload({stream: true, once: true}))
    .pipe($.jshint())
    .pipe($.jshint.reporter('jshint-stylish'))
    .pipe($.if(!browserSync.active, $.jshint.reporter('fail')));
});

// Optimize Images
gulp.task('images', function () {
  return gulp.src('app/images/**/*')
    .pipe($.cache($.imagemin({
      progressive: true,
      interlaced: true
    })))
    .pipe(gulp.dest('dist/images'))
    .pipe($.size({title: 'images'}));
});

// Copy All Files At The Root Level (app)
gulp.task('copy', function () {
  return gulp.src(['app/*','!app/*.html'])
    .pipe(gulp.dest('dist'))
    .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'}));
});

// Automatically Prefix CSS
gulp.task('styles:css', function () {
  return gulp.src('app/styles/**/*.css')
    .pipe($.changed('app/styles'))
    .pipe($.autoprefixer(AUTOPREFIXER_BROWSERS))
    .pipe(gulp.dest('app/styles'))
    .pipe($.size({title: 'styles:css'}));
});

// Compile Sass For Style Guide Components (app/styles/components)
gulp.task('styles:components', function () {
  return gulp.src('app/styles/components/components.scss')
    .pipe($.rubySass({
      style: 'expanded',
      precision: 10,
      loadPath: ['app/styles/components']
    }))
    .on('error', console.error.bind(console))
    .pipe($.autoprefixer(AUTOPREFIXER_BROWSERS))
    .pipe(gulp.dest('app/styles/components'))
    .pipe($.size({title: 'styles:components'}));
});

// Compile Any Other Sass Files You Added (app/styles)
gulp.task('styles:scss', function () {
  return gulp.src(['app/styles/**/*.scss', '!app/styles/components/components.scss'])
    .pipe($.rubySass({
      style: 'expanded',
      precision: 10,
      loadPath: ['app/styles']
    }))
    .on('error', console.error.bind(console))
    .pipe($.autoprefixer(AUTOPREFIXER_BROWSERS))
    .pipe(gulp.dest('.tmp/styles'))
    .pipe($.size({title: 'styles:scss'}));
});

// Output Final CSS Styles
gulp.task('styles', ['styles:components', 'styles:scss', 'styles:css']);

// Scan Your HTML For Assets & Optimize Them
gulp.task('html', function () {
  return gulp.src('app/**/*.html')
    .pipe($.useref.assets({searchPath: '{.tmp,app}'}))
    // Concatenate And Minify JavaScript
    .pipe($.if('*.js', $.uglify({preserveComments: 'some'})))
    // Remove Any Unused CSS
    // Note: If not using the Style Guide, you can delete it from
    // the next line to only include styles your project uses.
    .pipe($.if('*.css', $.uncss({
      html: [
        'app/index.html',
        'app/styleguide/index.html'
      ],
      // CSS Selectors for UnCSS to ignore
      ignore: [
        '.navdrawer-container.open',
        /.app-bar.open/
      ]
    })))
    // Concatenate And Minify Styles
    .pipe($.if('*.css', $.csso()))
    .pipe($.useref.restore())
    .pipe($.useref())
    // Update Production Style Guide Paths
    .pipe($.replace('components/components.css', 'components/main.min.css'))
    // Minify Any HTML
    .pipe($.if('*.html', $.minifyHtml()))
    // Output Files
    .pipe(gulp.dest('dist'))
    .pipe($.size({title: 'html'}));
});

// Clean Output Directory
gulp.task('clean', del.bind(null, ['.tmp', 'dist']));

// Watch Files For Changes & Reload
gulp.task('serve', function () {
  browserSync({
    notify: false,
    server: {
      baseDir: ['.tmp', 'app']
    }
  });

  gulp.watch(['app/**/*.html'], reload);
  gulp.watch(['app/styles/**/*.scss'], ['styles:components', 'styles:scss']);
  gulp.watch(['{.tmp,app}/styles/**/*.css'], ['styles:css', reload]);
  gulp.watch(['app/scripts/**/*.js'], ['jshint']);
  gulp.watch(['app/images/**/*'], reload);
});

// Build and serve the output from the dist build
gulp.task('serve:dist', ['default'], function () {
  browserSync({
    notify: false,
    server: {
      baseDir: 'dist'
    }
  });
});

// Build Production Files, the Default Task
gulp.task('default', ['clean'], function (cb) {
  runSequence('styles', ['jshint', 'html', 'images', 'fonts', 'copy'], cb);
});

// Run PageSpeed Insights
// Update `url` below to the public URL for your site
gulp.task('pagespeed', pagespeed.bind(null, {
  // By default, we use the PageSpeed Insights
  // free (no API key) tier. You can use a Google
  // Developer API key if you have one. See
  // http://goo.gl/RkN0vE for info key: 'YOUR_API_KEY'
  url: 'https://example.com',
  strategy: 'mobile'
}));

// Load custom tasks from the `tasks` directory
try { require('require-dir')('tasks'); } catch (err) {}
<commit_msg>Update gulpfile.js<commit_after>/**
 *
 *  Web Starter Kit
 *  Copyright 2014 Google Inc. All rights reserved.
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License
 *
 */

'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 pagespeed = require('psi');
var reload = browserSync.reload;

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

// Lint JavaScript
gulp.task('jshint', function () {
  return gulp.src('app/scripts/**/*.js')
    .pipe(reload({stream: true, once: true}))
    .pipe($.jshint())
    .pipe($.jshint.reporter('jshint-stylish'))
    .pipe($.if(!browserSync.active, $.jshint.reporter('fail')));
});

// Optimize Images
gulp.task('images', function () {
  return gulp.src('app/images/**/*')
    .pipe($.cache($.imagemin({
      progressive: true,
      interlaced: true
    })))
    .pipe(gulp.dest('dist/images'))
    .pipe($.size({title: 'images'}));
});

// Copy All Files At The Root Level (app)
gulp.task('copy', function () {
  return gulp.src(['app/*','!app/*.html'])
    .pipe(gulp.dest('dist'))
    .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'}));
});

// Automatically Prefix CSS
gulp.task('styles:css', function () {
  return gulp.src('app/styles/**/*.css')
    .pipe($.changed('app/styles'))
    .pipe($.autoprefixer(AUTOPREFIXER_BROWSERS))
    .pipe(gulp.dest('app/styles'))
    .pipe($.size({title: 'styles:css'}));
});

// Compile Sass For Style Guide Components (app/styles/components)
gulp.task('styles:components', function () {
  return gulp.src('app/styles/components/components.scss')
    .pipe($.rubySass({
      style: 'expanded',
      precision: 10,
      loadPath: ['app/styles/components']
    }))
    .on('error', console.error.bind(console))
    .pipe($.autoprefixer(AUTOPREFIXER_BROWSERS))
    .pipe(gulp.dest('app/styles/components'))
    .pipe($.size({title: 'styles:components'}));
});

// Compile Any Other Sass Files You Added (app/styles)
gulp.task('styles:scss', function () {
  return gulp.src(['app/styles/**/*.scss', '!app/styles/components/components.scss'])
    .pipe($.rubySass({
      style: 'expanded',
      precision: 10,
      loadPath: ['app/styles']
    }))
    .on('error', console.error.bind(console))
    .pipe($.autoprefixer(AUTOPREFIXER_BROWSERS))
    .pipe(gulp.dest('.tmp/styles'))
    .pipe($.size({title: 'styles:scss'}));
});

// Output Final CSS Styles
gulp.task('styles', ['styles:components', 'styles:scss', 'styles:css']);

// Scan Your HTML For Assets & Optimize Them
gulp.task('html', function () {
  return gulp.src('app/**/*.html')
    .pipe($.useref.assets({searchPath: '{.tmp,app}'}))
    // Concatenate And Minify JavaScript
    .pipe($.if('*.js', $.uglify({preserveComments: 'some'})))
    // Remove Any Unused CSS
    // Note: If not using the Style Guide, you can delete it from
    // the next line to only include styles your project uses.
    .pipe($.if('*.css', $.uncss({
      html: [
        'app/index.html',
        'app/styleguide/index.html'
      ],
      // CSS Selectors for UnCSS to ignore
      ignore: [
        '.navdrawer-container.open',
        /.app-bar.open/
      ]
    })))
    // Concatenate And Minify Styles
    .pipe($.if('*.css', $.csso()))
    .pipe($.useref.restore())
    .pipe($.useref())
    // Update Production Style Guide Paths
    .pipe($.replace('components/components.css', 'components/main.min.css'))
    // Minify Any HTML
    .pipe($.if('*.html', $.minifyHtml()))
    // Output Files
    .pipe(gulp.dest('dist'))
    .pipe($.size({title: 'html'}));
});

// Clean Output Directory
gulp.task('clean', del.bind(null, ['.tmp', 'dist']));

// Watch Files For Changes & Reload
gulp.task('serve', function () {
  browserSync({
    notify: false,
    server: {
      baseDir: ['.tmp', 'app']
    }
  });

  gulp.watch(['app/**/*.html'], reload);
  gulp.watch(['app/styles/**/*.scss'], ['styles:components', 'styles:scss']);
  gulp.watch(['{.tmp,app}/styles/**/*.css'], ['styles:css', reload]);
  gulp.watch(['app/scripts/**/*.js'], ['jshint']);
  gulp.watch(['app/images/**/*'], reload);
});

// Build and serve the output from the dist build
gulp.task('serve:dist', ['default'], function () {
  browserSync({
    notify: false,
    server: {
      baseDir: 'dist'
    }
  });
});

// Build Production Files, the Default Task
gulp.task('default', ['clean'], function (cb) {
  runSequence('styles', ['jshint', 'html', 'images', 'fonts', 'copy'], cb);
});

// Run PageSpeed Insights
// Update `url` below to the public URL for your site
gulp.task('pagespeed', pagespeed.bind(null, {
  // By default, we use the PageSpeed Insights
  // free (no API key) tier. You can use a Google
  // Developer API key if you have one. See
  // http://goo.gl/RkN0vE for info key: 'YOUR_API_KEY'
  url: 'https://isc-host.github.io/flags.isc',
  strategy: 'mobile'
}));

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


<commit_before>const gulp = require('gulp');
const $ = require('gulp-load-plugins')();
const fs = require('fs');
const del = require('del');
const glob = require('glob');
const path = require('path');
const mkdirp = require('mkdirp');
const babelify = require('babelify');
const isparta = require('isparta');
const esperanto = require('esperanto');
const browserify = require('browserify');
const runSequence = require('run-sequence');
const source = require('vinyl-source-stream');

const manifest = require('./package.json');
const config = manifest.babelBoilerplateOptions;
const mainFile = manifest.main;
const destinationFolder = path.dirname(mainFile);
const exportFileName = path.basename(mainFile, path.extname(mainFile));

// Remove the built files
gulp.task('clean', function(cb) {
  del([destinationFolder], cb);
});

// Remove our temporary files
gulp.task('clean-tmp', function(cb) {
  del(['tmp'], cb);
});

// Send a notification when JSHint fails,
// so that you know your changes didn't build
function jshintNotify(file) {
  if (!file.jshint) { return; }
  return file.jshint.success ? false : 'JSHint failed';
}

function jscsNotify(file) {
  if (!file.jscs) { return; }
  return file.jscs.success ? false : 'JSRC failed';
}

function createLintTask(taskName, files) {
  gulp.task(taskName, function() {
    return gulp.src(files)
      .pipe($.plumber())
      .pipe($.jshint())
      .pipe($.jshint.reporter('jshint-stylish'))
      .pipe($.notify(jshintNotify))
      .pipe($.jscs())
      .pipe($.notify(jscsNotify))
      .pipe($.jshint.reporter('fail'));
  });
}

// Lint our source code
createLintTask('lint-src', ['src/**/*.js']);

// Lint our test code
createLintTask('lint-test', ['test/**/*.js']);

// Build two versions of the library
gulp.task('build', ['lint-src', 'clean'], function(done) {
  esperanto.bundle({
    base: 'src',
    entry: config.entryFileName,
  }).then(function(bundle) {
    var res = bundle.toUmd({
      sourceMap: true,
      sourceMapSource: config.entryFileName + '.js',
      sourceMapFile: exportFileName + '.js',
      name: config.exportVarName
    });

    // Write the generated sourcemap
    mkdirp.sync(destinationFolder);
    fs.writeFileSync(path.join(destinationFolder, exportFileName + '.js'), res.map.toString());

    $.file(exportFileName + '.js', res.code, { src: true })
      .pipe($.plumber())
      .pipe($.sourcemaps.init({ loadMaps: true }))
      .pipe($.babel({ blacklist: ['useStrict'] }))
      .pipe($.sourcemaps.write('./', {addComment: false}))
      .pipe(gulp.dest(destinationFolder))
      .pipe($.filter(['*', '!**/*.js.map']))
      .pipe($.rename(exportFileName + '.min.js'))
      .pipe($.sourcemaps.init({ loadMaps: true }))
      .pipe($.uglify())
      .pipe($.sourcemaps.write('./'))
      .pipe(gulp.dest(destinationFolder))
      .on('end', done);
  })
  .catch(done);
});

// Bundle our app for our unit tests
gulp.task('browserify', function() {
  var testFiles = glob.sync('./test/unit/**/*');
  var allFiles = ['./test/setup/browserify.js'].concat(testFiles);
  var bundler = browserify(allFiles);
  bundler.transform(babelify.configure({
    sourceMapRelative: __dirname + '/src',
    blacklist: ['useStrict']
  }));
  var bundleStream = bundler.bundle();
  return bundleStream
    .on('error', function(err){
      console.log(err.message);
      this.emit('end');
    })
    .pipe($.plumber())
    .pipe(source('./tmp/__spec-build.js'))
    .pipe(gulp.dest(''))
    .pipe($.livereload());
});

gulp.task('coverage', ['lint-src', 'lint-test'], function(done) {
  require('babel/register')({ modules: 'common' });
  gulp.src(['src/**/*.js'])
    .pipe($.istanbul({ instrumenter: isparta.Instrumenter }))
    .pipe($.istanbul.hookRequire())
    .on('finish', function() {
      return test()
      .pipe($.istanbul.writeReports())
      .on('end', done);
    });
});

function test() {
  return gulp.src(['test/setup/node.js', 'test/unit/**/*.js'], {read: false})
    .pipe($.mocha({reporter: 'dot', globals: config.mochaGlobals}));
};

// Lint and run our tests
gulp.task('test', ['lint-src', 'lint-test'], function() {
  require('babel/register')({ modules: 'common' });
  return test();
});

// Ensure that linting occurs before browserify runs. This prevents
// the build from breaking due to poorly formatted code.
gulp.task('build-in-sequence', function(callback) {
  runSequence(['lint-src', 'lint-test'], 'browserify', callback);
});

const watchFiles = ['src/**/*', 'test/**/*', 'package.json', '**/.jshintrc', '.jscsrc'];

// Run the headless unit tests as you make changes.
gulp.task('watch', function() {
  gulp.watch(watchFiles, ['test']);
});

// Set up a livereload environment for our spec runner
gulp.task('test-browser', ['build-in-sequence'], function() {
  $.livereload.listen({port: 35729, host: 'localhost', start: true});
  return gulp.watch(watchFiles, ['build-in-sequence']);
});

// An alias of test
gulp.task('default', ['test']);
<commit_msg>Utilize default options of babel.<commit_after>const gulp = require('gulp');
const $ = require('gulp-load-plugins')();
const fs = require('fs');
const del = require('del');
const glob = require('glob');
const path = require('path');
const mkdirp = require('mkdirp');
const babelify = require('babelify');
const isparta = require('isparta');
const esperanto = require('esperanto');
const browserify = require('browserify');
const runSequence = require('run-sequence');
const source = require('vinyl-source-stream');

const manifest = require('./package.json');
const config = manifest.babelBoilerplateOptions;
const mainFile = manifest.main;
const destinationFolder = path.dirname(mainFile);
const exportFileName = path.basename(mainFile, path.extname(mainFile));

// Remove the built files
gulp.task('clean', function(cb) {
  del([destinationFolder], cb);
});

// Remove our temporary files
gulp.task('clean-tmp', function(cb) {
  del(['tmp'], cb);
});

// Send a notification when JSHint fails,
// so that you know your changes didn't build
function jshintNotify(file) {
  if (!file.jshint) { return; }
  return file.jshint.success ? false : 'JSHint failed';
}

function jscsNotify(file) {
  if (!file.jscs) { return; }
  return file.jscs.success ? false : 'JSRC failed';
}

function createLintTask(taskName, files) {
  gulp.task(taskName, function() {
    return gulp.src(files)
      .pipe($.plumber())
      .pipe($.jshint())
      .pipe($.jshint.reporter('jshint-stylish'))
      .pipe($.notify(jshintNotify))
      .pipe($.jscs())
      .pipe($.notify(jscsNotify))
      .pipe($.jshint.reporter('fail'));
  });
}

// Lint our source code
createLintTask('lint-src', ['src/**/*.js']);

// Lint our test code
createLintTask('lint-test', ['test/**/*.js']);

// Build two versions of the library
gulp.task('build', ['lint-src', 'clean'], function(done) {
  esperanto.bundle({
    base: 'src',
    entry: config.entryFileName,
  }).then(function(bundle) {
    var res = bundle.toUmd({
      sourceMap: true,
      sourceMapSource: config.entryFileName + '.js',
      sourceMapFile: exportFileName + '.js',
      name: config.exportVarName
    });

    // Write the generated sourcemap
    mkdirp.sync(destinationFolder);
    fs.writeFileSync(path.join(destinationFolder, exportFileName + '.js'), res.map.toString());

    $.file(exportFileName + '.js', res.code, { src: true })
      .pipe($.plumber())
      .pipe($.sourcemaps.init({ loadMaps: true }))
      .pipe($.babel({ blacklist: ['useStrict'] }))
      .pipe($.sourcemaps.write('./', {addComment: false}))
      .pipe(gulp.dest(destinationFolder))
      .pipe($.filter(['*', '!**/*.js.map']))
      .pipe($.rename(exportFileName + '.min.js'))
      .pipe($.sourcemaps.init({ loadMaps: true }))
      .pipe($.uglify())
      .pipe($.sourcemaps.write('./'))
      .pipe(gulp.dest(destinationFolder))
      .on('end', done);
  })
  .catch(done);
});

// Bundle our app for our unit tests
gulp.task('browserify', function() {
  var testFiles = glob.sync('./test/unit/**/*');
  var allFiles = ['./test/setup/browserify.js'].concat(testFiles);
  var bundler = browserify(allFiles);
  bundler.transform(babelify.configure({
    sourceMapRelative: __dirname + '/src',
    blacklist: ['useStrict']
  }));
  var bundleStream = bundler.bundle();
  return bundleStream
    .on('error', function(err){
      console.log(err.message);
      this.emit('end');
    })
    .pipe($.plumber())
    .pipe(source('./tmp/__spec-build.js'))
    .pipe(gulp.dest(''))
    .pipe($.livereload());
});

gulp.task('coverage', ['lint-src', 'lint-test'], function(done) {
  require('babel/register');
  gulp.src(['src/**/*.js'])
    .pipe($.istanbul({ instrumenter: isparta.Instrumenter }))
    .pipe($.istanbul.hookRequire())
    .on('finish', function() {
      return test()
      .pipe($.istanbul.writeReports())
      .on('end', done);
    });
});

function test() {
  return gulp.src(['test/setup/node.js', 'test/unit/**/*.js'], {read: false})
    .pipe($.mocha({reporter: 'dot', globals: config.mochaGlobals}));
};

// Lint and run our tests
gulp.task('test', ['lint-src', 'lint-test'], function() {
  require('babel/register');
  return test();
});

// Ensure that linting occurs before browserify runs. This prevents
// the build from breaking due to poorly formatted code.
gulp.task('build-in-sequence', function(callback) {
  runSequence(['lint-src', 'lint-test'], 'browserify', callback);
});

const watchFiles = ['src/**/*', 'test/**/*', 'package.json', '**/.jshintrc', '.jscsrc'];

// Run the headless unit tests as you make changes.
gulp.task('watch', function() {
  gulp.watch(watchFiles, ['test']);
});

// Set up a livereload environment for our spec runner
gulp.task('test-browser', ['build-in-sequence'], function() {
  $.livereload.listen({port: 35729, host: 'localhost', start: true});
  return gulp.watch(watchFiles, ['build-in-sequence']);
});

// An alias of test
gulp.task('default', ['test']);
<|endoftext|>


<commit_before>var gulp = require('gulp');
var browserify = require('browserify');
var babelify = require('babelify');
var brfs = require('brfs');
var watchify = require('watchify');

var concat = require('gulp-concat');
var rename = require('gulp-rename');
var sourcemaps = require('gulp-sourcemaps');
var iife = require("gulp-iife");
var runSequence = require('run-sequence');
var bowerFiles = require('bower-files')();
var uglify = require('gulp-uglify');
var sass = require('gulp-sass');
var mocha = require('gulp-spawn-mocha');
var eslint = require('gulp-eslint');
var codecov = require('gulp-codecov.io');
var notify = require("gulp-notify");
var buffer = require('vinyl-buffer');
var source = require('vinyl-source-stream');

var gulpUtils = require('anyware/gulp-utils');

var browserSync = require('browser-sync').create();

gulp.task('default', function(callback) {
  return runSequence('clean', 'lint', 'test', 'css', 'images', 'build', callback);
});

/* This task will only work from a Travis like CI environment */
gulp.task('submit-coverage', function submitCoverage() {
  return gulp.src('coverage/lcov.info')
    .pipe(codecov());
});

gulp.task('watch', ['build-dependencies', 'build-watch', 'css', 'build-index', 'images', 'collect-sounds'], function() {
  gulp.watch(['bower_components/**/*.js'], ['build-dependencies']);
  gulp.watch(['index.html'], ['build-index']);
  gulp.watch(['styles/**/*.scss'], ['css']);
});

gulp.task('watchTests', function watchTests() {
  gulp.watch(['src/**/*.js{,x}', 'test/**/*.js{,x}'], ['lint', 'test']);
});

gulp.task('build', function build(callback) {
  return runSequence('build-dependencies', 'build-nowatch', 'build-index', 'images', 'collect-sounds', callback);
});

/*
  Creates a browserified stream of the given files and calls the passed bundle function.a
  if watch is true, will automatically watch and rebuild using the passed bundle function.

  The bundle function must take a stream as parameter and produce the appropriate output.
*/
function createBrowserifiedStream(files, watch, bundle) {
  var b = browserify({entries: files,
// Disabling until this is fixed: https://github.com/substack/node-browserify/issues/1386
//                      debug: true,
                      extensions: ['.jsx']
                     })
    .transform(babelify.configure({
      presets: ['react', 'es2015'],
      plugins: ['transform-class-properties']
    }))
    .transform(brfs);

  if (watch) {
    var w = watchify(b, {ignoreWatch: false});
    w.on('update', function() {
      console.log("Updating...");
      return bundle(b);
    });
  }
  return bundle(b);
}

/*
  Takes a browserify stream as input and produces a bundled output
*/
 function bundleApp(b) {
  return b.bundle()
    .on('error', function(err) {
      return notify().write(err);
    })
    .pipe(source('app.js'))
    .pipe(buffer())
    .pipe(sourcemaps.init({loadMaps: true}))
    .pipe(iife({useStrict: false}))
    .pipe(uglify())
    .pipe(sourcemaps.write())
    .pipe(gulp.dest(gulpUtils.getDistPath()))
    .pipe(notify("Build app done!"))
    .pipe(browserSync.reload({stream: true, once: true}));
}

var browserify_files = ['src/emulator-app.js'];
gulp.task('build-nowatch', function() {
  return createBrowserifiedStream(browserify_files, false, bundleApp);
});

gulp.task('build-watch', function() {
  return createBrowserifiedStream(browserify_files, true, bundleApp);
});

var debug = require('gulp-debug');
gulp.task('build-app', function buildDependencies() {
  return gulp.src(['src/emulator-app.js'])
    .pipe(browserified)
    .pipe(sourcemaps.init({loadMaps: true}))
    .pipe(iife({useStrict: false}))
// concat isn't necessary since browserified outputs a single file
//    .pipe(concat('app.js'))
    .pipe(rename('app.js'))
    .pipe(uglify())
    .pipe(sourcemaps.write())
    .pipe(gulp.dest(gulpUtils.getDistPath()))
    .pipe(notify("Build app done!"));
});

gulp.task('build-dependencies', function buildApp() {
  return gulp.src(bowerFiles.ext('js').files)
    .pipe(sourcemaps.init())
    .pipe(concat('dependencies.js'))
    .pipe(uglify())
    .pipe(sourcemaps.write())
    .pipe(gulp.dest(gulpUtils.getDistPath()));
});

gulp.task('build-index', function buildIndex() {
  return gulp.src('index.html')
    .pipe(gulp.dest(gulpUtils.getDistPath()));
});

gulp.task('collect-sounds', function collectSounds() {
  return gulp.src(['node_modules/@anyware/sound-assets/**/*.wav'])
    .pipe(gulp.dest(gulpUtils.getDistPath('sounds')));
});

gulp.task('css', function buildCSS() {
  return gulp.src('styles/app.scss')
    .pipe(sourcemaps.init())
    .pipe(sass().on('error', sass.logError))
    .pipe(sourcemaps.write())
    .pipe(gulp.dest(gulpUtils.getDistPath('css')));
});

gulp.task('images', function distImages() {
  return gulp.src(['images/*.png', 'images/*.jpg', 'images/*.gif'])
    .pipe(gulp.dest(gulpUtils.getDistPath('images')));
});

gulp.task('clean', function clean(callback) {
  gulpUtils.removeDistFiles(callback);
});

gulp.task('lint', function lint() {
  return gulp.src(["src/**/*.js{,x}", "test/**/*.js{,x}"])
    .pipe(eslint('node_modules/anyware/.eslintrc'))
    .pipe(eslint.format());
});

gulp.task('test', function test() {
  return gulp.src('test/**/*-test.js{,x}', {read: false})
    .pipe(mocha({
      reporter: process.env.TRAVIS ? 'spec' : 'nyan',
      compilers: 'js:babel-register'
    }));
});

gulp.task('serve', ['watch'], function () {
  browserSync.init(null, {
    server: {
      baseDir: 'lib'
    },
    startPath: 'index.html',
    debugInfo: false,
    open: true,
    hostnameSuffix: ""
  });
});
<commit_msg>Re-enable sourcemaps<commit_after>var gulp = require('gulp');
var browserify = require('browserify');
var babelify = require('babelify');
var brfs = require('brfs');
var watchify = require('watchify');

var concat = require('gulp-concat');
var rename = require('gulp-rename');
var sourcemaps = require('gulp-sourcemaps');
var iife = require("gulp-iife");
var runSequence = require('run-sequence');
var bowerFiles = require('bower-files')();
var uglify = require('gulp-uglify');
var sass = require('gulp-sass');
var mocha = require('gulp-spawn-mocha');
var eslint = require('gulp-eslint');
var codecov = require('gulp-codecov.io');
var notify = require("gulp-notify");
var buffer = require('vinyl-buffer');
var source = require('vinyl-source-stream');

var gulpUtils = require('anyware/gulp-utils');

var browserSync = require('browser-sync').create();

gulp.task('default', function(callback) {
  return runSequence('clean', 'lint', 'test', 'css', 'images', 'build', callback);
});

/* This task will only work from a Travis like CI environment */
gulp.task('submit-coverage', function submitCoverage() {
  return gulp.src('coverage/lcov.info')
    .pipe(codecov());
});

gulp.task('watch', ['build-dependencies', 'build-watch', 'css', 'build-index', 'images', 'collect-sounds'], function() {
  gulp.watch(['bower_components/**/*.js'], ['build-dependencies']);
  gulp.watch(['index.html'], ['build-index']);
  gulp.watch(['styles/**/*.scss'], ['css']);
});

gulp.task('watchTests', function watchTests() {
  gulp.watch(['src/**/*.js{,x}', 'test/**/*.js{,x}'], ['lint', 'test']);
});

gulp.task('build', function build(callback) {
  return runSequence('build-dependencies', 'build-nowatch', 'build-index', 'images', 'collect-sounds', callback);
});

/*
  Creates a browserified stream of the given files and calls the passed bundle function.a
  if watch is true, will automatically watch and rebuild using the passed bundle function.

  The bundle function must take a stream as parameter and produce the appropriate output.
*/
function createBrowserifiedStream(files, watch, bundle) {
  var b = browserify({entries: files,
                      debug: true,
                      extensions: ['.jsx']
                     })
    .transform(babelify.configure({
      presets: ['react', 'es2015'],
      plugins: ['transform-class-properties']
    }))
    .transform(brfs);

  if (watch) {
    var w = watchify(b, {ignoreWatch: false});
    w.on('update', function() {
      console.log("Updating...");
      return bundle(b);
    });
  }
  return bundle(b);
}

/*
  Takes a browserify stream as input and produces a bundled output
*/
 function bundleApp(b) {
  return b.bundle()
    .on('error', function(err) {
      return notify().write(err);
    })
    .pipe(source('app.js'))
    .pipe(buffer())
    .pipe(sourcemaps.init({loadMaps: true}))
    .pipe(iife({useStrict: false}))
    .pipe(uglify())
    .pipe(sourcemaps.write('./'))
    .pipe(gulp.dest(gulpUtils.getDistPath()))
    .pipe(notify("Build app done!"))
    .pipe(browserSync.reload({stream: true, once: true}));
}

var browserify_files = ['src/emulator-app.js'];
gulp.task('build-nowatch', function() {
  return createBrowserifiedStream(browserify_files, false, bundleApp);
});

gulp.task('build-watch', function() {
  return createBrowserifiedStream(browserify_files, true, bundleApp);
});

var debug = require('gulp-debug');
gulp.task('build-app', function buildDependencies() {
  return gulp.src(['src/emulator-app.js'])
    .pipe(browserified)
    .pipe(sourcemaps.init({loadMaps: true}))
    .pipe(iife({useStrict: false}))
// concat isn't necessary since browserified outputs a single file
//    .pipe(concat('app.js'))
    .pipe(rename('app.js'))
    .pipe(uglify())
    .pipe(sourcemaps.write())
    .pipe(gulp.dest(gulpUtils.getDistPath()))
    .pipe(notify("Build app done!"));
});

gulp.task('build-dependencies', function buildApp() {
  return gulp.src(bowerFiles.ext('js').files)
    .pipe(sourcemaps.init())
    .pipe(concat('dependencies.js'))
    .pipe(uglify())
    .pipe(sourcemaps.write())
    .pipe(gulp.dest(gulpUtils.getDistPath()));
});

gulp.task('build-index', function buildIndex() {
  return gulp.src('index.html')
    .pipe(gulp.dest(gulpUtils.getDistPath()));
});

gulp.task('collect-sounds', function collectSounds() {
  return gulp.src(['node_modules/@anyware/sound-assets/**/*.wav'])
    .pipe(gulp.dest(gulpUtils.getDistPath('sounds')));
});

gulp.task('css', function buildCSS() {
  return gulp.src('styles/app.scss')
    .pipe(sourcemaps.init())
    .pipe(sass().on('error', sass.logError))
    .pipe(sourcemaps.write())
    .pipe(gulp.dest(gulpUtils.getDistPath('css')));
});

gulp.task('images', function distImages() {
  return gulp.src(['images/*.png', 'images/*.jpg', 'images/*.gif'])
    .pipe(gulp.dest(gulpUtils.getDistPath('images')));
});

gulp.task('clean', function clean(callback) {
  gulpUtils.removeDistFiles(callback);
});

gulp.task('lint', function lint() {
  return gulp.src(["src/**/*.js{,x}", "test/**/*.js{,x}"])
    .pipe(eslint('node_modules/anyware/.eslintrc'))
    .pipe(eslint.format());
});

gulp.task('test', function test() {
  return gulp.src('test/**/*-test.js{,x}', {read: false})
    .pipe(mocha({
      reporter: process.env.TRAVIS ? 'spec' : 'nyan',
      compilers: 'js:babel-register'
    }));
});

gulp.task('serve', ['watch'], function () {
  browserSync.init(null, {
    server: {
      baseDir: 'lib'
    },
    startPath: 'index.html',
    debugInfo: false,
    open: true,
    hostnameSuffix: ""
  });
});
<|endoftext|>


<commit_before>'use strict';
/**
 * Created by ivo.cazemier on 01/11/16.
 */

const gulp = require('gulp');
const istanbul = require('gulp-istanbul');
const mocha = require('gulp-mocha');
const eslint = require('gulp-eslint');
const jsdoc = require('gulp-jsdoc3');
const plumber = require('gulp-plumber');

gulp.doneCallback = function (err) {
    process.exit(err ? 1 : 0);
};

gulp.task('default', ['lint', 'test', 'docs']);

gulp.task('pre-test', () => {
    return gulp.src(['lib/**/*.js'])
    // Covering files
        .pipe(istanbul({includeUntested: true}))
        // Force `require` to return covered files
        .pipe(istanbul.hookRequire());
});

gulp.task('test', ['pre-test'], () => {

    return gulp.src(['test/**/*.test.js', '!test/coverage/*'], {read: false})
        .pipe(plumber())
        .pipe(mocha({
            reporter: 'spec',
            globals: {}
        }))
        // Creating the reports after tests ran
        .pipe(istanbul.writeReports({
            dir: './test/coverage'
        }))
        // Enforce coverage
        .pipe(istanbul.enforceThresholds({
            thresholds: {
                global: 80
                // {
                //     statements: 90,
                //     branches: 90,
                //     functions: 90,
                //     lines: 90
                // }
            }
        }));
});

gulp.task('lint', () => {
    // ESLint ignores files with "node_modules" paths.
    // So, it's best to have gulp ignore the directory as well.
    // Also, Be sure to return the stream from the task;
    // Otherwise, the task may end before the stream has finished.
    return gulp.src(['lib/**/*.js', '!node_modules/**'])
    // eslint() attaches the lint output to the "eslint" property
    // of the file object so it can be used by other modules.
        .pipe(eslint())
        // eslint.format() outputs the lint results to the console.
        // Alternatively use eslint.formatEach() (see Docs).
        .pipe(eslint.format())
        // To have the process exit with an error code (1) on
        // lint error, return the stream and pipe to failAfterError last.
        .pipe(eslint.failAfterError());
});

gulp.task('watch-test', () => {
    gulp.watch(['lib/**', 'index.js', 'test/**'], ['test']);
});

gulp.task('docs', (cb) => {
    const config = require('./config/jsdocs');
    gulp.src(['README.md', './index.js', './lib/**/*.js'], {read: false})
        .pipe(plumber())
        .pipe(jsdoc(config, cb));
});
<commit_msg>Bumped coverage to 100%<commit_after>'use strict';
/**
 * Created by ivo.cazemier on 01/11/16.
 */

const gulp = require('gulp');
const istanbul = require('gulp-istanbul');
const mocha = require('gulp-mocha');
const eslint = require('gulp-eslint');
const jsdoc = require('gulp-jsdoc3');
const plumber = require('gulp-plumber');

gulp.doneCallback = function (err) {
    process.exit(err ? 1 : 0);
};

gulp.task('default', ['lint', 'test', 'docs']);

gulp.task('pre-test', () => {
    return gulp.src(['lib/**/*.js'])
    // Covering files
        .pipe(istanbul({includeUntested: true}))
        // Force `require` to return covered files
        .pipe(istanbul.hookRequire());
});

gulp.task('test', ['pre-test'], () => {

    return gulp.src(['test/**/*.test.js', '!test/coverage/*'], {read: false})
        .pipe(plumber())
        .pipe(mocha({
            reporter: 'spec',
            globals: {}
        }))
        // Creating the reports after tests ran
        .pipe(istanbul.writeReports({
            dir: './test/coverage'
        }))
        // Enforce coverage
        .pipe(istanbul.enforceThresholds({
            thresholds: {
                global: 100
                // {
                //     statements: 90,
                //     branches: 90,
                //     functions: 90,
                //     lines: 90
                // }
            }
        }));
});

gulp.task('lint', () => {
    // ESLint ignores files with "node_modules" paths.
    // So, it's best to have gulp ignore the directory as well.
    // Also, Be sure to return the stream from the task;
    // Otherwise, the task may end before the stream has finished.
    return gulp.src(['lib/**/*.js', '!node_modules/**'])
    // eslint() attaches the lint output to the "eslint" property
    // of the file object so it can be used by other modules.
        .pipe(eslint())
        // eslint.format() outputs the lint results to the console.
        // Alternatively use eslint.formatEach() (see Docs).
        .pipe(eslint.format())
        // To have the process exit with an error code (1) on
        // lint error, return the stream and pipe to failAfterError last.
        .pipe(eslint.failAfterError());
});

gulp.task('watch-test', () => {
    gulp.watch(['lib/**', 'index.js', 'test/**'], ['test']);
});

gulp.task('docs', (cb) => {
    const config = require('./config/jsdocs');
    gulp.src(['README.md', './index.js', './lib/**/*.js'], {read: false})
        .pipe(plumber())
        .pipe(jsdoc(config, cb));
});
<|endoftext|>


<commit_before>(function () {
   'use strict';
   var gulp = require('gulp'),

      fs = require('fs'),

      rename = require('gulp-rename'),

      concat = require('gulp-concat'),

      uglify = require('gulp-uglify'),

      jshint = require('gulp-jshint'),

      insert = require('gulp-insert'),

      stripDebug = require('gulp-strip-debug'),

      sourcemaps = require('gulp-sourcemaps'),

      sass = require('gulp-ruby-sass'),

      cssnano = require('gulp-cssnano'),

      htmlReplace = require('gulp-html-replace'),

      del = require('del'),

      path = require('path'),

      gulpFile = require('gulp-file'),

      foreach = require('gulp-foreach'),

      json_merger = require('json_merger'),

      jsonminify = require('gulp-jsonminify'),

      babel = require('gulp-babel'),

      jscs = require('gulp-jscs'),

      vinylfs = require('vinyl-fs');

   var projectRoot = __dirname + '/../../';

   var transpileDir = projectRoot + '/src/transpiled/';

   var buildDir = projectRoot + '/dist/';

   var bundleThirdPartyLibraries = false;

   // All file paths used in the gulp file are inside this object
   var paths = {
      js: {
         source: projectRoot + '/src/js/',
         transpiled: transpileDir + '/js/',
         build: buildDir + '/js/',
         sourceRoot: '/js/',
         coreLibraryFile: projectRoot + '/node_modules/widget-core-library/dist/core.js',
         thirdPartyLibraryFile: projectRoot + '/node_modules/third-party-dependencies/dist/thirdparty.js',
      },
      css: {
         source: projectRoot + '/src/scss/',
         transpiled: transpileDir + '/css/',
         build: buildDir + '/css/',
         sourceRoot: '../../scss/'
      },
      i18n: {
         source: projectRoot + '/src/i18n/',
         coreLibrarySource: projectRoot + '/node_modules/widget-core-library/src/i18n/',
         transpiled: transpileDir + '/i18n/',
         build: buildDir + '/i18n/'
      },
      views: {
         source: projectRoot + '/src/views/*.html',
         transpiled: transpileDir + '/js/views/'
      },
      fonts: {
         source: projectRoot + '/node_modules/widget-core-library/src/fonts/**/*',
         transpiled: transpileDir + '/fonts/',
         build: buildDir + '/fonts/'
      },
      configFiles: [
         projectRoot + '/node_modules/widget-build-tools/widget_config/gitignore',
         projectRoot + '/node_modules/widget-build-tools/widget_config/.editorconfig',
         projectRoot + '/node_modules/widget-build-tools/widget_config/.jshintrc',
         projectRoot + '/node_modules/widget-build-tools/widget_config/.jscsrc',
         projectRoot + '/node_modules/widget-build-tools/widget_config/config.rb',
         projectRoot + '/node_modules/widget-build-tools/widget_config/LICENSE',
         projectRoot + '/node_modules/widget-build-tools/widget_config/.scss-lint.yml'
      ],
      staticFiles: [
         './src/**/*',
         '!./src/js/**',
         '!./src/js/',
         '!./src/scss/**',
         '!./src/scss/',
         '!./src/i18n/**',
         '!./src/i18n/',
         '!./src/transpiled/**',
         '!./src/transpiled/'
      ]
   };

   var buildParameters;
   try {
      buildParameters = JSON.parse(fs.readFileSync('./buildparameters.json'));
   } catch (e) {
      buildParameters = {};
   }

   var coreLibConfig, widgetConfig, buildToolsConfig, dependencyCoreLibVersion, dependencyBuildToolsVersion;
   try {
      coreLibConfig = JSON.parse(fs.readFileSync('./node_modules/widget-core-library/package.json'));
      widgetConfig = JSON.parse(fs.readFileSync('./package.json'));

      buildToolsConfig = JSON.parse(fs.readFileSync('./node_modules/widget-build-tools/package.json'));

      dependencyBuildToolsVersion = widgetConfig.devDependencies['widget-build-tools'].split('#')[1];
      if (dependencyBuildToolsVersion.charAt(0) === 'v') {
         dependencyBuildToolsVersion = dependencyBuildToolsVersion.slice(1);
      }

      dependencyCoreLibVersion = widgetConfig.devDependencies['widget-core-library'].split('#')[1];
      if (dependencyCoreLibVersion.charAt(0) === 'v') {
         dependencyCoreLibVersion = dependencyCoreLibVersion.slice(1);
      }
   } catch (e) {
      throw new Error('Could not read package.json of the widget or one of its dependencies');
   }

   if (dependencyCoreLibVersion !== coreLibConfig.version) {
      throw new Error(
         'widget-core-library dependency does not match node_modules dependency version. Expected: ' +
         dependencyCoreLibVersion +
         ' got ' +
         coreLibConfig.version +
         ' \nPlease run npm install (not npm update!)');
   }

   if (dependencyBuildToolsVersion !== buildToolsConfig.version) {
      throw new Error(
         'widget-build-tools dependency does not match node_modules dependency version. Expected: ' +
         dependencyBuildToolsVersion +
         ' got ' +
         buildToolsConfig.version +
         ' \nPlease run npm install (not npm update!)');
   }

   /**
    * Copies project configuration files from the build tools into the project
    */
   gulp.task('copy-config-files', function () {
      return gulp.src(paths.configFiles)
         .pipe(rename(function ( path ) {
            // .gitignore has special handling because npm strips .gitignore files
            // when downloading dependencies
            if ( path.basename === 'gitignore' ) {
               path.basename = '.gitignore';
            }
         }))
         .pipe(vinylfs.dest(projectRoot, { overwrite: true })); // same as gulp.dest, but accepts an overwrite flag
   });

   gulp.task('clean-temp', function () {
      return del.sync(transpileDir);
   });

   /**
    * Cleans the project (deletes transpileDir and buildDir folders)
    */
   gulp.task('clean', ['clean-temp'], function () {
      return del.sync(buildDir);
   });

   /**
    * Cleans then builds
    */
   gulp.task('default', ['clean'], function () {
      return gulp.start('build');
   });

   /**
    * Same as default but bundles the third party library file with
    * the javascript file
    */
   gulp.task('default-bundle', ['clean'], function () {
      bundleThirdPartyLibraries = true;
      return gulp.start('build');
   });

   /**
    * Tasks used by 'build' to run everything in the right order
    */
   gulp.task('build2', ['copy-config-files'], function () {
      return gulp.start('build3');
   });
   gulp.task('build3', ['compile'], function () {
      return gulp.start('build4');
   });
   gulp.task('build4', ['bundle-static', 'bundle-css', 'bundle-js', 'bundle-fonts'], function () {
      return gulp.start('build5');
   });
   gulp.task('build5', ['html-replace']);

   /**
    * Full build cycle with compilling and minifying
    */
   gulp.task('build', ['build2']);

   /**
    * Replaces references inside index.html to reference the minified and concatanated
    * js and css files
    */
   gulp.task('html-replace', function () {
      var resourcePaths;
      try {
         resourcePaths = JSON.parse(fs.readFileSync('./resourcepaths.json'));
      } catch (e) {
         throw new Error('could not read resourcepaths.json');
      }
      if (resourcePaths.htmlReplace == null) {
         resourcePaths.htmlReplace = {};
      }

      var kambiAPIVersion = coreLibConfig['kambi-widget-api-version'] != null ? coreLibConfig['kambi-widget-api-version'] : '1.0.0.10';

      var kambiWidgetAPIUrl = 'https://c3-static.kambi.com/sb-mobileclient/widget-api/{{API_VERSION}}/kambi-widget-api.js'
         .replace('{{API_VERSION}}', kambiAPIVersion);

      var references = {
         js: 'js/app.min.js',
         css: 'css/app.min.css',
         'kambi-widget-api': kambiWidgetAPIUrl
      };
      if (!bundleThirdPartyLibraries) {
         references['third-party-libs'] = resourcePaths.thirdPartyLibs;
      }

      references = extendObj(
         references,
         resourcePaths.htmlReplace
      );
      return gulp.src('./src/index.html')
         .pipe(htmlReplace(references))
         .pipe(gulp.dest('./dist'));
   });

   /**
    * Compiles all scss files and places them in {transpileDir}/css/ folder
    */
   gulp.task('compile-scss', [], function () {
      return sass(paths.css.source + 'app.scss', {
            compass: true,
            style: 'expanded',
            lineComments: false,
            sourcemap: true
         })
         .pipe(sourcemaps.write('.', {
            includeContent: false,
            sourceRoot: paths.css.sourceRoot
         }))
         .pipe(gulp.dest(paths.css.transpiled));
   });

   /**
    * Compiles all js files using Babel and places them in {transpileDir} folder
    */
   gulp.task('compile-babel', [], function () {
      var sourceRootMap = function (file) {
         return '../' + path.relative(file.history[0], paths.js.source) + paths.js.sourceRoot;
      };
      return gulp.src(paths.js.source + '/**/*.js')
         .pipe(jshint('.jshintrc'))
         .pipe(jshint.reporter('default'))
         .pipe(jscs())
         .pipe(jscs.reporter())
         .pipe(sourcemaps.init())
         .pipe(babel({
            presets: ['es2015']
         }))
         .pipe(sourcemaps.write('.', {
            includeContent: false,
            sourceRoot: sourceRootMap
         }))
         .pipe(gulp.dest(paths.js.transpiled));
   });

   /**
    * Copies all static files (.html, .json, images) to transpileDir folder, i18n files are handled
    * by the compile-translations task
    */
   gulp.task('compile-static', [], function () {
      return gulp.src(paths.staticFiles)
         .pipe(gulp.dest(transpileDir));
   });

   /**
    * Transforms all .html files from /src/views into javascript files
    * that add the content of the original files as strings in global
    * names defined by the original file name
    */
   gulp.task('compile-views', [], function () {
      return gulp.src(paths.views.source)
         .pipe(foreach(function ( stream, file ) {
            var name = path.basename(file.path);
            name = name.slice(0, -5);
            return stream
               .pipe(insert.prepend('window["' + name + '-view' + '"] = `'))
               .pipe(insert.append('`;'));
         }))
         .pipe(rename(function (path) {
            path.extname = '.js';
         }))
         .pipe(babel({ // babel does the scaping of the file convertin `` to ""
            presets: ['es2015']
         }))
         .pipe(gulp.dest(paths.views.transpiled));
   });

   /**
    * Copies all fonts from widget-core-library to transpileDir
    */
   gulp.task('compile-fonts', [], function () {
      return gulp.src(paths.fonts.source)
         .pipe(gulp.dest(paths.fonts.transpiled));
   });

   /**
    * Compiles all js, scss and i18n files and place them (alongside static files) in the dist
    * folder
    */
   gulp.task('compile', [
      'compile-babel',
      'compile-scss',
      'compile-translations',
      'compile-static',
      'compile-views',
      'compile-fonts'
   ]);

   /**
    * Watches for any change in the files inside /src/ folder and recompiles them
    */
   gulp.task('watch', [], function () {
      gulp.watch(paths.js.source + '/**/*.js', ['compile-babel']);
      gulp.watch(paths.css.source + '/**/*.scss', ['compile-scss']);
      gulp.watch(paths.i18n.source + '/**/*.json', ['compile-translations']);
      gulp.watch(paths.staticFiles, ['compile-static']);
      gulp.watch(paths.views.source, ['compile-views']);
      gulp.watch(paths.fonts.source, ['compile-fonts']);
   });

   /**
    * Minifies and concatenates all css files from {transpileDir} into {buildDir}
    */
   gulp.task('bundle-css', function () {
      return gulp.src(paths.css.transpiled + '/**/*.css')
         .pipe(concat('app.css'))
         .pipe(gulp.dest(paths.css.build))
         .pipe(cssnano({
            autoprefixer: false // If true removes older browser prefixes from code
         }))
         .pipe(rename('app.min.css'))
         .pipe(gulp.dest(paths.css.build));
   });

   /**
    * Minifies and concatenates all js files from {transpileDir} into {buildDir}
    */
   gulp.task('bundle-js', function () {
      var files = [
         paths.js.coreLibraryFile,
         paths.js.transpiled + '**/*.js'
      ];
      if (bundleThirdPartyLibraries) {
         files = [paths.js.thirdPartyLibraryFile].concat(files);
      }
      fs.exists(paths.js.thirdPartyLibraryFile, function (e) {
         console.log(e);
      });
      return gulp.src(files)
         .pipe(concat('app.js'))
         .pipe(stripDebug())
         .pipe(gulp.dest(paths.js.build))
         .pipe(uglify())
         .pipe(rename('app.min.js'))
         .pipe(gulp.dest(paths.js.build));
   });

   /**
    * Copies all static files (.html, .json, images) to buildDir folder, i18n files are handled
    * by the compile-translations task
    */
   gulp.task('bundle-static', [], function () {
      return gulp.src(paths.staticFiles)
         .pipe(gulp.dest(buildDir));
   });

   /**
    * Copies all font files from widget-core-library to buildDir folder
    */
   gulp.task('bundle-fonts', [], function () {
      return gulp.src(paths.fonts.source)
         .pipe(gulp.dest(paths.fonts.build));
   });

   /**
    * Merges widget i18n files with cherry-picked strings from the widget-core-library
    */
   gulp.task('compile-translations', function () {
      return gulp.src(paths.i18n.source + '/**/*.json')
         .pipe(foreach(function ( stream, file ) {
            var name = path.basename(file.path);
            var filePath = paths.i18n.coreLibrarySource + name;
            var srcJson = JSON.parse(file.contents.toString());
            var selectedFromKambi = {};

            try {
               fs.statSync(filePath); // throws error if file does not exist
               var coreLibraryJson = json_merger.fromFile(filePath);

               // buildParameters.localeStrings should be an object in the following format:
               // { "keyInI18nJSON": "pathToValueInKambiI18nJSON" }
               if (buildParameters.localeStrings != null) {
                  Object.keys(buildParameters.localeStrings).forEach(function ( key ) {
                     // creates a new function that retrieves the string specified by the path in localeStrings from the localeJson
                     /* jslint evil: true */
                     selectedFromKambi[key] = new Function('json', 'return json.' + buildParameters.localeStrings[key])(coreLibraryJson);
                  });
               }

               var result = extendObj(srcJson, selectedFromKambi);
               // TODO find a way to make this synchronous:
               gulpFile(name, JSON.stringify(result, null, 3), { src: true })
                  .pipe(gulp.dest(paths.i18n.transpiled))
                  .pipe(jsonminify())
                  .pipe(gulp.dest(paths.i18n.build));
            } catch (e) {
               console.warn('Warning: could not merge i18n file named: ' + name + ' with core file');
               console.warn(e);
               // TODO find a way to make this synchronous:
               // copying without merging
               gulp.src(paths.i18n.source + name)
                  .pipe(gulp.dest('./' + transpileDir + '/i18n/'))
                  .pipe(jsonminify())
                  .pipe(gulp.dest(paths.i18n.source.build));
            }

            return stream;
         }));
   });

   function extendObj ( obj, src ) {
      Object.keys(src).forEach(function ( key ) {
         obj[key] = src[key];
      });
      return obj;
   }

}).call(this);
<commit_msg>Removed console.log and updated version number<commit_after>(function () {
   'use strict';
   var gulp = require('gulp'),

      fs = require('fs'),

      rename = require('gulp-rename'),

      concat = require('gulp-concat'),

      uglify = require('gulp-uglify'),

      jshint = require('gulp-jshint'),

      insert = require('gulp-insert'),

      stripDebug = require('gulp-strip-debug'),

      sourcemaps = require('gulp-sourcemaps'),

      sass = require('gulp-ruby-sass'),

      cssnano = require('gulp-cssnano'),

      htmlReplace = require('gulp-html-replace'),

      del = require('del'),

      path = require('path'),

      gulpFile = require('gulp-file'),

      foreach = require('gulp-foreach'),

      json_merger = require('json_merger'),

      jsonminify = require('gulp-jsonminify'),

      babel = require('gulp-babel'),

      jscs = require('gulp-jscs'),

      vinylfs = require('vinyl-fs');

   var projectRoot = __dirname + '/../../';

   var transpileDir = projectRoot + '/src/transpiled/';

   var buildDir = projectRoot + '/dist/';

   var bundleThirdPartyLibraries = false;

   // All file paths used in the gulp file are inside this object
   var paths = {
      js: {
         source: projectRoot + '/src/js/',
         transpiled: transpileDir + '/js/',
         build: buildDir + '/js/',
         sourceRoot: '/js/',
         coreLibraryFile: projectRoot + '/node_modules/widget-core-library/dist/core.js',
         thirdPartyLibraryFile: projectRoot + '/node_modules/third-party-dependencies/dist/thirdparty.js',
      },
      css: {
         source: projectRoot + '/src/scss/',
         transpiled: transpileDir + '/css/',
         build: buildDir + '/css/',
         sourceRoot: '../../scss/'
      },
      i18n: {
         source: projectRoot + '/src/i18n/',
         coreLibrarySource: projectRoot + '/node_modules/widget-core-library/src/i18n/',
         transpiled: transpileDir + '/i18n/',
         build: buildDir + '/i18n/'
      },
      views: {
         source: projectRoot + '/src/views/*.html',
         transpiled: transpileDir + '/js/views/'
      },
      fonts: {
         source: projectRoot + '/node_modules/widget-core-library/src/fonts/**/*',
         transpiled: transpileDir + '/fonts/',
         build: buildDir + '/fonts/'
      },
      configFiles: [
         projectRoot + '/node_modules/widget-build-tools/widget_config/gitignore',
         projectRoot + '/node_modules/widget-build-tools/widget_config/.editorconfig',
         projectRoot + '/node_modules/widget-build-tools/widget_config/.jshintrc',
         projectRoot + '/node_modules/widget-build-tools/widget_config/.jscsrc',
         projectRoot + '/node_modules/widget-build-tools/widget_config/config.rb',
         projectRoot + '/node_modules/widget-build-tools/widget_config/LICENSE',
         projectRoot + '/node_modules/widget-build-tools/widget_config/.scss-lint.yml'
      ],
      staticFiles: [
         './src/**/*',
         '!./src/js/**',
         '!./src/js/',
         '!./src/scss/**',
         '!./src/scss/',
         '!./src/i18n/**',
         '!./src/i18n/',
         '!./src/transpiled/**',
         '!./src/transpiled/'
      ]
   };

   var buildParameters;
   try {
      buildParameters = JSON.parse(fs.readFileSync('./buildparameters.json'));
   } catch (e) {
      buildParameters = {};
   }

   var coreLibConfig, widgetConfig, buildToolsConfig, dependencyCoreLibVersion, dependencyBuildToolsVersion;
   try {
      coreLibConfig = JSON.parse(fs.readFileSync('./node_modules/widget-core-library/package.json'));
      widgetConfig = JSON.parse(fs.readFileSync('./package.json'));

      buildToolsConfig = JSON.parse(fs.readFileSync('./node_modules/widget-build-tools/package.json'));

      dependencyBuildToolsVersion = widgetConfig.devDependencies['widget-build-tools'].split('#')[1];
      if (dependencyBuildToolsVersion.charAt(0) === 'v') {
         dependencyBuildToolsVersion = dependencyBuildToolsVersion.slice(1);
      }

      dependencyCoreLibVersion = widgetConfig.devDependencies['widget-core-library'].split('#')[1];
      if (dependencyCoreLibVersion.charAt(0) === 'v') {
         dependencyCoreLibVersion = dependencyCoreLibVersion.slice(1);
      }
   } catch (e) {
      throw new Error('Could not read package.json of the widget or one of its dependencies');
   }

   if (dependencyCoreLibVersion !== coreLibConfig.version) {
      throw new Error(
         'widget-core-library dependency does not match node_modules dependency version. Expected: ' +
         dependencyCoreLibVersion +
         ' got ' +
         coreLibConfig.version +
         ' \nPlease run npm install (not npm update!)');
   }

   if (dependencyBuildToolsVersion !== buildToolsConfig.version) {
      throw new Error(
         'widget-build-tools dependency does not match node_modules dependency version. Expected: ' +
         dependencyBuildToolsVersion +
         ' got ' +
         buildToolsConfig.version +
         ' \nPlease run npm install (not npm update!)');
   }

   /**
    * Copies project configuration files from the build tools into the project
    */
   gulp.task('copy-config-files', function () {
      return gulp.src(paths.configFiles)
         .pipe(rename(function ( path ) {
            // .gitignore has special handling because npm strips .gitignore files
            // when downloading dependencies
            if ( path.basename === 'gitignore' ) {
               path.basename = '.gitignore';
            }
         }))
         .pipe(vinylfs.dest(projectRoot, { overwrite: true })); // same as gulp.dest, but accepts an overwrite flag
   });

   gulp.task('clean-temp', function () {
      return del.sync(transpileDir);
   });

   /**
    * Cleans the project (deletes transpileDir and buildDir folders)
    */
   gulp.task('clean', ['clean-temp'], function () {
      return del.sync(buildDir);
   });

   /**
    * Cleans then builds
    */
   gulp.task('default', ['clean'], function () {
      return gulp.start('build');
   });

   /**
    * Same as default but bundles the third party library file with
    * the javascript file
    */
   gulp.task('default-bundle', ['clean'], function () {
      bundleThirdPartyLibraries = true;
      return gulp.start('build');
   });

   /**
    * Tasks used by 'build' to run everything in the right order
    */
   gulp.task('build2', ['copy-config-files'], function () {
      return gulp.start('build3');
   });
   gulp.task('build3', ['compile'], function () {
      return gulp.start('build4');
   });
   gulp.task('build4', ['bundle-static', 'bundle-css', 'bundle-js', 'bundle-fonts'], function () {
      return gulp.start('build5');
   });
   gulp.task('build5', ['html-replace']);

   /**
    * Full build cycle with compilling and minifying
    */
   gulp.task('build', ['build2']);

   /**
    * Replaces references inside index.html to reference the minified and concatanated
    * js and css files
    */
   gulp.task('html-replace', function () {
      var resourcePaths;
      try {
         resourcePaths = JSON.parse(fs.readFileSync('./resourcepaths.json'));
      } catch (e) {
         throw new Error('could not read resourcepaths.json');
      }
      if (resourcePaths.htmlReplace == null) {
         resourcePaths.htmlReplace = {};
      }

      var kambiAPIVersion = coreLibConfig['kambi-widget-api-version'] != null ? coreLibConfig['kambi-widget-api-version'] : '1.0.0.10';

      var kambiWidgetAPIUrl = 'https://c3-static.kambi.com/sb-mobileclient/widget-api/{{API_VERSION}}/kambi-widget-api.js'
         .replace('{{API_VERSION}}', kambiAPIVersion);

      var references = {
         js: 'js/app.min.js',
         css: 'css/app.min.css',
         'kambi-widget-api': kambiWidgetAPIUrl
      };
      if (!bundleThirdPartyLibraries) {
         references['third-party-libs'] = resourcePaths.thirdPartyLibs;
      }

      references = extendObj(
         references,
         resourcePaths.htmlReplace
      );
      return gulp.src('./src/index.html')
         .pipe(htmlReplace(references))
         .pipe(gulp.dest('./dist'));
   });

   /**
    * Compiles all scss files and places them in {transpileDir}/css/ folder
    */
   gulp.task('compile-scss', [], function () {
      return sass(paths.css.source + 'app.scss', {
            compass: true,
            style: 'expanded',
            lineComments: false,
            sourcemap: true
         })
         .pipe(sourcemaps.write('.', {
            includeContent: false,
            sourceRoot: paths.css.sourceRoot
         }))
         .pipe(gulp.dest(paths.css.transpiled));
   });

   /**
    * Compiles all js files using Babel and places them in {transpileDir} folder
    */
   gulp.task('compile-babel', [], function () {
      var sourceRootMap = function (file) {
         return '../' + path.relative(file.history[0], paths.js.source) + paths.js.sourceRoot;
      };
      return gulp.src(paths.js.source + '/**/*.js')
         .pipe(jshint('.jshintrc'))
         .pipe(jshint.reporter('default'))
         .pipe(jscs())
         .pipe(jscs.reporter())
         .pipe(sourcemaps.init())
         .pipe(babel({
            presets: ['es2015']
         }))
         .pipe(sourcemaps.write('.', {
            includeContent: false,
            sourceRoot: sourceRootMap
         }))
         .pipe(gulp.dest(paths.js.transpiled));
   });

   /**
    * Copies all static files (.html, .json, images) to transpileDir folder, i18n files are handled
    * by the compile-translations task
    */
   gulp.task('compile-static', [], function () {
      return gulp.src(paths.staticFiles)
         .pipe(gulp.dest(transpileDir));
   });

   /**
    * Transforms all .html files from /src/views into javascript files
    * that add the content of the original files as strings in global
    * names defined by the original file name
    */
   gulp.task('compile-views', [], function () {
      return gulp.src(paths.views.source)
         .pipe(foreach(function ( stream, file ) {
            var name = path.basename(file.path);
            name = name.slice(0, -5);
            return stream
               .pipe(insert.prepend('window["' + name + '-view' + '"] = `'))
               .pipe(insert.append('`;'));
         }))
         .pipe(rename(function (path) {
            path.extname = '.js';
         }))
         .pipe(babel({ // babel does the scaping of the file convertin `` to ""
            presets: ['es2015']
         }))
         .pipe(gulp.dest(paths.views.transpiled));
   });

   /**
    * Copies all fonts from widget-core-library to transpileDir
    */
   gulp.task('compile-fonts', [], function () {
      return gulp.src(paths.fonts.source)
         .pipe(gulp.dest(paths.fonts.transpiled));
   });

   /**
    * Compiles all js, scss and i18n files and place them (alongside static files) in the dist
    * folder
    */
   gulp.task('compile', [
      'compile-babel',
      'compile-scss',
      'compile-translations',
      'compile-static',
      'compile-views',
      'compile-fonts'
   ]);

   /**
    * Watches for any change in the files inside /src/ folder and recompiles them
    */
   gulp.task('watch', [], function () {
      gulp.watch(paths.js.source + '/**/*.js', ['compile-babel']);
      gulp.watch(paths.css.source + '/**/*.scss', ['compile-scss']);
      gulp.watch(paths.i18n.source + '/**/*.json', ['compile-translations']);
      gulp.watch(paths.staticFiles, ['compile-static']);
      gulp.watch(paths.views.source, ['compile-views']);
      gulp.watch(paths.fonts.source, ['compile-fonts']);
   });

   /**
    * Minifies and concatenates all css files from {transpileDir} into {buildDir}
    */
   gulp.task('bundle-css', function () {
      return gulp.src(paths.css.transpiled + '/**/*.css')
         .pipe(concat('app.css'))
         .pipe(gulp.dest(paths.css.build))
         .pipe(cssnano({
            autoprefixer: false // If true removes older browser prefixes from code
         }))
         .pipe(rename('app.min.css'))
         .pipe(gulp.dest(paths.css.build));
   });

   /**
    * Minifies and concatenates all js files from {transpileDir} into {buildDir}
    */
   gulp.task('bundle-js', function () {
      var files = [
         paths.js.coreLibraryFile,
         paths.js.transpiled + '**/*.js'
      ];
      if (bundleThirdPartyLibraries) {
         files = [paths.js.thirdPartyLibraryFile].concat(files);
      }
      return gulp.src(files)
         .pipe(concat('app.js'))
         .pipe(stripDebug())
         .pipe(gulp.dest(paths.js.build))
         .pipe(uglify())
         .pipe(rename('app.min.js'))
         .pipe(gulp.dest(paths.js.build));
   });

   /**
    * Copies all static files (.html, .json, images) to buildDir folder, i18n files are handled
    * by the compile-translations task
    */
   gulp.task('bundle-static', [], function () {
      return gulp.src(paths.staticFiles)
         .pipe(gulp.dest(buildDir));
   });

   /**
    * Copies all font files from widget-core-library to buildDir folder
    */
   gulp.task('bundle-fonts', [], function () {
      return gulp.src(paths.fonts.source)
         .pipe(gulp.dest(paths.fonts.build));
   });

   /**
    * Merges widget i18n files with cherry-picked strings from the widget-core-library
    */
   gulp.task('compile-translations', function () {
      return gulp.src(paths.i18n.source + '/**/*.json')
         .pipe(foreach(function ( stream, file ) {
            var name = path.basename(file.path);
            var filePath = paths.i18n.coreLibrarySource + name;
            var srcJson = JSON.parse(file.contents.toString());
            var selectedFromKambi = {};

            try {
               fs.statSync(filePath); // throws error if file does not exist
               var coreLibraryJson = json_merger.fromFile(filePath);

               // buildParameters.localeStrings should be an object in the following format:
               // { "keyInI18nJSON": "pathToValueInKambiI18nJSON" }
               if (buildParameters.localeStrings != null) {
                  Object.keys(buildParameters.localeStrings).forEach(function ( key ) {
                     // creates a new function that retrieves the string specified by the path in localeStrings from the localeJson
                     /* jslint evil: true */
                     selectedFromKambi[key] = new Function('json', 'return json.' + buildParameters.localeStrings[key])(coreLibraryJson);
                  });
               }

               var result = extendObj(srcJson, selectedFromKambi);
               // TODO find a way to make this synchronous:
               gulpFile(name, JSON.stringify(result, null, 3), { src: true })
                  .pipe(gulp.dest(paths.i18n.transpiled))
                  .pipe(jsonminify())
                  .pipe(gulp.dest(paths.i18n.build));
            } catch (e) {
               console.warn('Warning: could not merge i18n file named: ' + name + ' with core file');
               console.warn(e);
               // TODO find a way to make this synchronous:
               // copying without merging
               gulp.src(paths.i18n.source + name)
                  .pipe(gulp.dest('./' + transpileDir + '/i18n/'))
                  .pipe(jsonminify())
                  .pipe(gulp.dest(paths.i18n.source.build));
            }

            return stream;
         }));
   });

   function extendObj ( obj, src ) {
      Object.keys(src).forEach(function ( key ) {
         obj[key] = src[key];
      });
      return obj;
   }

}).call(this);
<|endoftext|>