<commit_before>'use strict'
var gulp = require('gulp');
var gulpTypescript = require('gulp-tsc');
var insert = require('gulp-insert');
var mocha = require('gulp-mocha');
var nodeResolve = require('rollup-plugin-node-resolve');
var rename = require('gulp-rename');
var rollup = require('rollup');
var rollupTypescript = require('rollup-plugin-typescript');
var strip = require('gulp-strip-comments');
var typescript = require('typescript');
var uglify = require('gulp-uglify');

var tests = [
    { name: 'NavigationRouting', to: 'navigationRouting.test.js' },
    { name: 'StateConfig', to: 'stateConfig.test.js' },
    { name: 'Navigation', to: 'navigation.test.js' },
    { name: 'NavigationData', to: 'navigationData.test.js' },
    { name: 'FluentNavigation', to: 'fluentNavigation.test.js' },
    { name: 'NavigationLink', to: 'navigationLink.test.js', folder: 'React', ext: 'tsx' },
    { name: 'NavigationBackLink', to: 'navigationBackLink.test.js', folder: 'React', ext: 'tsx' },
    { name: 'RefreshLink', to: 'refreshLink.test.js', folder: 'React', ext: 'tsx' }
];
function rollupTestTask(name, file, to) {
    return rollup.rollup({
        input: file,
        external: ['assert', 'react', 'react-dom', 'react-dom/test-utils', 'jsdom' , 'tslib'],
        plugins: [
            rollupTypescript({
                typescript: typescript,
                baseUrl: '.',
                paths: {
                    navigation: ['Navigation/src/Navigation'],
                    'navigation-react': ['NavigationReact/src/NavigationReact']
                },
                importHelpers: true,
                target: 'es3',
                module: 'es6',
                jsx: 'react'
            })
        ]
    }).then((bundle) => (
        bundle.write({
            format: 'cjs',
            file: to
        })
    ));
}
function testTask(file) {
    return gulp.src(file)
        .pipe(mocha({ reporter: 'progress' }));
}
var testTasks = tests.reduce((tasks, test) => {
    var folder = './Navigation' + (test.folder || '') + '/test/';
    var file = folder + test.name + 'Test.' + (test.ext || 'ts');
    var to = './build/dist/' + test.to;
    gulp.task('RollupTest' + test.name, () => rollupTestTask(test.name, file, to));
    gulp.task('Test' + test.name, ['RollupTest' + test.name], () => testTask(to));
    tasks.push('Test' + test.name);
    return tasks;
}, []);
gulp.task('test', testTasks);

var items = [
    require('./build/npm/navigation/package.json'),
    Object.assign({ globals: { navigation: 'Navigation', react: 'React',
            'react-dom': 'ReactDOM' } },
        require('./build/npm/navigation-react/package.json'),
        require('./NavigationReact/src/tsconfig.json')),
    Object.assign({ globals: { knockout: 'ko' } },
        require('./build/npm/navigation-knockout/package.json')),
    Object.assign({ globals: { angular: 'angular' } },
        require('./build/npm/navigation-angular/package.json')),
    Object.assign({ globals: { '@cycle/dom': 'CycleDOM', rx: 'Rx' } },
        require('./build/npm/navigation-cycle/package.json')),
    Object.assign({ globals: { navigation: 'Navigation',
            'navigation-react': 'NavigationReact', react: 'React' } },
        require('./build/npm/navigation-react-mobile/package.json'),
        require('./NavigationReactMobile/src/tsconfig.json')),
    Object.assign({ globals: { react: 'React', 'react-native': 'ReactNative',
            'd3-interpolate': 'd3', 'd3-ease': 'd3' } },
        require('./build/npm/navigation-react-native/package.json'),
        require('./NavigationReactNative/src/tsconfig.json')),
];
function rollupTask(name, file, to, globals) {
    return rollup.rollup({
        input: file,
        external: Object.keys(globals),
        plugins: [
            rollupTypescript({
                typescript: typescript,
                importHelpers: true,
                target: 'es3',
                module: 'es6',
                jsx: 'react'
            }),
            nodeResolve({ jsnext: true, main: true })
        ]
    }).then((bundle) => (
        bundle.write({
            format: 'iife',
            name,
            globals,
            file: './build/dist/' + to
        })
    ));
}
function buildTask(file, details) {
    var info = `/**
 * ${details.name} v${details.version}
 * (c) Graham Mendick - ${details.homepage}
 * License: ${details.license}
 */
`;
    return gulp.src('./build/dist/' + file)
        .pipe(strip())
        .pipe(insert.prepend(info))
        .pipe(gulp.dest('./build/dist'))
        .pipe(rename(file.replace(/js$/, 'min.js')))
        .pipe(uglify())
        .pipe(insert.prepend(info))
        .pipe(gulp.dest('./build/dist'));
}
function packageTask(name, file, details) {
    return gulp.src(file)
        .pipe(gulpTypescript(details.compilerOptions))
        .pipe(gulp.dest('./build/npm/' + name + '/lib'));
}
var itemTasks = items.reduce((tasks, item) => {
    var packageName = item.name;
    var upperName = packageName.replace(/\b./g, (val) => val.toUpperCase());
    var name = upperName.replace(/-/g, '');
    var tsFrom = './' + name + '/src/' + name + '.ts';
    var jsTo = packageName.replace(/-/g, '.') + '.js';
    item.name = upperName.replace(/-/g, ' ');
    gulp.task('Rollup' + name, () => rollupTask(name, tsFrom, jsTo, item.globals || {}));
    gulp.task('Build' + name, ['Rollup' + name], () => buildTask(jsTo, item));
    gulp.task('Package' + name, () => packageTask(packageName, tsFrom, item));
    tasks.buildTasks.push('Build' + name);
    tasks.packageTasks.push('Package' + name);
    return tasks;
}, { buildTasks: [], packageTasks: [] });
gulp.task('build', itemTasks.buildTasks);
gulp.task('package', itemTasks.packageTasks);
<commit_msg>Passed tasks full file name<commit_after>'use strict'
var gulp = require('gulp');
var gulpTypescript = require('gulp-tsc');
var insert = require('gulp-insert');
var mocha = require('gulp-mocha');
var nodeResolve = require('rollup-plugin-node-resolve');
var rename = require('gulp-rename');
var rollup = require('rollup');
var rollupTypescript = require('rollup-plugin-typescript');
var strip = require('gulp-strip-comments');
var typescript = require('typescript');
var uglify = require('gulp-uglify');

var tests = [
    { name: 'NavigationRouting', to: 'navigationRouting.test.js' },
    { name: 'StateConfig', to: 'stateConfig.test.js' },
    { name: 'Navigation', to: 'navigation.test.js' },
    { name: 'NavigationData', to: 'navigationData.test.js' },
    { name: 'FluentNavigation', to: 'fluentNavigation.test.js' },
    { name: 'NavigationLink', to: 'navigationLink.test.js', folder: 'React', ext: 'tsx' },
    { name: 'NavigationBackLink', to: 'navigationBackLink.test.js', folder: 'React', ext: 'tsx' },
    { name: 'RefreshLink', to: 'refreshLink.test.js', folder: 'React', ext: 'tsx' }
];
function rollupTestTask(name, input, file) {
    return rollup.rollup({
        input,
        external: ['assert', 'react', 'react-dom', 'react-dom/test-utils', 'jsdom' , 'tslib'],
        plugins: [
            rollupTypescript({
                typescript: typescript,
                baseUrl: '.',
                paths: {
                    navigation: ['Navigation/src/Navigation'],
                    'navigation-react': ['NavigationReact/src/NavigationReact']
                },
                importHelpers: true,
                target: 'es3',
                module: 'es6',
                jsx: 'react'
            })
        ]
    }).then((bundle) => (
        bundle.write({
            format: 'cjs',
            file
        })
    ));
}
function testTask(file) {
    return gulp.src(file)
        .pipe(mocha({ reporter: 'progress' }));
}
var testTasks = tests.reduce((tasks, test) => {
    var folder = './Navigation' + (test.folder || '') + '/test/';
    var file = folder + test.name + 'Test.' + (test.ext || 'ts');
    var to = './build/dist/' + test.to;
    gulp.task('RollupTest' + test.name, () => rollupTestTask(test.name, file, to));
    gulp.task('Test' + test.name, ['RollupTest' + test.name], () => testTask(to));
    tasks.push('Test' + test.name);
    return tasks;
}, []);
gulp.task('test', testTasks);

var items = [
    require('./build/npm/navigation/package.json'),
    Object.assign({ globals: { navigation: 'Navigation', react: 'React',
            'react-dom': 'ReactDOM' } },
        require('./build/npm/navigation-react/package.json'),
        require('./NavigationReact/src/tsconfig.json')),
    Object.assign({ globals: { knockout: 'ko' } },
        require('./build/npm/navigation-knockout/package.json')),
    Object.assign({ globals: { angular: 'angular' } },
        require('./build/npm/navigation-angular/package.json')),
    Object.assign({ globals: { '@cycle/dom': 'CycleDOM', rx: 'Rx' } },
        require('./build/npm/navigation-cycle/package.json')),
    Object.assign({ globals: { navigation: 'Navigation',
            'navigation-react': 'NavigationReact', react: 'React' } },
        require('./build/npm/navigation-react-mobile/package.json'),
        require('./NavigationReactMobile/src/tsconfig.json')),
    Object.assign({ globals: { react: 'React', 'react-native': 'ReactNative',
            'd3-interpolate': 'd3', 'd3-ease': 'd3' } },
        require('./build/npm/navigation-react-native/package.json'),
        require('./NavigationReactNative/src/tsconfig.json')),
];
function rollupTask(name, input, file, globals) {
    return rollup.rollup({
        input,
        external: Object.keys(globals),
        plugins: [
            rollupTypescript({
                typescript: typescript,
                importHelpers: true,
                target: 'es3',
                module: 'es6',
                jsx: 'react'
            }),
            nodeResolve({ jsnext: true, main: true })
        ]
    }).then((bundle) => (
        bundle.write({
            format: 'iife',
            name,
            globals,
            file
        })
    ));
}
function buildTask(file, details) {
    var info = `/**
 * ${details.name} v${details.version}
 * (c) Graham Mendick - ${details.homepage}
 * License: ${details.license}
 */
`;
    return gulp.src(file)
        .pipe(strip())
        .pipe(insert.prepend(info))
        .pipe(gulp.dest('./build/dist'))
        .pipe(rename(file.replace(/js$/, 'min.js')))
        .pipe(uglify())
        .pipe(insert.prepend(info))
        .pipe(gulp.dest('.'));
}
function packageTask(name, file, details) {
    return gulp.src(file)
        .pipe(gulpTypescript(details.compilerOptions))
        .pipe(gulp.dest('./build/npm/' + name + '/lib'));
}
var itemTasks = items.reduce((tasks, item) => {
    var packageName = item.name;
    var upperName = packageName.replace(/\b./g, (val) => val.toUpperCase());
    var name = upperName.replace(/-/g, '');
    var tsFrom = './' + name + '/src/' + name + '.ts';
    var jsTo = './build/dist/' + packageName.replace(/-/g, '.') + '.js';
    item.name = upperName.replace(/-/g, ' ');
    gulp.task('Rollup' + name, () => rollupTask(name, tsFrom, jsTo, item.globals || {}));
    gulp.task('Build' + name, ['Rollup' + name], () => buildTask(jsTo, item));
    gulp.task('Package' + name, () => packageTask(packageName, tsFrom, item));
    tasks.buildTasks.push('Build' + name);
    tasks.packageTasks.push('Package' + name);
    return tasks;
}, { buildTasks: [], packageTasks: [] });
gulp.task('build', itemTasks.buildTasks);
gulp.task('package', itemTasks.packageTasks);
<|endoftext|>


<commit_before>var
  gulp        = require('gulp'),
  $           = require('gulp-load-plugins')(),
  runSequence = require('run-sequence'),
  browserSync = require('browser-sync'),
  del         = require('del'),

  AUTOPREFIXER_BROWSERS = [
    'ie >= 9',
    'ff >= 30',
    'chrome >= 40',
    'safari >= 7',
    'opera >= 29',
    'ie_mob >= 10',
    'ios >= 7',
    'android >= 4.0',
  ];

gulp.task('eslint', function() {
  return gulp.src('app/scripts/**/*.js')
    .pipe(browserSync.reload({stream: true, once: true}))
    .pipe($.eslint())
    .pipe($.eslint.format())
    .pipe($.if(!browserSync.active, $.eslint.failOnError()));
});

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

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

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

  return gulp.src([
    'app/styles/**/*.scss',
    'app/styles/**/*.css'
  ])
    .pipe($.plumber())
    // .pipe($.changed('.tmp/styles', {extension: '.css'}))
    .pipe($.sourcemaps.init())
    .pipe($.sass.sync({
      precision: 3,
    }))
    .pipe($.autoprefixer(AUTOPREFIXER_BROWSERS))
    .pipe(gulp.dest('.tmp/styles'))
    .pipe($.if('*.css', $.minifyCss()))
    .pipe($.sourcemaps.write())
    .pipe(gulp.dest('dist/styles'));
});

gulp.task('scripts', function() {
  return gulp.src(['app/scripts/**/*.js'])
    .pipe($.plumber())
    .pipe($.babel())
    .pipe(gulp.dest('.tmp/scripts'))
    .pipe($.uglify({preserveComments: 'some'}))
    .pipe(gulp.dest('dist/scripts'));
});

gulp.task('html', function() {
  var assets = $.useref.assets({searchPath: '{.tmp,app}'});

  return gulp.src('app/**/*.html')
    .pipe(assets)
    .pipe($.if('*.css', $.minifyCss()))
    .pipe(assets.restore())
    .pipe($.useref())
    .pipe($.if('*.html', $.minifyHtml()))
    .pipe(gulp.dest('dist'));
});

gulp.task('clean', function(){ del(['.tmp', 'dist/*', '!dist/.git'], {dot: true})});

gulp.task('watch',['styles', 'scripts'], function() {
  browserSync({
    notify: false,
    https: false,
    server: ['.tmp', 'app']
  });

  gulp.watch(['app/**/*.html'], browserSync.reload);
  gulp.watch(['app/styles/**/*.{scss,css}'], ['styles', browserSync.reload]);
  gulp.watch(['app/scripts/**/*.js'], ['scripts', 'eslint']);
  gulp.watch(['app/images/**/*'], browserSync.reload);
});

gulp.task('build', ['clean'], function(cb) {
  runSequence(
    'styles',
    'scripts',
    ['eslint', 'html', 'images', 'fonts'],
    cb
  );
});

gulp.task('default', ['watch']);

<commit_msg>ビルドエラーを修正<commit_after>var
  gulp        = require('gulp'),
  $           = require('gulp-load-plugins')(),
  runSequence = require('run-sequence'),
  browserSync = require('browser-sync'),
  del         = require('del'),

  AUTOPREFIXER_BROWSERS = [
    'ie >= 9',
    'ff >= 30',
    'chrome >= 40',
    'safari >= 7',
    'opera >= 29',
    'ie_mob >= 10',
    'ios >= 7',
    'android >= 4.0',
  ];

gulp.task('eslint', function() {
  return gulp.src('app/scripts/**/*.js')
    .pipe(browserSync.reload({stream: true, once: true}))
    .pipe($.eslint())
    .pipe($.eslint.format())
    .pipe($.if(!browserSync.active, $.eslint.failOnError()));
});

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

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

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

  return gulp.src([
    'app/styles/**/*.scss',
    'app/styles/**/*.css'
  ])
    .pipe($.plumber())
    // .pipe($.changed('.tmp/styles', {extension: '.css'}))
    .pipe($.sourcemaps.init())
    .pipe($.sass.sync({
      precision: 3,
    }))
    .pipe($.autoprefixer(AUTOPREFIXER_BROWSERS))
    .pipe($.sourcemaps.write())
    .pipe($.if(browserSync.active, gulp.dest('.tmp/styles')))
    .pipe($.if(!browserSync.active, $.minifyCss()))
    .pipe($.if(!browserSync.active, gulp.dest('dist/styles')));
});

gulp.task('scripts', function() {
  return gulp.src(['app/scripts/**/*.js'])
    .pipe($.plumber())
    .pipe($.babel())
    .pipe($.if(browserSync.active, gulp.dest('.tmp/scripts')))
    .pipe($.if(!browserSync.active, $.uglify({preserveComments: 'some'})))
    .pipe($.if(!browserSync.active, gulp.dest('dist/scripts')));
});

gulp.task('html', function() {
  var assets = $.useref.assets({searchPath: '{.tmp,app}'});

  return gulp.src('app/**/*.html')
    .pipe(assets)
    .pipe($.if('*.css', $.minifyCss()))
    .pipe(assets.restore())
    .pipe($.useref())
    .pipe($.if('*.html', $.minifyHtml()))
    .pipe(gulp.dest('dist'));
});

gulp.task('clean', function(){
  del.sync(
    ['.tmp', 'dist/*', '!dist/.git'],
    {dot: true}
  );
});

gulp.task('watch',['styles', 'scripts'], function() {
  browserSync({
    notify: false,
    https: false,
    server: ['.tmp', 'app']
  });

  gulp.watch(['app/**/*.html'], browserSync.reload);
  gulp.watch(['app/styles/**/*.{scss,css}'], ['styles', browserSync.reload]);
  gulp.watch(['app/scripts/**/*.js'], ['scripts', 'eslint']);
  gulp.watch(['app/images/**/*'], browserSync.reload);
});

gulp.task('build', ['clean'], function(cb) {
  runSequence(
    'styles',
    'scripts',
    ['eslint', 'html', 'images', 'fonts'],
    cb
  );
});

gulp.task('default', ['watch']);

<|endoftext|>


<commit_before>/**
 * @license
 * Copyright 2014 The Lovefield Project Authors. 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.
 */
var gulp = /** @type {{
    task: function(string, (!Array|!Function), !Function=),
    src: !Function}} */ (require('gulp'));
var gjslint = /** @type {!Function} */ (require('gulp-gjslint'));
var pathMod = require('path');
var chalk = /** @type {{green: !Function, red: !Function}} */ (
    require('chalk'));
var nopt = /** @type {!Function} */ (require('nopt'));

var builder = /** @type {{
    buildLib: !Function,
    buildTest: !Function,
    buildAllTests: !Function}} */ (
        require(pathMod.resolve(
            pathMod.join(__dirname, 'tools/builder.js'))));
var runner = /** @type {{
    runJsUnitTests: function(?string, string):!IThenable,
    runSpacTests: function():!IThenable,
    runJsPerfTests: function(string=):!IThenable}} */ (
        require(pathMod.resolve(
            pathMod.join(__dirname, 'tools/run_test.js'))));
var testServer = /** @type {{
    runUnitTestServer: function(number):!IThenable,
    runPerfTestServer: function(number):!IThenable,
    stopServer: !Function }} */ (
        require(pathMod.resolve(
            pathMod.join(__dirname, 'tools/run_test_server.js'))));

var log = console['log'];

gulp.task('default', function() {
  log('Usage: ');
  log('  gulp build --target=<all|lib|tests> --mode=<opt|debug>:');
  log('      Compile source files using Closure compiler');
  log('  gulp debug [--target=<tests|perf>] [--port=<number>]:');
  log('      Start a debug server (default is test at port 8000)');
  log('  gulp lint: Lint against source files');
  log('  gulp test --target=spac: Run SPAC tests');
  log('  gulp test --target=perf [--browser=<chrome|firefox>]:');
  log('      Run perf tests using webdriver (need separate install).');
  log('  gulp test --target=tests [--filter=<test name> ' +
      '--browser=<chrome|firefox>]:');
  log('      Run unit tests using webdriver (need separate install).');
});

gulp.task('lint', function() {
  return gulp.src([
    'src/**/*.js',
    'tests/**/*.js',
    'testing/**/*.js',
  ]).pipe(gjslint()).
      pipe(gjslint['reporter']('console'), {fail: true});
});

gulp.task('build', function() {
  var knownOpts = {
    'mode': [String, null],
    'target': [String, null]
  };
  var options = nopt(knownOpts);

  if (options.target == 'all' || options.target == null) {
    // TODO(dpapad): Build also the lib here.
    return builder.buildAllTests();
  } else if (options.target == 'lib') {
    return builder.buildLib(options);
  } else {
    return builder.buildTest(options);
  }
});

gulp.task('debug', function() {
  var knownOpts = {
    'target': [String, null],
    'port': [Number, null]
  };

  var options = nopt(knownOpts);
  options.target = options.target || 'tests';
  var port = options.port || 8000;

  // The test server cannot callback. It is terminated by Ctrl-C.
  if (options.target == 'perf') {
    testServer.runPerfTestServer(port);
  } else if (options.target != 'spac') {
    testServer.runUnitTestServer(port);
  }
});

/**
 * TODO(dpapad):
 *  1) Accept command line param to run a specific browser, run all browsers by
 *     default.
 *  2) Gather the output of the tests and display something useful (summary).
 */
gulp.task('test', ['debug'], function() {
  var knownOpts = {
    'browser': [String, null],
    'filter': [String, null],
    'target': [String]
  };
  var options = nopt(knownOpts);
  options.browser = options.browser || 'chrome';

  var whenTestsDone = null;
  if (options.target == 'perf') {
    // Run only perf regression tests and dump output in the console.
    whenTestsDone = runner.runJsPerfTests(options.browser).then(
        function(perfData) {
          log(JSON.stringify(perfData, null, 2));
          testServer.stopServer();
          process.exit();
        });
  } else if (options.target == 'spac') {
    // Run only SPAC.
    whenTestsDone = runner.runSpacTests();
  } else {
    // Run only JSUnit tests.
    whenTestsDone =
        runner.runJsUnitTests(options.filter, options.browser).then(
            function(results) {
              var failedCount = results.reduce(function(prev, item) {
                return prev + item['pass'] ? 0 : 1;
              }, 0);
              log(results.length + ' tests, ' + failedCount + ' failure(s).');
              log('JSUnit tests: ', failedCount > 0 ? chalk.red('FAILED') :
                  chalk.green('PASSED'));
              testServer.stopServer();
              process.exit();
            });
  }
  return whenTestsDone;
});
<commit_msg>Fix a bug calculating test summary. Remove obsolete comments in gulp file. ------------- Created by MOE: http://code.google.com/p/moe-java MOE_MIGRATED_REVID=100433931<commit_after>/**
 * @license
 * Copyright 2014 The Lovefield Project Authors. 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.
 */
var gulp = /** @type {{
    task: function(string, (!Array|!Function), !Function=),
    src: !Function}} */ (require('gulp'));
var gjslint = /** @type {!Function} */ (require('gulp-gjslint'));
var pathMod = require('path');
var chalk = /** @type {{green: !Function, red: !Function}} */ (
    require('chalk'));
var nopt = /** @type {!Function} */ (require('nopt'));

var builder = /** @type {{
    buildLib: !Function,
    buildTest: !Function,
    buildAllTests: !Function}} */ (
        require(pathMod.resolve(
            pathMod.join(__dirname, 'tools/builder.js'))));
var runner = /** @type {{
    runJsUnitTests: function(?string, string):!IThenable,
    runSpacTests: function():!IThenable,
    runJsPerfTests: function(string=):!IThenable}} */ (
        require(pathMod.resolve(
            pathMod.join(__dirname, 'tools/run_test.js'))));
var testServer = /** @type {{
    runUnitTestServer: function(number):!IThenable,
    runPerfTestServer: function(number):!IThenable,
    stopServer: !Function }} */ (
        require(pathMod.resolve(
            pathMod.join(__dirname, 'tools/run_test_server.js'))));

var log = console['log'];

gulp.task('default', function() {
  log('Usage: ');
  log('  gulp build --target=<all|lib|tests> --mode=<opt|debug>:');
  log('      Compile source files using Closure compiler');
  log('  gulp debug [--target=<tests|perf>] [--port=<number>]:');
  log('      Start a debug server (default is test at port 8000)');
  log('  gulp lint: Lint against source files');
  log('  gulp test --target=spac: Run SPAC tests');
  log('  gulp test --target=perf [--browser=<chrome|firefox>]:');
  log('      Run perf tests using webdriver (need separate install).');
  log('  gulp test --target=tests [--filter=<test name> ' +
      '--browser=<chrome|firefox>]:');
  log('      Run unit tests using webdriver (need separate install).');
});

gulp.task('lint', function() {
  return gulp.src([
    'src/**/*.js',
    'tests/**/*.js',
    'testing/**/*.js',
  ]).pipe(gjslint()).
      pipe(gjslint['reporter']('console'), {fail: true});
});

gulp.task('build', function() {
  var knownOpts = {
    'mode': [String, null],
    'target': [String, null]
  };
  var options = nopt(knownOpts);

  if (options.target == 'all' || options.target == null) {
    // TODO(dpapad): Build also the lib here.
    return builder.buildAllTests();
  } else if (options.target == 'lib') {
    return builder.buildLib(options);
  } else {
    return builder.buildTest(options);
  }
});

gulp.task('debug', function() {
  var knownOpts = {
    'target': [String, null],
    'port': [Number, null]
  };

  var options = nopt(knownOpts);
  options.target = options.target || 'tests';
  var port = options.port || 8000;

  // The test server cannot callback. It is terminated by Ctrl-C.
  if (options.target == 'perf') {
    testServer.runPerfTestServer(port);
  } else if (options.target != 'spac') {
    testServer.runUnitTestServer(port);
  }
});

gulp.task('test', ['debug'], function() {
  var knownOpts = {
    'browser': [String, null],
    'filter': [String, null],
    'target': [String]
  };
  var options = nopt(knownOpts);
  options.browser = options.browser || 'chrome';

  var whenTestsDone = null;
  if (options.target == 'perf') {
    // Run only perf regression tests and dump output in the console.
    whenTestsDone = runner.runJsPerfTests(options.browser).then(
        function(perfData) {
          log(JSON.stringify(perfData, null, 2));
          testServer.stopServer();
          process.exit();
        });
  } else if (options.target == 'spac') {
    // Run only SPAC.
    whenTestsDone = runner.runSpacTests();
  } else {
    // Run only JSUnit tests.
    whenTestsDone =
        runner.runJsUnitTests(options.filter, options.browser).then(
            function(results) {
              var failedCount = results.reduce(function(prev, item) {
                return prev + (item['pass'] ? 0 : 1);
              }, 0);
              log(results.length + ' tests, ' + failedCount + ' failure(s).');
              log('JSUnit tests: ', failedCount > 0 ? chalk.red('FAILED') :
                  chalk.green('PASSED'));
              testServer.stopServer();
              process.exit();
            });
  }
  return whenTestsDone;
});
<|endoftext|>


<commit_before>/**
 * CouchDB base class/resource definition.
 * This file should be inherited by all CouchDB models that want to leverage
 * CouchDB's power in rocket.
 */

var crypto = require('crypto')
  , _ = require('underscore')
  , lingo = require('lingo')
  , cradle = require('cradle')
  , async = require('async')
  ;

var oo = require('../utils/oo')
  , namespace = require('../utils/namespace')
  , BaseResource = require('./base_resource')
  ;

/******************************************************************************
 * CONSTANTS
 */

var ROCKET_NAMESPACE = 'rocket';

/******************************************************************************
 * Default connection parameters
 */
CouchDBResource.connection = {
    host: 'localhost'
  , port: 5984
  , options: {
      raw: true
    , cache: false
    , auth: null
    }
  };

/******************************************************************************
 * Default _design documents                                     *** SYNCD ***
 */
CouchDBResource.ddocs = [
    {
      _id: '_design/rocket'
    , lists: {}
    , shows: {}
    , updates: {
        in_place: function(doc, req) {
          var oo  = require('rocket/oo')
            , ret
            ;

          if(doc !== null) {
            oo.__extends(doc, req.query, { overwrite: true });
            ret = doc;
          }else{
            ret = req.query;
          }

          return [ret, JSON.stringify(ret)];
        }
      }
    , validate_doc_update: function(newDoc, oldDoc, userCtx) {

        if(newDoc._deleted
        || typeof newDoc.doc_type === 'undefined'
        || newDoc.doc_type === null
        || newDoc.doc_type === ''
        ){
          return;
        }

        var schema = require('rocket/schema/' + newDoc.doc_type);

        for(var member in schema) {

          if(typeof schema[member] !== 'undefined'
          && schema[member] !== null) {

            var validator;
            var optional;
            var prefix;

            if(typeof schema[member] === 'string') {

              validator = require('rocket/validators/' + schema[member]) || null;

            }else if(typeof schema[member] === 'object') {

              alias = schema[member].alias;
              prefix = schema[member].prefix;
              optional = schema[member].optional;
              validator = (schema[member].validate ? require('rocket/validators/' + schema[member].validate) : null);

            }

            var value = newDoc[member];

            if(typeof value !== 'undefined'
            && value !== null) {
              if(alias) {
                continue;
              }

              if(prefix) {
                if(value.substr(0, prefix.length) !== prefix) {
                  throw({ invalid: member + '[' + value + '] must have prefix [' + prefix + ']' + '\n' + JSON.stringify(newDoc) });
                }else{
                  value = value.substr(prefix.length);
                }
              }

              if(validator) {
                validator(member, value);
              }else{
                continue;
              }
            }else if(optional || alias){
              continue;
            }else{
              throw({ invalid: member + ' can\'t be missing or null' });
            }
          }
        }
      }
    , views: {
       all: {
          map: function(doc) { emit(doc._id, doc); }
        }
      }
    }
  ];

/******************************************************************************
 * Default _security document                                    *** SYNCD ***
 */
CouchDBResource._security = {
    admins: {
        names: ["admin"]
      , roles: []
      }
  , readers: {
        names: ["admin"]
      , roles: []
      }
  };

/******************************************************************************
 * Utils functions
 */
function setProperties(dst, src, synced) {

  var synced = typeof synced !== 'undefined' ? synced : true;

  if(! dst.synced)  { Object.defineProperty(dst, 'synced', {value: {}}); }
  if(! dst.values)    { Object.defineProperty(dst, 'values', {value: {}}); }

  function createSetter(prop) {
    return function(v) {
      dst.synced[prop] = dst.synced[prop] && dst.values[prop] === v;
      dst.values[prop] = v;
    }
  }

  function createGetter(prop) {
    return function() { return dst.values[prop] };
  }

  for(var prop in src) {

    if( dst.propertyIsEnumerable(prop) === false) { continue; }

    var val = src[prop];
    delete src[prop];
    Object.defineProperty(dst, prop, { enumerable: true,  configurable: true, get: createGetter(prop), set: createSetter(prop) });
    dst.synced[prop] = synced;
    dst.values[prop] = val;
  }
}

function updateCache(obj, newValues) {
  obj.__db.cache.store[obj._id].document = newValues;
  obj.__db.cache.store[obj._id].attime = Date.now();
}

function timestamp(obj) {

  var current_time = Date.now();

  if(typeof obj.creation_date === 'undefined'
  || obj.creation_date === null
  ){
    obj.creation_date = current_time;
  }

  obj.modification_date = current_time;
}

function set_doc_type(obj, doc_type) {
  if(typeof obj.doc_type === 'undefined'
  || obj.doc_type === null
  || obj.doc_type === ''
  || !obj.propertyIsEnumerable('doc_type')
  || obj.doc_type !== doc_type
  ){
    obj.doc_type = doc_type;
  }
}

function oo_cb_wrapper(cons, cb) {
  return function(err, res) {

    var objects = [];

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

    if(res) {
      if(Array.isArray(res)){
        cons = (Array.isArray(cons) ? cons : [cons]);

        for(var i = 0, ii = res.length; i < ii; i++) {
          objects.push(new cons[i % cons.length](res[i]));
        }
        cb(err, objects);
      }else{
        //single object...
        cb(err, new cons(res));
      }
    }else{
      cb(err, res); return;
    }

  };
}

/******************************************************************************
 * Resource Prototype Functions (used to create models)
 */
CouchDBResource.prototype = {
    save: function save_CouchDBResourceInstance(callback) {
      var that = this
      ;

      timestamp(this);
      set_doc_type(this, this.doc_type);

      this.__db.save(this._id, this._rev, this, function(err,res) {
        if(err){
          callback(err);
        }else{
          setProperties(that, that);
          callback(null, res);
        }
      });
    }
  , update: function update_CouchDBResourceInstance(callback) {
      var modz = {}
        , that = this
        ;
      console.log('update');
      timestamp(this);
      set_doc_type(this, this.doc_type);

      for(var k in this) {
        if(this.propertyIsEnumerable(k) === false) {
          continue;
        }

        if(! this.synced[k]) {
          modz[k] = this[k];
        }
      }

      if(modz !== {}) {
        this.__db.update('rocket/in_place', this._id, modz, function(err){
          if(err){
            callback(err);
          }else{
            setProperties(that, that);
            updateCache(that, that.values);
            callback.apply(that, Array.prototype.slice.apply(arguments));
          }
        });
      }else{
        callback(null, '');
      }
    }
  , destroy: function destroy_CouchDBResourceInstance(callback) {
      this.__db.remove(this._id, function(err) { callback(err); });
    }
  , reload: function reload_CouchDBResourceInstance(callback) {
      var that = this;

      this.__db.get(this._id, function(err, doc) {
        if(err) {
          callback(err);
        }else{

          setProperties(that, doc);
          callback(null, that);
        }
      });

    }
  , exists: function exists_CouchDBResourceInstance() {}
  };

/******************************************************************************
 * Resource Factory/Constructor Functions
 */
var factoryFunctions = {
    initialize: function initialize_CouchDBResource(model_name, callback) {
      var that = this
        , doc_type = namespace.extractName(model_name.toLowerCase(), { suffix: '_document' })
        ;

      //Initialize connection object
      that.__connection = new cradle.Connection(
          that.connection.host
        , that.connection.port
        , that.connection.options
        );

      //Infer DB name from file name unless specified
      if(typeof that.db_name !== 'undefined' && that.db_name !== null){
        that.__db_name = that.db_name;
      }else{
        that.__db_name = lingo.en.pluralize(doc_type);
      }

      //setup db object
      that.__db = that.__connection.database(that.__db_name);
      that.prototype.__db  = that.__db;

      that.prototype.doc_type  = doc_type;

      //Create db if it doesn't exists. Harmless otherwise.
      that.__db.create();

      //prepare ddoc if it exists
      if(that.ddoc) {
        that.ddoc._id = that.ddoc._id || '_design/' + doc_type;
        that.ddocs.push(that.ddoc);
      }

      async.parallel([
        function(callback) { async.forEach(that.ddocs, syncDoc, callback); }
      , function(callback) { that.__db._save('_security', false, that._security, callback); }
      ], callback);

      function fctToString(obj) {
       for(var key in obj) {
          if(typeof obj[key] === 'function') {
            obj[key] = obj[key].toString();
          }else if(typeof obj[key] === 'object' && obj[key] !== null) {
            arguments.callee(obj[key]);
          }
        }
      }

      function syncDoc(docObj, callback) {

        //create the `rocket` namespace in the design doc
        docObj[ROCKET_NAMESPACE] = {};

        //add the validators to the design doc
        docObj[ROCKET_NAMESPACE].validators = oo.__extends({}, that.validators);

        //add the schema to the design doc
        docObj[ROCKET_NAMESPACE].schema = {};
        docObj[ROCKET_NAMESPACE].schema[doc_type] = 'module.exports = ' + JSON.stringify(that.schema);

        //convert all functions to strings
        fctToString(docObj);

        //make all validators available through commonJS' `require`
        for(var f in docObj[ROCKET_NAMESPACE].validators) {
          docObj[ROCKET_NAMESPACE].validators[f] = 'module.exports = ' + docObj[ROCKET_NAMESPACE].validators[f];
        }

        //make all the oo functions available through commonJS' `require`
        docObj[ROCKET_NAMESPACE].oo = fs.readFileSync(path.join(__dirname, '../utils/oo.js'), 'utf8');

        that.__db.get(docObj._id, checkAndUpdate);

        function checkAndUpdate(err, doc) {

          doc = doc || {};

          var oldDocJSON = JSON.stringify(doc);

          //extend the DB doc with the current doc
          oo.__deepExtends(doc, docObj, {overwrite: true});

          //docObj to a JSON string
          var docJSON = JSON.stringify(doc);

          if(err) {
            if(err.error === 'not_found'){
              that.__db.save(doc._id, doc, callback);
            }else{
              console.log(('xxx [CouchDBResource] ERROR id: ' + doc._id + ' ' + require('util').inspect(err)).red);
              callback(err);
            }
          }else{

            if(oldDocJSON !== docJSON) {
              that.__db.save(doc._id, doc._rev, doc, callback);
            }else{
              callback(null);
            }
          }
        };
      };
    }
  , create: function create_CouchDBResource(obj, callback) {
      var constructor = this.prototype.constructor
        , obj = (obj instanceof constructor ? obj : new constructor(obj))
        ;

      obj.save(callback);
    }
  , save: function save_CouchDBResource(obj, callback) {
      var constructor = this.prototype.constructor
        , obj = (obj instanceof constructor ? obj : new constructor(obj))
        ;

      obj.save(callback);
    }
  , get: function get_CouchDBResource(_id, callback) {
      this.__db.get(_id, oo_cb_wrapper(this.prototype.constructor, callback));
    }
  , destroy: function destroy_CouchDBResource(_id, callback) {
      this.__db.remove(_id, callback);
    }
  , all: function all_CouchDBResource(args) {
      var args_array = Array.prototype.slice.call(args)
        ;

      args_array.unshift('rocket/all');

      this.view(args_array);
    }
  , view: function view_CouchDBResource() {
      var args_array    = Array.prototype.slice.call(arguments)
        , view          = args_array.shift()
        , params        = (
                             typeof args_array[0] === 'object'
                          && args_array[0]
                          && ! Array.isArray(args_array[0])
                          ? args_array.shift()
                          : {}
                          )
        , constructors  = (
                             typeof args_array[0] === 'object'
                          && args_array[0]
                          && Array.isArray(args_array[0])
                          ? args_array.shift()
                          : this.prototype.constructor
                          )
        , callback      = args_array.shift()
        ;

      //add doc_type argument to filter out other docs
      params.doc_type = this.prototype.doc_type;

      //call with our callback to objectify the result
      this.__db.view.apply(this.__db, view, params, oo_cb_wrapper(constructors, callback));
    }
  };

oo.__extends(CouchDBResource, factoryFunctions, {overwrite: true});

/******************************************************************************
 * CouchDBResource's Constructor
 */
function CouchDBResource(obj) {
  arguments.callee.__super__.call(this, obj);
  setProperties(this, this);
};

oo.inherits(CouchDBResource, BaseResource);

//Finally export the CouchDBResource Object
module.exports = CouchDBResource;
<commit_msg>Fixed bug when cache is disabled / empty + proper setProperties<commit_after>/**
 * CouchDB base class/resource definition.
 * This file should be inherited by all CouchDB models that want to leverage
 * CouchDB's power in rocket.
 */

var crypto = require('crypto')
  , _ = require('underscore')
  , lingo = require('lingo')
  , cradle = require('cradle')
  , async = require('async')
  ;

var oo = require('../utils/oo')
  , namespace = require('../utils/namespace')
  , BaseResource = require('./base_resource')
  ;

/******************************************************************************
 * CONSTANTS
 */

var ROCKET_NAMESPACE = 'rocket';

/******************************************************************************
 * Default connection parameters
 */
CouchDBResource.connection = {
    host: 'localhost'
  , port: 5984
  , options: {
      raw: true
    , cache: false
    , auth: null
    }
  };

/******************************************************************************
 * Default _design documents                                     *** SYNCD ***
 */
CouchDBResource.ddocs = [
    {
      _id: '_design/rocket'
    , lists: {}
    , shows: {}
    , updates: {
        in_place: function(doc, req) {
          var oo  = require('rocket/oo')
            , ret
            ;

          if(doc !== null) {
            oo.__extends(doc, req.query, { overwrite: true });
            ret = doc;
          }else{
            ret = req.query;
          }

          return [ret, JSON.stringify(ret)];
        }
      }
    , validate_doc_update: function(newDoc, oldDoc, userCtx) {

        if(newDoc._deleted
        || typeof newDoc.doc_type === 'undefined'
        || newDoc.doc_type === null
        || newDoc.doc_type === ''
        ){
          return;
        }

        var schema = require('rocket/schema/' + newDoc.doc_type);

        for(var member in schema) {

          if(typeof schema[member] !== 'undefined'
          && schema[member] !== null) {

            var validator;
            var optional;
            var prefix;

            if(typeof schema[member] === 'string') {

              validator = require('rocket/validators/' + schema[member]) || null;

            }else if(typeof schema[member] === 'object') {

              alias = schema[member].alias;
              prefix = schema[member].prefix;
              optional = schema[member].optional;
              validator = (schema[member].validate ? require('rocket/validators/' + schema[member].validate) : null);

            }

            var value = newDoc[member];

            if(typeof value !== 'undefined'
            && value !== null) {
              if(alias) {
                continue;
              }

              if(prefix) {
                if(value.substr(0, prefix.length) !== prefix) {
                  throw({ invalid: member + '[' + value + '] must have prefix [' + prefix + ']' + '\n' + JSON.stringify(newDoc) });
                }else{
                  value = value.substr(prefix.length);
                }
              }

              if(validator) {
                validator(member, value);
              }else{
                continue;
              }
            }else if(optional || alias){
              continue;
            }else{
              throw({ invalid: member + ' can\'t be missing or null' });
            }
          }
        }
      }
    , views: {
       all: {
          map: function(doc) { emit(doc._id, doc); }
        }
      }
    }
  ];

/******************************************************************************
 * Default _security document                                    *** SYNCD ***
 */
CouchDBResource._security = {
    admins: {
        names: ["admin"]
      , roles: []
      }
  , readers: {
        names: ["admin"]
      , roles: []
      }
  };

/******************************************************************************
 * Utils functions
 */
function setProperties(dst, src, synced) {

  var synced = typeof synced !== 'undefined' ? synced : true;

  if(! dst.synced)  { Object.defineProperty(dst, 'synced', {value: {}}); }
  if(! dst.values)    { Object.defineProperty(dst, 'values', {value: {}}); }

  function createSetter(prop) {
    return function(v) {
      dst.synced[prop] = dst.synced[prop] && dst.values[prop] === v;
      dst.values[prop] = v;
    }
  }

  function createGetter(prop) {
    return function() { return dst.values[prop] };
  }

  for(var prop in src) {

    if( src.propertyIsEnumerable(prop) === false) { continue; }

    var val = src[prop];
    delete src[prop];
    Object.defineProperty(dst, prop, { enumerable: true,  configurable: true, get: createGetter(prop), set: createSetter(prop) });
    dst.synced[prop] = synced;
    dst.values[prop] = val;
  }
}

function updateCache(obj, newValues) {
  if(obj.__db.cache.store[obj._id]) {
    obj.__db.cache.store[obj._id].document = newValues;
    obj.__db.cache.store[obj._id].attime = Date.now();
  }
}

function timestamp(obj) {

  var current_time = Date.now();

  if(typeof obj.creation_date === 'undefined'
  || obj.creation_date === null
  ){
    obj.creation_date = current_time;
  }

  obj.modification_date = current_time;
}

function set_doc_type(obj, doc_type) {
  if(typeof obj.doc_type === 'undefined'
  || obj.doc_type === null
  || obj.doc_type === ''
  || !obj.propertyIsEnumerable('doc_type')
  || obj.doc_type !== doc_type
  ){
    obj.doc_type = doc_type;
  }
}

function oo_cb_wrapper(cons, cb) {
  return function(err, res) {

    var objects = [];

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

    if(res) {
      if(Array.isArray(res)){
        cons = (Array.isArray(cons) ? cons : [cons]);

        for(var i = 0, ii = res.length; i < ii; i++) {
          objects.push(new cons[i % cons.length](res[i]));
        }
        cb(err, objects);
      }else{
        //single object...
        cb(err, new cons(res));
      }
    }else{
      cb(err, res); return;
    }

  };
}

/******************************************************************************
 * Resource Prototype Functions (used to create models)
 */
CouchDBResource.prototype = {
    save: function save_CouchDBResourceInstance(callback) {
      var that = this
      ;

      timestamp(this);
      set_doc_type(this, this.doc_type);

      this.__db.save(this._id, this._rev, this, function(err,res) {
        if(err){
          callback(err);
        }else{
          setProperties(that, that);
          callback(null, res);
        }
      });
    }
  , update: function update_CouchDBResourceInstance(callback) {
      var modz = {}
        , that = this
        ;

      timestamp(this);
      set_doc_type(this, this.doc_type);

      for(var k in this) {
        if(this.propertyIsEnumerable(k) === false) {
          continue;
        }

        if(! this.synced[k]) {
          modz[k] = this[k];
        }
      }

      if(modz !== {}) {
        this.__db.update('rocket/in_place', this._id, modz, function(err){
          if(err){
            callback(err);
          }else{
            setProperties(that, that);
            updateCache(that, that.values);
            callback.apply(that, Array.prototype.slice.apply(arguments));
          }
        });
      }else{
        callback(null, '');
      }
    }
  , destroy: function destroy_CouchDBResourceInstance(callback) {
      this.__db.remove(this._id, function(err) { callback(err); });
    }
  , reload: function reload_CouchDBResourceInstance(callback) {
      var that = this;

      this.__db.get(this._id, function(err, doc) {
        if(err) {
          callback(err);
        }else{
          setProperties(that, doc);
          callback(null, that);
        }
      });

    }
  , exists: function exists_CouchDBResourceInstance() {}
  };

/******************************************************************************
 * Resource Factory/Constructor Functions
 */
var factoryFunctions = {
    initialize: function initialize_CouchDBResource(model_name, callback) {
      var that = this
        , doc_type = namespace.extractName(model_name.toLowerCase(), { suffix: '_document' })
        ;

      //Initialize connection object
      that.__connection = new cradle.Connection(
          that.connection.host
        , that.connection.port
        , that.connection.options
        );

      //Infer DB name from file name unless specified
      if(typeof that.db_name !== 'undefined' && that.db_name !== null){
        that.__db_name = that.db_name;
      }else{
        that.__db_name = lingo.en.pluralize(doc_type);
      }

      //setup db object
      that.__db = that.__connection.database(that.__db_name);
      that.prototype.__db  = that.__db;

      that.prototype.doc_type  = doc_type;

      //Create db if it doesn't exists. Harmless otherwise.
      that.__db.create();

      //prepare ddoc if it exists
      if(that.ddoc) {
        that.ddoc._id = that.ddoc._id || '_design/' + doc_type;
        that.ddocs.push(that.ddoc);
      }

      async.parallel([
        function(callback) { async.forEach(that.ddocs, syncDoc, callback); }
      , function(callback) { that.__db._save('_security', false, that._security, callback); }
      ], callback);

      function fctToString(obj) {
       for(var key in obj) {
          if(typeof obj[key] === 'function') {
            obj[key] = obj[key].toString();
          }else if(typeof obj[key] === 'object' && obj[key] !== null) {
            arguments.callee(obj[key]);
          }
        }
      }

      function syncDoc(docObj, callback) {

        //create the `rocket` namespace in the design doc
        docObj[ROCKET_NAMESPACE] = {};

        //add the validators to the design doc
        docObj[ROCKET_NAMESPACE].validators = oo.__extends({}, that.validators);

        //add the schema to the design doc
        docObj[ROCKET_NAMESPACE].schema = {};
        docObj[ROCKET_NAMESPACE].schema[doc_type] = 'module.exports = ' + JSON.stringify(that.schema);

        //convert all functions to strings
        fctToString(docObj);

        //make all validators available through commonJS' `require`
        for(var f in docObj[ROCKET_NAMESPACE].validators) {
          docObj[ROCKET_NAMESPACE].validators[f] = 'module.exports = ' + docObj[ROCKET_NAMESPACE].validators[f];
        }

        //make all the oo functions available through commonJS' `require`
        docObj[ROCKET_NAMESPACE].oo = fs.readFileSync(path.join(__dirname, '../utils/oo.js'), 'utf8');

        that.__db.get(docObj._id, checkAndUpdate);

        function checkAndUpdate(err, doc) {

          doc = doc || {};

          var oldDocJSON = JSON.stringify(doc);

          //extend the DB doc with the current doc
          oo.__deepExtends(doc, docObj, {overwrite: true});

          //docObj to a JSON string
          var docJSON = JSON.stringify(doc);

          if(err) {
            if(err.error === 'not_found'){
              that.__db.save(doc._id, doc, callback);
            }else{
              console.log(('xxx [CouchDBResource] ERROR id: ' + doc._id + ' ' + require('util').inspect(err)).red);
              callback(err);
            }
          }else{

            if(oldDocJSON !== docJSON) {
              that.__db.save(doc._id, doc._rev, doc, callback);
            }else{
              callback(null);
            }
          }
        };
      };
    }
  , create: function create_CouchDBResource(obj, callback) {
      var constructor = this.prototype.constructor
        , obj = (obj instanceof constructor ? obj : new constructor(obj))
        ;

      obj.save(callback);
    }
  , save: function save_CouchDBResource(obj, callback) {
      var constructor = this.prototype.constructor
        , obj = (obj instanceof constructor ? obj : new constructor(obj))
        ;

      obj.save(callback);
    }
  , get: function get_CouchDBResource(_id, callback) {
      this.__db.get(_id, oo_cb_wrapper(this.prototype.constructor, callback));
    }
  , destroy: function destroy_CouchDBResource(_id, callback) {
      this.__db.remove(_id, callback);
    }
  , all: function all_CouchDBResource(args) {
      var args_array = Array.prototype.slice.call(args)
        ;

      args_array.unshift('rocket/all');

      this.view(args_array);
    }
  , view: function view_CouchDBResource() {
      var args_array    = Array.prototype.slice.call(arguments)
        , view          = args_array.shift()
        , params        = (
                             typeof args_array[0] === 'object'
                          && args_array[0]
                          && ! Array.isArray(args_array[0])
                          ? args_array.shift()
                          : {}
                          )
        , constructors  = (
                             typeof args_array[0] === 'object'
                          && args_array[0]
                          && Array.isArray(args_array[0])
                          ? args_array.shift()
                          : this.prototype.constructor
                          )
        , callback      = args_array.shift()
        ;

      //add doc_type argument to filter out other docs
      params.doc_type = this.prototype.doc_type;

      //call with our callback to objectify the result
      this.__db.view.apply(this.__db, view, params, oo_cb_wrapper(constructors, callback));
    }
  };

oo.__extends(CouchDBResource, factoryFunctions, {overwrite: true});

/******************************************************************************
 * CouchDBResource's Constructor
 */
function CouchDBResource(obj) {
  arguments.callee.__super__.call(this, obj);
  setProperties(this, this);
};

oo.inherits(CouchDBResource, BaseResource);

//Finally export the CouchDBResource Object
module.exports = CouchDBResource;
<|endoftext|>


<commit_before>Gulp = {
	self    : null,
	uglify  : null,
	cssmin  : null,
	sass    : null,
	init: function(){
		Gulp.self   = require('gulp');
		Gulp.uglify = require('gulp-uglify');
		Gulp.cssmin = require('gulp-cssmin');
		Gulp.sass   = require('gulp-sass');
		Gulp.default();
		Gulp.js();
		Gulp.scss();
		Gulp.css();
		Gulp.watch();
		Gulp.wsass();
	},
	scss: function(){
		Gulp.self.task('scss', function(){
			console.log('[SASS] Compilando Arquivos do Sass');
			Gulp.self.src('./assets/scss/base/base.scss')
			.pipe(Gulp.sass())
			.pipe(Gulp.self.dest('./assets/css/src'));
			Gulp.self.src('./assets/scss/pages/**/*.scss')
			.pipe(Gulp.sass())
			.pipe(Gulp.self.dest('./assets/css/src'));
		});
	},
	css: function(){
		Gulp.self.task('css', function(){
			console.log('[CSS] Minificando Arquivos CSS');
			Gulp.self.src('./assets/css/src/**/*.css')
			.pipe(Gulp.cssmin())
			.pipe(Gulp.self.dest('./assets/css/dist'));
		});
	},
	js: function(){
		Gulp.self.task('js', function(){
			console.log('[JS] Minificando Arquivos JavaScript');
			Gulp.self.src(['./js/src/**/*.js', '!js/dist/**'])
			.pipe(Gulp.uglify())
			.pipe(Gulp.self.dest('./js/dist'))
		});
	},
	default: function(){
		Gulp.self.task('default', ['scss', 'css']);
	},
	watch: function(){
		Gulp.self.task('watch', function(){
			Gulp.self.watch('./js/**/*.js', ['js']);
			Gulp.self.watch('./assets/css/src/**', ['css']);
			Gulp.self.watch('./assets/scss/**', ['scss']);
		});
	},
	wsass: function(){
		Gulp.self.task('wsass', function(){
			Gulp.self.watch('../assets/scss/**', ['scss']);
		});
	}
}
Gulp.init();<commit_msg>Ajuste diretório destino Gulp<commit_after>Gulp = {
	self    : null,
	uglify  : null,
	cssmin  : null,
	sass    : null,
	init: function(){
		Gulp.self   = require('gulp');
		Gulp.uglify = require('gulp-uglify');
		Gulp.cssmin = require('gulp-cssmin');
		Gulp.sass   = require('gulp-sass');
		Gulp.default();
		Gulp.js();
		Gulp.scss();
		Gulp.css();
		Gulp.watch();
		Gulp.wsass();
	},
	scss: function(){
		Gulp.self.task('scss', function(){
			console.log('[SASS] Compilando Arquivos do Sass');
			Gulp.self.src('./assets/scss/base/base.scss')
			.pipe(Gulp.sass())
			.pipe(Gulp.self.dest('./assets/css/src/base'));
			Gulp.self.src('./assets/scss/pages/**/*.scss')
			.pipe(Gulp.sass())
			.pipe(Gulp.self.dest('./assets/css/src/pages'));
		});
	},
	css: function(){
		Gulp.self.task('css', function(){
			console.log('[CSS] Minificando Arquivos CSS');
			Gulp.self.src('./assets/css/src/**/*.css')
			.pipe(Gulp.cssmin())
			.pipe(Gulp.self.dest('./assets/css/dist'));
		});
	},
	js: function(){
		Gulp.self.task('js', function(){
			console.log('[JS] Minificando Arquivos JavaScript');
			Gulp.self.src(['./js/src/**/*.js', '!js/dist/**'])
			.pipe(Gulp.uglify())
			.pipe(Gulp.self.dest('./js/dist'))
		});
	},
	default: function(){
		Gulp.self.task('default', ['scss', 'css']);
	},
	watch: function(){
		Gulp.self.task('watch', function(){
			Gulp.self.watch('./js/**/*.js', ['js']);
			Gulp.self.watch('./assets/css/src/**', ['css']);
			Gulp.self.watch('./assets/scss/**', ['scss']);
		});
	},
	wsass: function(){
		Gulp.self.task('wsass', function(){
			Gulp.self.watch('../assets/scss/**', ['scss']);
		});
	}
}
Gulp.init();<|endoftext|>


<commit_before>'use strict';
// Require the needed npm modules.
const gulp = require('gulp'),
	uglify = require('gulp-uglify'),
	rename = require('gulp-rename'),
	sass = require('gulp-sass'),
	maps = require('gulp-sourcemaps'),
	useref = require('gulp-useref'),
	iff = require('gulp-if'),
	csso = require('gulp-csso'),
	concat = require('gulp-concat'),
	imagemin = require('gulp-imagemin'),
	del = require('del'),
	browserSync = require('browser-sync');

// Variables w/ path to source & dist folder.
const options = {
	src: 'src',
	dist: 'dist'
};

/* Gulp Tasks      *********************************************************/
gulp.task('scripts', ['jsMinify'], ()=> {
	// Runs jsMinify task first, then creates source map, concats the two JS files.
	return gulp.src([options.src + '/js/circle/autogrow.js', options.src + '/js/circle.min.js'])
		.pipe(maps.init())
		.pipe(concat('all.min.js'))
		.pipe(maps.write('./'))
		.pipe(gulp.dest(options.dist + '/scripts/'));
});
gulp.task('jsMinify', ()=> {
	//	Minifies the one JS file that needs it.
	return gulp.src(options.src + '/js/circle/circle.js')
	.pipe(uglify())
	.pipe(rename('circle.min.js'))
	.pipe(gulp.dest(options.src + '/js/'));
});

gulp.task('cssMinify', ()=> {
	// TODO: Check that source maps are working correctly in the browser.
	// Maybe remove the globbing patterns for the *.sass files?  'src/sass/circle/_components.sass', 'src/sass/circle/_core.sass'
	// Compiles the SaSS into CSS, writes source map for SaSS files.
	return gulp.src([options.src + '/sass/global.scss'])
		.pipe(maps.init())
		.pipe(sass())
		.pipe(maps.write('./'))
		.pipe(gulp.dest(options.dist + '/styles/'))
		.pipe(gulp.dest(options.src + '/css/'));
});

gulp.task('styles', ['cssMinify'], ()=> {
	// Needed in order to meet rubric for styles task to compile, concat & minify all SaSS files.
	return gulp.src(options.dist + '/styles/global.css')
		.pipe(csso())
		.pipe(rename('all.min.css'))
		.pipe(gulp.dest(options.dist + '/styles/'));
});

gulp.task('images', ()=> {
	// Uses gulp-imagemin module to optimize the images for production.
	return gulp.src(options.src + '/images/*')
		.pipe(imagemin())
		.pipe(gulp.dest(options.dist + '/content'));
});

gulp.task('clean', ()=> {
	// Deletes all of the files and folders in the dist folder & other files created from tasks.
	return del(['dist/*', 'src/css/', 'src/js/all.js', 'src/js/all.js.map', 'src/js/circle.min.js']);
});

gulp.task('html', ['scripts', 'styles', 'images'], ()=> {
	// Helper task for the build task to properly run the clean, scripts, styles & images tasks as dependencies.  Then any JS scripts & CSS links in the index.html get concated, minified for production.
	return gulp.src(options.src + '/index.html')
		.pipe(useref())	// useref() does file concatenation, but Not minification.
		.pipe(iff('*.js', uglify()))
		.pipe(iff('*.css', csso()))
		.pipe(gulp.dest(options.dist));
});

gulp.task('build', ['clean'], ()=> {
	//  Runs the clean, scripts, styles, and images tasks. Setups the project development files into a folder for production.
	// gulp.start(['jsMinify','styles', 'images']);
	gulp.start('html');
	// Provide production files below:
	return gulp.src(['css/global.css',
									'dist/scripts/all.min.js',
									'src/index.html',
									'src/icons/**'],
									{ base: './src/' })
		.pipe(gulp.dest('dist'));
});

gulp.task('default', ['build'], ()=> {
	// When the default gulp command is run, it continuously watches for changes to any .scss file in the project.  Runs the build task as a dependency, then serves the project using a local webserver.
	return gulp.start('watch');
});

gulp.task('watch', ['browser', 'watchMinify'], ()=> {
	// When run, watches SaSS files for changes, runs styles task on any changes to those files.
	//	gulp.watch('files-to-watch', ['tasks', 'to', 'run']);
	gulp.watch(options.src + '/sass/**/*.scss', ['watchMinify']);
});

gulp.task('browser', ()=> {
	// Starts a local server, opens project in new browser tab.
	browserSync.init({
		server: {
			baseDir: 'dist'
		},
	});
});

gulp.task('watchMinify', ['styles'], ()=> {
	// This task runs 'styles' as dependency, & then itself is run as a dependency of the 'watch' task.  Then it will minify the global.css file w/ csso(), update the production directory file & update the browser, displaying the changes.
	return gulp.src(options.dist + '/styles/all.min.css')
		// .pipe(csso())  '/styles/global.css'
		// .pipe(rename('all.min.css'))
		// .pipe(gulp.dest(options.dist + '/styles/'))
		.pipe(browserSync.reload({
			stream: true
		}));
});
<commit_msg>Fixed bug where source map was not fully working in the browser dev console by moving '.pipe(useref())' down two lines to be below both of the '.pipe(iff('*.file', uglify/csso())' methods.<commit_after>'use strict';
// Require the needed npm modules.
const gulp = require('gulp'),
	uglify = require('gulp-uglify'),
	rename = require('gulp-rename'),
	sass = require('gulp-sass'),
	maps = require('gulp-sourcemaps'),
	useref = require('gulp-useref'),
	iff = require('gulp-if'),
	csso = require('gulp-csso'),
	concat = require('gulp-concat'),
	imagemin = require('gulp-imagemin'),
	del = require('del'),
	browserSync = require('browser-sync');
// Variables w/ path to source & dist folder.
const options = {
	src: 'src',
	dist: 'dist'
};

/* Gulp Tasks      *********************************************************/
gulp.task('scripts', ['jsMinify'], ()=> {
	// Runs jsMinify task first, then creates source map, concats the two JS files.
	return gulp.src([options.src + '/js/circle/autogrow.js', options.src + '/js/circle.min.js'])
		.pipe(maps.init())
		.pipe(concat('all.min.js'))
		.pipe(maps.write('./'))
		.pipe(gulp.dest(options.dist + '/scripts/'));
});
gulp.task('jsMinify', ()=> {
	//	Minifies the one JS file that needs it.
	return gulp.src(options.src + '/js/circle/circle.js')
	.pipe(uglify())
	.pipe(rename('circle.min.js'))
	.pipe(gulp.dest(options.src + '/js/'));
});

gulp.task('cssMinify', ()=> {
	// TODO: Check that source maps are working correctly in the browser.
	return gulp.src(options.src + '/sass/global.scss')
		.pipe(maps.init({ largeFile: true, loadMaps: true }))
		// .pipe(maps.identityMap())
		.pipe(sass())
		.pipe(maps.write('./'))
		.pipe(gulp.dest(options.dist + '/styles/'))
		.pipe(gulp.dest(options.src + '/css/'));
});

gulp.task('styles', ['cssMinify'], ()=> {
	// Needed in order to meet rubric for styles task to compile, concat & minify all SaSS files.
	return gulp.src(options.dist + '/styles/global.css')
		.pipe(csso())
		.pipe(rename('all.min.css'))
		.pipe(gulp.dest(options.dist + '/styles/'));
});

gulp.task('images', ()=> {
	// Uses gulp-imagemin module to optimize the images for production.
	return gulp.src(options.src + '/images/*')
		.pipe(imagemin())
		.pipe(gulp.dest(options.dist + '/content'));
});

gulp.task('clean', ()=> {
	// Deletes all of the files and folders in the dist folder & other files created from tasks.
	return del(['dist/*', 'src/css/', 'src/js/all.js', 'src/js/all.js.map', 'src/js/circle.min.js']);
});

gulp.task('html', ['scripts', 'styles', 'images'], ()=> {
	// Helper task for the build task to properly run the clean, scripts, styles & images tasks as dependencies.  Then any JS scripts & CSS links in the index.html get concated, minified for production.
	return gulp.src(options.src + '/index.html')
		.pipe(iff('*.js', uglify()))
		.pipe(iff('*.css', csso()))
		.pipe(useref())
		.pipe(gulp.dest(options.dist));
});

gulp.task('build', ['clean'], ()=> {
	//  Runs the clean, scripts, styles, and images tasks. Setups the project development files into a folder for production.
	// gulp.start(['jsMinify','styles', 'images']);
	gulp.start('html');
	// Provide production files below:
	return gulp.src(['css/global.css',
									'dist/scripts/all.min.js',
									'src/index.html',
									'src/icons/**'],
									{ base: './src/' })
		.pipe(gulp.dest('dist'));
});

gulp.task('default', ['build'], ()=> {
	// When the default gulp command is run, it continuously watches for changes to any .scss file in the project.  Runs the build task as a dependency, then serves the project using a local webserver.
	return gulp.start('watch');
});

gulp.task('watch', ['browser', 'watchMinify'], ()=> {
	// When run, watches SaSS files for changes, runs styles task on any changes to those files.
	//	gulp.watch('files-to-watch', ['tasks', 'to', 'run']);
	gulp.watch(options.src + '/sass/**/*.scss', ['watchMinify']);
});

gulp.task('browser', ()=> {
	// Starts a local server, opens project in new browser tab.
	browserSync.init({
		server: {
			baseDir: 'dist'
		},
	});
});

gulp.task('watchMinify', ['styles'], ()=> {
	// This task runs 'styles' as dependency, & then itself is run as a dependency of the 'watch' task.  Then it will minify the global.css file w/ csso(), update the production directory file & update the browser, displaying the changes.
	return gulp.src(options.dist + '/styles/all.min.css')
		.pipe(csso())  // '/styles/global.css'
		// .pipe(rename('all.min.css'))
		// .pipe(gulp.dest(options.dist + '/styles/'))
		.pipe(useref())
		// .pipe(gulp.dest(options.dist))
		.pipe(browserSync.reload({
			stream: true
		}));
});
<|endoftext|>


<commit_before>/**
 * Module dependencies
 */

var gulp    = require('gulp');
var browser = require('browser-sync');
var reload  = require('browser-sync').reload;

/**
 * Default task
 */

gulp.task('default', ['server', 'watch']);

/**
 * Watch task
 */

gulp.task('watch', function() {
  gulp.watch('app/**/*.html', ['reload']);
});

/**
 * Server task
 */

gulp.task('server', function() {
  browser({
    server: {
      baseDir: './app'
    },

    port: 4000
  });
});

/**
 * Reload task
 */

gulp.task('reload', function() {
  reload();
});
<commit_msg>Update gulp tasks<commit_after>/**
 * Module dependencies
 */

var gulp    = require('gulp');
var browser = require('browser-sync');
var reload  = require('browser-sync').reload;

/**
 * Default task
 */

gulp.task('default', ['server', 'watch']);

/**
 * Watch task
 */

gulp.task('watch', function() {
  gulp.watch('./**/*.html', ['reload']);
});

/**
 * Server task
 */

gulp.task('server', function() {
  browser({
    server: {
      baseDir: '.',
      index: 'demo.html'
    },

    port: 4000
  });
});

/**
 * Reload task
 */

gulp.task('reload', function() {
  reload();
});
<|endoftext|>


<commit_before>'use strict';

var gulp = require('gulp');

var pkg = require('./package.json');

var jshint = require('gulp-jshint');
var uglify = require('gulp-uglify');
var webserver = require('gulp-webserver');
var concat = require('gulp-concat');
var rename = require('gulp-rename');
var size = require('gulp-size');
var header = require('gulp-header');
var rimraf = require('gulp-rimraf');
var rollup = require('gulp-rollup');
var typescript = require('rollup-plugin-typescript');
var karma = require('karma').Server;
var bump = require('gulp-bump'),

getToday = function () {

	let today = new Date();
	let dd = 	today.getDate();
	let mm = 	today.getMonth() + 1; //January is 0!
	let yyyy =  today.getFullYear();

	if (dd < 10) {
		dd = '0' + dd;
	}

	if (mm < 10) {
		mm = '0' + mm;
	}

	return yyyy + '-' + mm + '-' + dd;

};

var headerMeta = ['/*!',
	' * <%= pkg.name %> - Version <%= pkg.version %> - ' + getToday(),
	' * Copyright (c) ' + new Date().getFullYear() + ' <%= pkg.author.name %>',
	' *',
	' * <%= pkg.description %>',
	' *',
	' * - Source: https://github.com/i18next/ng-i18next/',
	' * - Issues: https://github.com/i18next/ng-i18next/issues',
	' *',
	' * License: <%= pkg.license %> - https://github.com/i18next/ng-i18next/blob/master/LICENSE',
	' *',
	'*/\n'
].join('\n');

var headerMetaMin = '/*! <%= pkg.name %> - <%= pkg.version %> - ' + getToday() +
	' - Copyright (c) ' + new Date().getFullYear() + ' <%= pkg.author.name %>; Licensed <%= pkg.license %>*/';

gulp.task('bump', function () {
	return gulp.src(['./bower.json', './package.json'])
		.pipe(bump())
		.pipe(gulp.dest('./'));
});

gulp.task('clean', [], function () {
	//remove old files
	return gulp.src(['./dist/*', './build/*'], { read: false })
		.pipe(rimraf());
});

gulp.task('rollup', ['clean'], function () {
	return gulp.src(['./src/*.ts'])
		.pipe(rollup({
			allowRealFiles: true,
			entry: 'src/provider.ts',
			format: 'umd',
			moduleName: 'ngI18next',
			dest: 'dist/ng-i18next.js',
			external: [
				'typescript'
			],
			plugins: [
				typescript()
			]
		}))
		.pipe(rename('ng-i18next.js'))
		.pipe(gulp.dest('./build/'));
});

gulp.task('concat', ['clean', 'rollup'], function () {
	return gulp.src('./build/ng-i18next.js')
		.pipe(header(headerMeta, { pkg: pkg }))
		.pipe(gulp.dest('./dist/'))
		.pipe(rename(pkg.name + '.min.js'))
		.pipe(uglify())
		.pipe(header(headerMetaMin, { pkg: pkg }))
		.pipe(size())
		.pipe(gulp.dest('./dist/'));
});

//run tests
gulp.task('karma', ['clean', 'rollup', 'concat'], function () {
	return karma.start({
		configFile: __dirname + '/karma.conf.js',
	});
});

//watch tests
gulp.task('karma-watch', ['clean', 'rollup', 'concat'], function () {
	return karma.start({
		configFile: __dirname + '/karma.conf.js',
		browsers: ['Chrome'],
		singleRun: false,
		autoWatch: true
	});
});

//TODO: documentation

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

	var info = [
		'',
		'  Usage:',
		'    - build: `gulp rollup`',
		'    - watch & test: `gulp watch`',
		'    - run examples: `gulp serve`',
		'      - Then open http://localhost:8000',
		'',
		'  For pull requests please run:',
		'    gulp test',
		'    gulp rollup',
		''
	].join('\n');

	console.info(info);
});

gulp.task('test', ['clean', 'rollup', 'concat', 'karma']);

gulp.task('serve', [], function () {

	gulp.src('./')
		.pipe(webserver({
			livereload: true,
			fallback: './examples/index.html'
		}));

});

gulp.task('ci', ['clean', 'rollup', 'concat', 'test']);
<commit_msg>let to var<commit_after>'use strict';

var gulp = require('gulp');

var pkg = require('./package.json');

var jshint = require('gulp-jshint');
var uglify = require('gulp-uglify');
var webserver = require('gulp-webserver');
var concat = require('gulp-concat');
var rename = require('gulp-rename');
var size = require('gulp-size');
var header = require('gulp-header');
var rimraf = require('gulp-rimraf');
var rollup = require('gulp-rollup');
var typescript = require('rollup-plugin-typescript');
var karma = require('karma').Server;
var bump = require('gulp-bump'),

getToday = function () {

	var today = new Date();
	var dd = 	today.getDate();
	var mm = 	today.getMonth() + 1; //January is 0!
	var yyyy =  today.getFullYear();

	if (dd < 10) {
		dd = '0' + dd;
	}

	if (mm < 10) {
		mm = '0' + mm;
	}

	return yyyy + '-' + mm + '-' + dd;

};

var headerMeta = ['/*!',
	' * <%= pkg.name %> - Version <%= pkg.version %> - ' + getToday(),
	' * Copyright (c) ' + new Date().getFullYear() + ' <%= pkg.author.name %>',
	' *',
	' * <%= pkg.description %>',
	' *',
	' * - Source: https://github.com/i18next/ng-i18next/',
	' * - Issues: https://github.com/i18next/ng-i18next/issues',
	' *',
	' * License: <%= pkg.license %> - https://github.com/i18next/ng-i18next/blob/master/LICENSE',
	' *',
	'*/\n'
].join('\n');

var headerMetaMin = '/*! <%= pkg.name %> - <%= pkg.version %> - ' + getToday() +
	' - Copyright (c) ' + new Date().getFullYear() + ' <%= pkg.author.name %>; Licensed <%= pkg.license %>*/';

gulp.task('bump', function () {
	return gulp.src(['./bower.json', './package.json'])
		.pipe(bump())
		.pipe(gulp.dest('./'));
});

gulp.task('clean', [], function () {
	//remove old files
	return gulp.src(['./dist/*', './build/*'], { read: false })
		.pipe(rimraf());
});

gulp.task('rollup', ['clean'], function () {
	return gulp.src(['./src/*.ts'])
		.pipe(rollup({
			allowRealFiles: true,
			entry: 'src/provider.ts',
			format: 'umd',
			moduleName: 'ngI18next',
			dest: 'dist/ng-i18next.js',
			external: [
				'typescript'
			],
			plugins: [
				typescript()
			]
		}))
		.pipe(rename('ng-i18next.js'))
		.pipe(gulp.dest('./build/'));
});

gulp.task('concat', ['clean', 'rollup'], function () {
	return gulp.src('./build/ng-i18next.js')
		.pipe(header(headerMeta, { pkg: pkg }))
		.pipe(gulp.dest('./dist/'))
		.pipe(rename(pkg.name + '.min.js'))
		.pipe(uglify())
		.pipe(header(headerMetaMin, { pkg: pkg }))
		.pipe(size())
		.pipe(gulp.dest('./dist/'));
});

//run tests
gulp.task('karma', ['clean', 'rollup', 'concat'], function () {
	return karma.start({
		configFile: __dirname + '/karma.conf.js',
	});
});

//watch tests
gulp.task('karma-watch', ['clean', 'rollup', 'concat'], function () {
	return karma.start({
		configFile: __dirname + '/karma.conf.js',
		browsers: ['Chrome'],
		singleRun: false,
		autoWatch: true
	});
});

//TODO: documentation

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

	var info = [
		'',
		'  Usage:',
		'    - build: `gulp rollup`',
		'    - watch & test: `gulp watch`',
		'    - run examples: `gulp serve`',
		'      - Then open http://localhost:8000',
		'',
		'  For pull requests please run:',
		'    gulp test',
		'    gulp rollup',
		''
	].join('\n');

	console.info(info);
});

gulp.task('test', ['clean', 'rollup', 'concat', 'karma']);

gulp.task('serve', [], function () {

	gulp.src('./')
		.pipe(webserver({
			livereload: true,
			fallback: './examples/index.html'
		}));

});

gulp.task('ci', ['clean', 'rollup', 'concat', 'test']);
<|endoftext|>


<commit_before>'use strict'
var cleanup = require('rollup-plugin-cleanup');
var { src, dest, series, parallel } = require('gulp');
var events = require('events');
var insert = require('gulp-insert');
var mocha = require('gulp-mocha');
var rename = require('gulp-rename');
var rollup = require('rollup');
var sucrase = require('@rollup/plugin-sucrase');
var terser = require('gulp-terser');
var typescript = require('@rollup/plugin-typescript');

events.EventEmitter.defaultMaxListeners = 0;

var items = [
    require('./build/npm/navigation/package.json'),
    Object.assign({ globals: { navigation: 'Navigation', react: 'React',
            'react-dom': 'ReactDOM' } },
        require('./build/npm/navigation-react/package.json')),
    Object.assign({ globals: { navigation: 'Navigation',
            'navigation-react': 'NavigationReact', react: 'React' } },
        require('./build/npm/navigation-react-mobile/package.json')),
    Object.assign({ globals: { navigation: 'Navigation', react: 'React',
            'react-freeze': 'ReactFreeze', 'navigation-react': 'NavigationReact',
            'react-native': 'ReactNative' },
            format: 'es' },
        require('./build/npm/navigation-react-native/package.json')),
];
function rollupTask(name, input, file, globals, format) {
    var include = input.replace(name + '.ts', '**');
    var tsconfig = input.replace(name + '.ts', 'tsconfig.json');
    return rollup.rollup({
        input,
        external: Array.isArray(globals) ? globals : Object.keys(globals),
        plugins: input.indexOf('Test') === -1
            ? [ typescript({ include, tsconfig }), cleanup({ comments: 'none' }) ]
            : [ sucrase({ include: input, transforms: ['typescript','jsx'] }) ]
    }).then((bundle) => bundle.write({ format, name, globals, file }));
}
function buildTask(name, input, file, globals, details) {
    var info = `/**
 * ${details.name} v${details.version}
 * (c) Graham Mendick - ${details.homepage}
 * License: ${details.license}
 */
`;
    return rollupTask(name, input, file, globals, 'iife')
        .then(() => (
            src(file)
                .pipe(insert.prepend(info))
                .pipe(dest('./build/dist'))
                .pipe(rename(file.replace(/js$/, 'min.js')))
                .pipe(terser())
                .pipe(insert.prepend(info))
                .pipe(dest('.'))
        ));
}
var packageNative = () => {
    var nativeFolders = ['android', 'ios']
        .map(folder => `./NavigationReactNative/src/${folder}/**/*`);
    return src(nativeFolders, {base: './NavigationReactNative/src'})
        .pipe(dest('./build/npm/navigation-react-native'));
};
var nameFunc = (func, name) => {
    func.displayName = name;
    return func;
};
var itemTasks = items.reduce((tasks, item) => {
    var packageName = item.name;
    var upperName = packageName.replace(/\b./g, (val) => val.toUpperCase());
    var name = upperName.replace(/-/g, '');
    var tsFrom = './' + name + '/src/' + name + '.ts';
    var jsTo = './build/dist/' + packageName.replace(/-/g, '.') + '.js';
    var jsPackageTo = './build/npm/' + packageName + '/' + packageName.replace(/-/g, '.') + '.js';
    item.name = upperName.replace(/-/g, ' ');
    var { globals = {}, format = 'cjs' } = item;
    tasks.buildTasks.push(
        nameFunc(() => buildTask(name, tsFrom, jsTo, globals, item), 'build' + name));
    tasks.packageTasks.push(
        nameFunc(() => rollupTask(name, tsFrom, jsPackageTo, globals, format), 'package' + name)
    );
    return tasks;
}, { buildTasks: [], packageTasks: [] });

var tests = [
    { name: 'NavigationRouting', to: 'navigationRouting.test.js' },
    { name: 'StateConfig', to: 'stateConfig.test.js' },
    { name: 'Navigation', to: 'navigation.test.js' },
    { name: 'NavigationData', to: 'navigationData.test.js' },
    { name: 'FluentNavigation', to: 'fluentNavigation.test.js' },
    { name: 'NavigationLink', to: 'navigationLink.test.js', folder: 'React', ext: 'tsx' },
    { name: 'NavigationBackLink', to: 'navigationBackLink.test.js', folder: 'React', ext: 'tsx' },
    { name: 'RefreshLink', to: 'refreshLink.test.js', folder: 'React', ext: 'tsx' },
    { name: 'FluentLink', to: 'fluentLink.test.js', folder: 'React', ext: 'tsx' },
    { name: 'NavigatingHook', to: 'navigatingHook.test.js', folder: 'ReactMobile', ext: 'tsx' },
    { name: 'NavigatedHook', to: 'navigatedHook.test.js', folder: 'ReactMobile', ext: 'tsx' },
    { name: 'UnloadingHook', to: 'unloadingHook.test.js', folder: 'ReactMobile', ext: 'tsx' },
    { name: 'UnloadedHook', to: 'unloadedHook.test.js', folder: 'ReactMobile', ext: 'tsx' },
    { name: 'NavigationMotion', to: 'navigationMotion.test.js', folder: 'ReactMobile', ext: 'tsx' }
];
function testTask(name, input, file) {
    var globals = [
        'mocha', 'assert', 'react', 'react-dom', 'react-dom/test-utils', 'jsdom',
        'tslib', 'navigation', 'navigation-react',  'navigation-react-mobile'
    ];
    return rollupTask(name, input, file, globals, 'cjs')
        .then(() =>
            src(file)
                .pipe(mocha({ reporter: 'progress' }))
                .on('error', err => console.log(err.message))
        );
}
var testTasks = tests.reduce((tasks, test) => {
    var folder = './Navigation' + (test.folder || '') + '/test/';
    var file = folder + test.name + 'Test.' + (test.ext || 'ts');
    var to = './build/dist/' + test.to;
    tasks.push(nameFunc(() => testTask(test.name, file, to), 'test' + test.name));
    return tasks;
}, []);
var packageDeps = parallel(
    itemTasks.packageTasks.find(({displayName}) => displayName === 'packageNavigation'),
    itemTasks.packageTasks.find(({displayName}) => displayName === 'packageNavigationReact'),
    itemTasks.packageTasks.find(({displayName}) => displayName === 'packageNavigationReactMobile')
);
exports.build = parallel(...itemTasks.buildTasks);
exports.package = parallel(packageNative, ...itemTasks.packageTasks);
exports.test = series(packageDeps, parallel(...testTasks));

<commit_msg>Reverted now react-freeze dep removed<commit_after>'use strict'
var cleanup = require('rollup-plugin-cleanup');
var { src, dest, series, parallel } = require('gulp');
var events = require('events');
var insert = require('gulp-insert');
var mocha = require('gulp-mocha');
var rename = require('gulp-rename');
var rollup = require('rollup');
var sucrase = require('@rollup/plugin-sucrase');
var terser = require('gulp-terser');
var typescript = require('@rollup/plugin-typescript');

events.EventEmitter.defaultMaxListeners = 0;

var items = [
    require('./build/npm/navigation/package.json'),
    Object.assign({ globals: { navigation: 'Navigation', react: 'React',
            'react-dom': 'ReactDOM' } },
        require('./build/npm/navigation-react/package.json')),
    Object.assign({ globals: { navigation: 'Navigation',
            'navigation-react': 'NavigationReact', react: 'React' } },
        require('./build/npm/navigation-react-mobile/package.json')),
    Object.assign({ globals: { navigation: 'Navigation', react: 'React',
            'navigation-react': 'NavigationReact', 'react-native': 'ReactNative' },
            format: 'es' },
        require('./build/npm/navigation-react-native/package.json')),
];
function rollupTask(name, input, file, globals, format) {
    var include = input.replace(name + '.ts', '**');
    var tsconfig = input.replace(name + '.ts', 'tsconfig.json');
    return rollup.rollup({
        input,
        external: Array.isArray(globals) ? globals : Object.keys(globals),
        plugins: input.indexOf('Test') === -1
            ? [ typescript({ include, tsconfig }), cleanup({ comments: 'none' }) ]
            : [ sucrase({ include: input, transforms: ['typescript','jsx'] }) ]
    }).then((bundle) => bundle.write({ format, name, globals, file }));
}
function buildTask(name, input, file, globals, details) {
    var info = `/**
 * ${details.name} v${details.version}
 * (c) Graham Mendick - ${details.homepage}
 * License: ${details.license}
 */
`;
    return rollupTask(name, input, file, globals, 'iife')
        .then(() => (
            src(file)
                .pipe(insert.prepend(info))
                .pipe(dest('./build/dist'))
                .pipe(rename(file.replace(/js$/, 'min.js')))
                .pipe(terser())
                .pipe(insert.prepend(info))
                .pipe(dest('.'))
        ));
}
var packageNative = () => {
    var nativeFolders = ['android', 'ios']
        .map(folder => `./NavigationReactNative/src/${folder}/**/*`);
    return src(nativeFolders, {base: './NavigationReactNative/src'})
        .pipe(dest('./build/npm/navigation-react-native'));
};
var nameFunc = (func, name) => {
    func.displayName = name;
    return func;
};
var itemTasks = items.reduce((tasks, item) => {
    var packageName = item.name;
    var upperName = packageName.replace(/\b./g, (val) => val.toUpperCase());
    var name = upperName.replace(/-/g, '');
    var tsFrom = './' + name + '/src/' + name + '.ts';
    var jsTo = './build/dist/' + packageName.replace(/-/g, '.') + '.js';
    var jsPackageTo = './build/npm/' + packageName + '/' + packageName.replace(/-/g, '.') + '.js';
    item.name = upperName.replace(/-/g, ' ');
    var { globals = {}, format = 'cjs' } = item;
    tasks.buildTasks.push(
        nameFunc(() => buildTask(name, tsFrom, jsTo, globals, item), 'build' + name));
    tasks.packageTasks.push(
        nameFunc(() => rollupTask(name, tsFrom, jsPackageTo, globals, format), 'package' + name)
    );
    return tasks;
}, { buildTasks: [], packageTasks: [] });

var tests = [
    { name: 'NavigationRouting', to: 'navigationRouting.test.js' },
    { name: 'StateConfig', to: 'stateConfig.test.js' },
    { name: 'Navigation', to: 'navigation.test.js' },
    { name: 'NavigationData', to: 'navigationData.test.js' },
    { name: 'FluentNavigation', to: 'fluentNavigation.test.js' },
    { name: 'NavigationLink', to: 'navigationLink.test.js', folder: 'React', ext: 'tsx' },
    { name: 'NavigationBackLink', to: 'navigationBackLink.test.js', folder: 'React', ext: 'tsx' },
    { name: 'RefreshLink', to: 'refreshLink.test.js', folder: 'React', ext: 'tsx' },
    { name: 'FluentLink', to: 'fluentLink.test.js', folder: 'React', ext: 'tsx' },
    { name: 'NavigatingHook', to: 'navigatingHook.test.js', folder: 'ReactMobile', ext: 'tsx' },
    { name: 'NavigatedHook', to: 'navigatedHook.test.js', folder: 'ReactMobile', ext: 'tsx' },
    { name: 'UnloadingHook', to: 'unloadingHook.test.js', folder: 'ReactMobile', ext: 'tsx' },
    { name: 'UnloadedHook', to: 'unloadedHook.test.js', folder: 'ReactMobile', ext: 'tsx' },
    { name: 'NavigationMotion', to: 'navigationMotion.test.js', folder: 'ReactMobile', ext: 'tsx' }
];
function testTask(name, input, file) {
    var globals = [
        'mocha', 'assert', 'react', 'react-dom', 'react-dom/test-utils', 'jsdom',
        'tslib', 'navigation', 'navigation-react',  'navigation-react-mobile'
    ];
    return rollupTask(name, input, file, globals, 'cjs')
        .then(() =>
            src(file)
                .pipe(mocha({ reporter: 'progress' }))
                .on('error', err => console.log(err.message))
        );
}
var testTasks = tests.reduce((tasks, test) => {
    var folder = './Navigation' + (test.folder || '') + '/test/';
    var file = folder + test.name + 'Test.' + (test.ext || 'ts');
    var to = './build/dist/' + test.to;
    tasks.push(nameFunc(() => testTask(test.name, file, to), 'test' + test.name));
    return tasks;
}, []);
var packageDeps = parallel(
    itemTasks.packageTasks.find(({displayName}) => displayName === 'packageNavigation'),
    itemTasks.packageTasks.find(({displayName}) => displayName === 'packageNavigationReact'),
    itemTasks.packageTasks.find(({displayName}) => displayName === 'packageNavigationReactMobile')
);
exports.build = parallel(...itemTasks.buildTasks);
exports.package = parallel(packageNative, ...itemTasks.packageTasks);
exports.test = series(packageDeps, parallel(...testTasks));

<|endoftext|>