<commit_before>//==============================================================================================================================================
//----------------------------------------------------------------------------------------------------------------------------------------------

//-- Setting

//----------------------------------------------------------------------------------------------------------------------------------------------

var gulp = require('gulp'), S = {}, $ = {
    combineMq:       require("gulp-combine-mq"),
    concat:          require("gulp-concat"),
    if:              require("gulp-if"),
    notify:          require("gulp-notify"),
    plumber:         require("gulp-plumber"),
    postcss:         require("gulp-postcss"),
    rename:          require("gulp-rename"),
    replace:         require("gulp-replace"),
    sass:            require("gulp-sass"),
    uglify:          require("gulp-uglify"),
    zip:             require("gulp-zip"),
    merge:           require("merge-stream"),
    bower:           require("bower"),
    browserSync:     require("browser-sync"),
    cssnano:         require("cssnano"),
    del:             require("del"),
    fs:              require("fs"),
    postcss_cssnext: require("postcss-cssnext"),
    runSequence:     require("run-sequence")
};

S.Extensions = ["analytics", "epubcfi", "jatex", "overreflow", "share", "unzipper"];

S.concat = function() {
    var list = arguments[0];
    for(var i = 1, l = arguments.length; i < l; i++) list = list.concat(arguments[i]);
    return list;
};

S.getVersion = function() {
    return JSON.parse($.fs.readFileSync('package.json')).version;
};

S.getBuildNumber = function() {
    var now = "", date = new Date();
    [
        date.getYear() + 1900,
        date.getMonth() + 1,
        date.getDate(),
        date.getHours(),
        date.getMinutes()/*,
        date.getSeconds()*/
    ].forEach(function(d) {
        now += (d < 10 ? "0" : "") + d;
    });
    return now;
};

//==============================================================================================================================================
//----------------------------------------------------------------------------------------------------------------------------------------------

//-- Clean

//----------------------------------------------------------------------------------------------------------------------------------------------

S.clean = function(list) {
    $.del.sync(list);
    return gulp;
};

gulp.task('clean: Scripts', function() {
    return S.clean(ToBeCleaned.Scripts);
});

gulp.task('clean: Styles', function() {
    return S.clean(ToBeCleaned.Styles);
});

gulp.task('clean: Metafiles', function() {
    return S.clean(ToBeCleaned.Metafiles);
});

gulp.task('clean: All', function() {
    return S.clean(ToBeCleaned.All);
});

var ToBeCleaned = {
    Scripts: [
        'bib/i/res/scripts',
        'bib/i/extensions/analytics',
        'bib/i/extensions/epubcfi',
        'bib/i/extensions/jatex',
        'bib/i/extensions/overreflow',
        'bib/i/extensions/share',
        'bib/i/extensions/unzipper',
        'bib/i.js'
    ],
    Styles: [
        'bib/i/res/styles',
        'bib/i.css'
    ],
    Metafiles: [
        'bib/LICENSE',
        'bib/README.md'
    ]
};

ToBeCleaned.All = S.concat(ToBeCleaned.Scripts, ToBeCleaned.Styles, ToBeCleaned.Metafiles);

//==============================================================================================================================================
//----------------------------------------------------------------------------------------------------------------------------------------------

//-- Update Metafiles

//----------------------------------------------------------------------------------------------------------------------------------------------

gulp.task('update: JSONs', function() {
    return gulp.src([
        'bower.json',
        'bib/manifest.json'
    ])
        .pipe($.plumber({ errorHandler: $.notify.onError('<%= error.message %>') }))
        .pipe($.replace(/"version"(\s*:\s*)".+?"/, '"version"$1"' + S.getVersion() + '"'))
        .pipe(gulp.dest(''));
});

gulp.task('update: README.md', function() {
    return gulp.src([
        'README.md'
    ])
        .pipe($.plumber({ errorHandler: $.notify.onError('<%= error.message %>') }))
        .pipe(gulp.dest('bib'));
});

gulp.task('update: LICENSE', function() {
    return gulp.src([
        'LICENSE'
    ])
        .pipe($.plumber({ errorHandler: $.notify.onError('<%= error.message %>') }))
        .pipe(gulp.dest('bib'));
});

var Tasks_updateMetafiles = [
    'update: JSONs',
    'update: README.md',
    'update: LICENSE'
];

//==============================================================================================================================================
//----------------------------------------------------------------------------------------------------------------------------------------------

//-- Update Bower Components

//----------------------------------------------------------------------------------------------------------------------------------------------

S.update_bower_components_js = function() {
    return gulp.src([
        'bower_components/native-promise-only/lib/npo.src.js',
        'bower_components/hammerjs/hammer.min.js',
        'bower_components/easing/easing-min.js',
        'bower_components/sML/sML.js'
    ])
        .pipe($.plumber({ errorHandler: $.notify.onError('<%= error.message %>') }))
        .pipe($.concat('dev-bib/i/res/scripts/_lib/bower_components.js'))
        .pipe($.uglify({ preserveComments: 'some' }))
        .pipe(gulp.dest(''));
};

gulp.task('update: bower_components', function() {
    return $.bower.commands.install().on('end', S.update_bower_components_js);
});

gulp.task('update: bower_components.js', function() {
    return S.update_bower_components_js();
});

//==============================================================================================================================================
//----------------------------------------------------------------------------------------------------------------------------------------------

//-- Make Scripts

//----------------------------------------------------------------------------------------------------------------------------------------------

S.makeScript = function(Param) {
    return gulp.src(Param.src)
        .pipe($.plumber({ errorHandler: $.notify.onError('<%= error.message %>') }))
        .pipe($.concat(Param.dist))
        .pipe($.uglify({ preserveComments: 'some' }))
        .pipe($.replace('0.000.0', S.getVersion()))
        .pipe($.replace('198106091234', S.getBuildNumber()))
        .pipe(gulp.dest(''))
        .pipe($.browserSync.reload({ stream: true }));
};

gulp.task('make: bibi.js', function() {
    return S.makeScript({
        src: [
			'dev-bib/i/res/scripts/_banner.js',
			'dev-bib/i/res/scripts/_lib/bower_components.js',
			'dev-bib/i/res/scripts/bibi.heart.js'
        ],
        dist: 'bib/i/res/scripts/bibi.js'
    });
});

gulp.task('make: i.js', function() {
    return S.makeScript({
        src: [
            'dev-bib/i.js'
        ],
        dist: 'bib/i.js'
    });
});

var Tasks_makeScripts = [
    'make: bibi.js',
    'make: i.js'
];

//==============================================================================================================================================
//----------------------------------------------------------------------------------------------------------------------------------------------

//-- Make Extension Scripts

//----------------------------------------------------------------------------------------------------------------------------------------------

S.makeExtensionScript = function(ExtensionName) {
    var Sources = [
        'dev-bib/i/extensions/' + ExtensionName + '/' + ExtensionName + '.js'
    ];
    if(ExtensionName == "unzipper") {
        Sources.unshift('dev-bib/i/extensions/unzipper/_banner.js');
        Sources.push(   'dev-bib/i/extensions/unzipper/_lib/jszip.min.js');
        Sources.push(   'dev-bib/i/extensions/unzipper/_lib/base64.js');
    }
    return S.makeScript({
        src: Sources,
        dist: 'bib/i/extensions/' + ExtensionName + '/' + ExtensionName + '.js'
    });
};

var Tasks_makeExtensionScripts = [];

S.Extensions.forEach(function(ExtensionName) {
    gulp.task('make: extension: ' + ExtensionName + '.js', function() {
        return S.makeExtensionScript(ExtensionName);
    });
    Tasks_makeExtensionScripts.push('make: extension: ' + ExtensionName + '.js');
});

//==============================================================================================================================================
//----------------------------------------------------------------------------------------------------------------------------------------------

//-- Make Styles

//----------------------------------------------------------------------------------------------------------------------------------------------

S.makeStyle = function(Param) {
    return $.merge(
        gulp.src(Param.header),
        gulp.src(Param.src)
    )
        .pipe($.plumber({ errorHandler: $.notify.onError('<%= error.message %>') }))
        .pipe($.sass())
        .pipe($.combineMq())
        .pipe($.concat(Param.dist))
        .pipe($.postcss([
            $.postcss_cssnext({
                browsers: 'last 2 versions',
                warnForDuplicates: false
            }),
            $.cssnano()
        ]))
        .pipe(gulp.dest(''))
        .pipe($.browserSync.reload({ stream: true }));
};

gulp.task('make: bibi.css', function() {
    return S.makeStyle({
        header: [
            'dev-bib/i/res/styles/-header.scss'
        ],
        src: [
            'dev-bib/i/res/styles/bibi.scss'
        ],
        dist: 'bib/i/res/styles/bibi.css'
    });
});

gulp.task('make: i.css', function() {
    return S.makeStyle({
        header: [
        ],
        src: [
            'dev-bib/i.scss'
        ],
        dist: 'bib/i.css'
    });
});

var Tasks_makeStyles = [
    'make: bibi.css',
    'make: i.css'
];

//==============================================================================================================================================
//----------------------------------------------------------------------------------------------------------------------------------------------

//-- Serve

//----------------------------------------------------------------------------------------------------------------------------------------------

gulp.task('serve', function() {
    $.browserSync({
        server: {
            baseDir: '',
            index: 'index.html'
        },
        ghostMode: {
            location: true
        }
    });
    return gulp.watch([
        'bib/i/index.html',
        'bib/i/presets/*.js',
        'bib/i/res/scripts/*.js',
        'bib/i/extensions/**/*.js'
    ]).on('change', $.browserSync.reload);
});

//==============================================================================================================================================
//----------------------------------------------------------------------------------------------------------------------------------------------

//-- Watch

//----------------------------------------------------------------------------------------------------------------------------------------------

gulp.task('watch', function() {
    gulp.watch(['dev-bib/i/res/scripts/**/*.js'], ['make: bibi.js']);
    gulp.watch(['dev-bib/i.js'], ['make: i.js']);
    S.Extensions.forEach(function(ExtensionName) {
        gulp.watch(['dev-bib/i/extensions/' + ExtensionName + '/**/*.js'], ['make: extension: ' + ExtensionName + '.js']);
    });
    gulp.watch(['dev-bib/i/res/styles/*.scss',], ['make: bibi.css']);
    gulp.watch(['dev-bib/i.scss'], ['make: i.css']);
    gulp.watch(['package.json'], ['update: JSONs']);
    gulp.watch(['README.md'], ['update: README.md']);
    gulp.watch(['LICENSE'], ['update: LICENSE']);
    gulp.watch(['bower.json'], ['update: bower_components']);
    return gulp;
});

//==============================================================================================================================================
//----------------------------------------------------------------------------------------------------------------------------------------------

//-- Build, Update, Default

//----------------------------------------------------------------------------------------------------------------------------------------------

gulp.task('build', function() {
    return $.runSequence(
        ['clean: All'],
        Tasks_updateMetafiles,
        ['update: bower_components.js'],
        S.concat(Tasks_makeScripts, Tasks_makeExtensionScripts, Tasks_makeStyles)
    );
});

gulp.task('update', function() {
    return $.runSequence(
        Tasks_updateMetafiles,
        ['update: bower_components.js'],
        S.concat(Tasks_makeScripts, Tasks_makeExtensionScripts, Tasks_makeStyles)
    );
});

gulp.task('default', function() {
    return $.runSequence(
        ['clean: All'],
        Tasks_updateMetafiles,
        ['update: bower_components.js'],
        S.concat(Tasks_makeScripts, Tasks_makeExtensionScripts, Tasks_makeStyles),
        ['serve', 'watch']
    );
});

//==============================================================================================================================================
//----------------------------------------------------------------------------------------------------------------------------------------------

//-- Distribute

//----------------------------------------------------------------------------------------------------------------------------------------------

gulp.task('clean: Distribution', function() {
    var Ver = S.getVersion();
    return S.clean([
        'archives/bibi-' + Ver,
        'archives/bibi-' + Ver + '.zip'
    ]);
});

gulp.task('copy: Distribution', function() {
    var Ver = S.getVersion();
    return gulp.src([
        'bib/i/**/*.*',
        'bib/*'
    ], {
        base: './'
    })
        .pipe($.plumber({ errorHandler: $.notify.onError('<%= error.message %>') }))
        .pipe(gulp.dest('archives/bibi-' + Ver));
});

gulp.task('archive: Distribution', function() {
    var Ver = S.getVersion();
    return gulp.src([
        'archives/bibi-' + Ver + '/bib/**/*.*',
        'archives/bibi-' + Ver + '/bib/*'
    ])
        .pipe($.plumber({ errorHandler: $.notify.onError('<%= error.message %>') }))
        .pipe($.zip('bibi-' + Ver + '.zip'))
        .pipe(gulp.dest('archives'));
});

gulp.task('distribute', function() {
    return $.runSequence(
        ['clean: All'],
        Tasks_updateMetafiles,
        ['update: bower_components.js'],
        S.concat(Tasks_makeScripts, Tasks_makeExtensionScripts, Tasks_makeStyles),
        'clean: Distribution',
        'copy: Distribution',
        'archive: Distribution'
    );
});
<commit_msg>Refactor gulpfile.js.<commit_after>//==============================================================================================================================================
//----------------------------------------------------------------------------------------------------------------------------------------------

//-- Setting

//----------------------------------------------------------------------------------------------------------------------------------------------

var gulp = require('gulp'), S = {}, $ = {
    combineMq:       require("gulp-combine-mq"),
    concat:          require("gulp-concat"),
    if:              require("gulp-if"),
    notify:          require("gulp-notify"),
    plumber:         require("gulp-plumber"),
    postcss:         require("gulp-postcss"),
    rename:          require("gulp-rename"),
    replace:         require("gulp-replace"),
    sass:            require("gulp-sass"),
    uglify:          require("gulp-uglify"),
    zip:             require("gulp-zip"),
    merge:           require("merge-stream"),
    bower:           require("bower"),
    browserSync:     require("browser-sync"),
    cssnano:         require("cssnano"),
    del:             require("del"),
    fs:              require("fs"),
    postcss_cssnext: require("postcss-cssnext"),
    runSequence:     require("run-sequence")
};

S.Extensions = [
    "analytics",
    "epubcfi",
    "jatex",
    "overreflow",
    "share",
    "unzipper"
];

S.concat = function() {
    var list = arguments[0];
    for(var i = 1, l = arguments.length; i < l; i++) list = list.concat(arguments[i]);
    return list;
};

S.getVersion = function() {
    return JSON.parse($.fs.readFileSync('package.json')).version;
};

S.getBuildNumber = function() {
    var now = "", date = new Date();
    [
        date.getYear() + 1900,
        date.getMonth() + 1,
        date.getDate(),
        date.getHours(),
        date.getMinutes()/*,
        date.getSeconds()*/
    ].forEach(function(d) {
        now += (d < 10 ? "0" : "") + d;
    });
    return now;
};

//==============================================================================================================================================
//----------------------------------------------------------------------------------------------------------------------------------------------

//-- Clean

//----------------------------------------------------------------------------------------------------------------------------------------------

S.clean = function(list) {
    $.del.sync(list);
    return gulp;
};

gulp.task('clean: Scripts', function() {
    return S.clean(ToBeCleaned.Scripts);
});

gulp.task('clean: Styles', function() {
    return S.clean(ToBeCleaned.Styles);
});

gulp.task('clean: Metafiles', function() {
    return S.clean(ToBeCleaned.Metafiles);
});

gulp.task('clean: All', function() {
    return S.clean(ToBeCleaned.All);
});

var ToBeCleaned = {
    Scripts: [
        'bib/i/res/scripts',
        'bib/i.js'
    ],
    Styles: [
        'bib/i/res/styles',
        'bib/i.css'
    ],
    Metafiles: [
        'bib/LICENSE',
        'bib/README.md'
    ]
};

S.Extensions.forEach(function(Extension) {
    ToBeCleaned.Scripts.push('bib/i/extensions/' + Extension);
});

ToBeCleaned.All = S.concat(ToBeCleaned.Scripts, ToBeCleaned.Styles, ToBeCleaned.Metafiles);

//==============================================================================================================================================
//----------------------------------------------------------------------------------------------------------------------------------------------

//-- Update Metafiles

//----------------------------------------------------------------------------------------------------------------------------------------------

gulp.task('update: JSONs', function() {
    return gulp.src([
        'bower.json',
        'bib/manifest.json'
    ])
        .pipe($.plumber({ errorHandler: $.notify.onError('<%= error.message %>') }))
        .pipe($.replace(/"version"(\s*:\s*)".+?"/, '"version"$1"' + S.getVersion() + '"'))
        .pipe(gulp.dest(''));
});

gulp.task('update: README.md', function() {
    return gulp.src([
        'README.md'
    ])
        .pipe($.plumber({ errorHandler: $.notify.onError('<%= error.message %>') }))
        .pipe(gulp.dest('bib'));
});

gulp.task('update: LICENSE', function() {
    return gulp.src([
        'LICENSE'
    ])
        .pipe($.plumber({ errorHandler: $.notify.onError('<%= error.message %>') }))
        .pipe(gulp.dest('bib'));
});

var Tasks_updateMetafiles = [
    'update: JSONs',
    'update: README.md',
    'update: LICENSE'
];

//==============================================================================================================================================
//----------------------------------------------------------------------------------------------------------------------------------------------

//-- Update Bower Components

//----------------------------------------------------------------------------------------------------------------------------------------------

S.update_bower_components_js = function() {
    return gulp.src([
        'bower_components/native-promise-only/lib/npo.src.js',
        'bower_components/hammerjs/hammer.min.js',
        'bower_components/easing/easing-min.js',
        'bower_components/sML/sML.js'
    ])
        .pipe($.plumber({ errorHandler: $.notify.onError('<%= error.message %>') }))
        .pipe($.concat('dev-bib/i/res/scripts/_lib/bower_components.js'))
        .pipe($.uglify({ preserveComments: 'some' }))
        .pipe(gulp.dest(''));
};

gulp.task('update: bower_components', function() {
    return $.bower.commands.install().on('end', S.update_bower_components_js);
});

gulp.task('update: bower_components.js', function() {
    return S.update_bower_components_js();
});

//==============================================================================================================================================
//----------------------------------------------------------------------------------------------------------------------------------------------

//-- Make Scripts

//----------------------------------------------------------------------------------------------------------------------------------------------

S.makeScript = function(Param) {
    return gulp.src(Param.src)
        .pipe($.plumber({ errorHandler: $.notify.onError('<%= error.message %>') }))
        .pipe($.concat(Param.dist))
        .pipe($.uglify({ preserveComments: 'some' }))
        .pipe($.replace('0.000.0', S.getVersion()))
        .pipe($.replace('198106091234', S.getBuildNumber()))
        .pipe(gulp.dest(''))
        .pipe($.browserSync.reload({ stream: true }));
};

gulp.task('make: bibi.js', function() {
    return S.makeScript({
        src: [
			'dev-bib/i/res/scripts/_banner.js',
			'dev-bib/i/res/scripts/_lib/bower_components.js',
			'dev-bib/i/res/scripts/bibi.heart.js'
        ],
        dist: 'bib/i/res/scripts/bibi.js'
    });
});

gulp.task('make: i.js', function() {
    return S.makeScript({
        src: [
            'dev-bib/i.js'
        ],
        dist: 'bib/i.js'
    });
});

var Tasks_makeScripts = [
    'make: bibi.js',
    'make: i.js'
];

//==============================================================================================================================================
//----------------------------------------------------------------------------------------------------------------------------------------------

//-- Make Extension Scripts

//----------------------------------------------------------------------------------------------------------------------------------------------

S.makeExtensionScript = function(ExtensionName) {
    var Sources = [
        'dev-bib/i/extensions/' + ExtensionName + '/' + ExtensionName + '.js'
    ];
    if(ExtensionName == "unzipper") {
        Sources.unshift('dev-bib/i/extensions/unzipper/_banner.js');
        Sources.push(   'dev-bib/i/extensions/unzipper/_lib/jszip.min.js');
        Sources.push(   'dev-bib/i/extensions/unzipper/_lib/base64.js');
    }
    return S.makeScript({
        src: Sources,
        dist: 'bib/i/extensions/' + ExtensionName + '/' + ExtensionName + '.js'
    });
};

var Tasks_makeExtensionScripts = [];

S.Extensions.forEach(function(ExtensionName) {
    gulp.task('make: extension: ' + ExtensionName + '.js', function() {
        return S.makeExtensionScript(ExtensionName);
    });
    Tasks_makeExtensionScripts.push('make: extension: ' + ExtensionName + '.js');
});

//==============================================================================================================================================
//----------------------------------------------------------------------------------------------------------------------------------------------

//-- Make Styles

//----------------------------------------------------------------------------------------------------------------------------------------------

S.makeStyle = function(Param) {
    return $.merge(
        gulp.src(Param.header),
        gulp.src(Param.src)
    )
        .pipe($.plumber({ errorHandler: $.notify.onError('<%= error.message %>') }))
        .pipe($.sass())
        .pipe($.combineMq())
        .pipe($.concat(Param.dist))
        .pipe($.postcss([
            $.postcss_cssnext({
                browsers: 'last 2 versions',
                warnForDuplicates: false
            }),
            $.cssnano({
                zindex: false
            })
        ]))
        .pipe(gulp.dest(''))
        .pipe($.browserSync.reload({ stream: true }));
};

gulp.task('make: bibi.css', function() {
    return S.makeStyle({
        header: [
            'dev-bib/i/res/styles/-header.scss'
        ],
        src: [
            'dev-bib/i/res/styles/bibi.scss'
        ],
        dist: 'bib/i/res/styles/bibi.css'
    });
});

gulp.task('make: i.css', function() {
    return S.makeStyle({
        header: [
        ],
        src: [
            'dev-bib/i.scss'
        ],
        dist: 'bib/i.css'
    });
});

var Tasks_makeStyles = [
    'make: bibi.css',
    'make: i.css'
];

//==============================================================================================================================================
//----------------------------------------------------------------------------------------------------------------------------------------------

//-- Make Extension Styles

//----------------------------------------------------------------------------------------------------------------------------------------------

S.makeExtensionStyle = function(ExtensionName) {
    return S.makeStyle({
        header: [
            'dev-bib/i/extensions/' + ExtensionName + '/-header.scss'
        ],
        src: [
            'dev-bib/i/extensions/' + ExtensionName + '/' + ExtensionName + '.scss'
        ],
        dist: 'bib/i/extensions/' + ExtensionName + '/' + ExtensionName + '.css'
    });
};

var Tasks_makeExtensionStyles = [];

S.Extensions.forEach(function(ExtensionName) {
    gulp.task('make: extension: ' + ExtensionName + '.css', function() {
        return S.makeExtensionStyle(ExtensionName);
    });
    Tasks_makeExtensionStyles.push('make: extension: ' + ExtensionName + '.css');
});

//==============================================================================================================================================
//----------------------------------------------------------------------------------------------------------------------------------------------

//-- Serve

//----------------------------------------------------------------------------------------------------------------------------------------------

gulp.task('serve', function() {
    $.browserSync({
        server: {
            baseDir: '',
            index: 'index.html'
        },
        ghostMode: {
            location: true
        }
    });
    return gulp.watch([
        'bib/i/index.html',
        'bib/i/presets/*.js',
        'bib/i/res/scripts/*.js',
        'bib/i/extensions/**/*.js'
    ]).on('change', $.browserSync.reload);
});

//==============================================================================================================================================
//----------------------------------------------------------------------------------------------------------------------------------------------

//-- Watch

//----------------------------------------------------------------------------------------------------------------------------------------------

gulp.task('watch', function() {
    gulp.watch(['dev-bib/i/res/scripts/**/*.js'], ['make: bibi.js']);
    gulp.watch(['dev-bib/i.js'], ['make: i.js']);
    gulp.watch(['dev-bib/i/res/styles/*.scss',], ['make: bibi.css']);
    gulp.watch(['dev-bib/i.scss'], ['make: i.css']);
    S.Extensions.forEach(function(ExtensionName) { gulp.watch(['dev-bib/i/extensions/' + ExtensionName + '/**/*.js'  ], ['make: extension: ' + ExtensionName + '.js' ]); });
    S.Extensions.forEach(function(ExtensionName) { gulp.watch(['dev-bib/i/extensions/' + ExtensionName + '/**/*.scss'], ['make: extension: ' + ExtensionName + '.css']); });
    gulp.watch(['package.json'], ['update: JSONs']);
    gulp.watch(['README.md'], ['update: README.md']);
    gulp.watch(['LICENSE'], ['update: LICENSE']);
    gulp.watch(['bower.json'], ['update: bower_components']);
    return gulp;
});

//==============================================================================================================================================
//----------------------------------------------------------------------------------------------------------------------------------------------

//-- Build, Update, Default

//----------------------------------------------------------------------------------------------------------------------------------------------

gulp.task('build', function() {
    return $.runSequence(
        ['clean: All'],
        Tasks_updateMetafiles,
        ['update: bower_components.js'],
        S.concat(Tasks_makeScripts, Tasks_makeStyles, Tasks_makeExtensionScripts, Tasks_makeExtensionStyles)
    );
});

gulp.task('update', function() {
    return $.runSequence(
        Tasks_updateMetafiles,
        ['update: bower_components.js'],
        S.concat(Tasks_makeScripts, Tasks_makeStyles, Tasks_makeExtensionScripts, Tasks_makeExtensionStyles)
    );
});

gulp.task('default', function() {
    return $.runSequence(
        ['clean: All'],
        Tasks_updateMetafiles,
        ['update: bower_components.js'],
        S.concat(Tasks_makeScripts, Tasks_makeStyles, Tasks_makeExtensionScripts, Tasks_makeExtensionStyles),
        ['serve', 'watch']
    );
});

//==============================================================================================================================================
//----------------------------------------------------------------------------------------------------------------------------------------------

//-- Distribute

//----------------------------------------------------------------------------------------------------------------------------------------------

gulp.task('clean: Distribution', function() {
    var Ver = S.getVersion();
    return S.clean([
        'archives/bibi-' + Ver,
        'archives/bibi-' + Ver + '.zip'
    ]);
});

gulp.task('copy: Distribution', function() {
    var Ver = S.getVersion();
    return gulp.src([
        'bib/i/**/*.*',
        'bib/*'
    ], {
        base: './'
    })
        .pipe($.plumber({ errorHandler: $.notify.onError('<%= error.message %>') }))
        .pipe(gulp.dest('archives/bibi-' + Ver));
});

gulp.task('archive: Distribution', function() {
    var Ver = S.getVersion();
    return gulp.src([
        'archives/bibi-' + Ver + '/bib/**/*.*',
        'archives/bibi-' + Ver + '/bib/*'
    ])
        .pipe($.plumber({ errorHandler: $.notify.onError('<%= error.message %>') }))
        .pipe($.zip('bibi-' + Ver + '.zip'))
        .pipe(gulp.dest('archives'));
});

gulp.task('distribute', function() {
    return $.runSequence(
        ['clean: All'],
        Tasks_updateMetafiles,
        ['update: bower_components.js'],
        S.concat(Tasks_makeScripts, Tasks_makeStyles, Tasks_makeExtensionScripts, Tasks_makeExtensionStyles),
        'clean: Distribution',
        'copy: Distribution',
        'archive: Distribution'
    );
});
<|endoftext|>


<commit_before>// ---------- Plugins and paths ----------

var gulp = require("gulp"),
    clean = require("gulp-clean"),
    zip = require("gulp-zip"),
    concat = require("gulp-concat"),
    rename = require("gulp-rename"),
    uglify = require("gulp-uglify"),
    sass = require("gulp-sass"),
    cssnano = require("gulp-cssnano"),
    htmlreplace = require("gulp-html-replace"),
    eslint = require("gulp-eslint"),
    scsslint = require("gulp-scss-lint"),
    bump = require("gulp-bump"),
    git = require("gulp-git"),
    tag_version = require("gulp-tag-version"),
    paths = {
        // All JS files - for linting
        allscripts : ["src/app/**/*.js", "gulpfile.js"],
        // Only source JS files - for building the artefact
        appscripts : ["src/app/app.module.js", "src/app/**/*.js"],
        // All scss files
        styles     : "src/assets/styles/*.scss",
        // All image files
        images     : "src/assets/images/**/*.png",
        // The config settings for the app
        config     : "src/app/app.config.json"
    };

// ---------- Code lint and tidy up tasks ----------

// Clean /dist and remove everything
gulp.task("clean", function () {
  return gulp.src("dist/*", {read:false})
    .pipe(clean({
        force : true
    }));
});

// Check the JS code against ESLint standards
gulp.task("eslint", function() {
  return gulp.src(paths.allscripts).pipe(eslint({
    extends : "eslint:recommended",
    rules : {
        "quotes" : [1, "double"],
        "semi"   : [1, "always"]
    },
    globals : {
        "angular"      : true,
        "keijiban"     : true,
        "window"       : true,
        "baseSlice"    : true,
        "chunk"        : true,
        "buildToggler" : true,
        "require"      : true
    }
  }))
  .pipe(eslint.format())
  .pipe(eslint.failOnError()); // Fail task on lint errors
});

// Check the SCSS code against scss-lint standards
gulp.task("scsslint", function() {
  return gulp.src(paths.styles)
    .pipe(scsslint())
    .pipe(scsslint.failReporter()); // Report failures in the console
});

// Combination task which checks the .js and .scss files against coding standards
gulp.task("code-check", ["eslint", "scsslint"]);

// ---------- Production build tasks ----------

// Build an artefact and zip everything up
gulp.task("build", ["scripts", "bower_components", "styles", "html", "images", "index", "config", "misc"], function() {
  return gulp.src("dist/**/**")
    .pipe(zip("keijiban.zip"))
    .pipe(gulp.dest("dist"));
});

// Combine all the src JS, minify and then uglify
gulp.task("scripts", function() {
  return gulp.src(paths.appscripts)
    .pipe(concat("app.js"))
    .pipe(gulp.dest("dist"))
    .pipe(rename("app.min.js"))
    //.pipe(uglify()) // Causes problems loading bower.json
    .pipe(gulp.dest("dist"));
});

// Combine sccs into one file, compile into css, minify
gulp.task("styles", function() {
  return gulp.src(paths.styles)
    .pipe(sass().on("error", sass.logError)) // Log sass errors
    .pipe(concat("app.min.css"))
    .pipe(cssnano())
    .pipe(gulp.dest("dist"));
});

// Move all the html into /dist
gulp.task("html", function() {
  return gulp.src("src/app/**/*.html")
    .pipe(gulp.dest("dist/src/app"));
});

// Move the images into /dist
gulp.task("images", function() {
  return gulp.src(paths.images)
    .pipe(gulp.dest("dist/src/assets/images/"));
});

// Move the app config into /dist
gulp.task("config", function() {
  return gulp.src(paths.config)
    .pipe(gulp.dest("dist/src/app"));
});

// Move index.html into /dist and replace the filepaths as required
gulp.task("index", function() {
  return gulp.src("index.html")
    .pipe(htmlreplace({
        "css" : "app.min.css",
        "js"  : "app.min.js"
    }))
    .pipe(gulp.dest("dist"));
});

// Copy all the required bower dependencies into /dist
gulp.task("bower_components", function() {
  return gulp.src(["bower_components/angular/angular.min.js",
                   "bower_components/angular-animate/angular-animate.min.js",
                   "bower_components/angular-aria/angular-aria.min.js",
                   "bower_components/angular-material/angular-material.min.js",
                   "bower_components/angular-route/angular-route.min.js",
                   "bower_components/angular-material/angular-material.min.css",
                   "bower_components/font-awesome/**"],
                   {base : "bower_components/"})
    .pipe(gulp.dest("dist/bower_components"));
});

// Move other misc files into /dist
gulp.task("misc", function() {
  return gulp.src(["bower.json", "package.json", "README.md"])
    .pipe(gulp.dest("dist/"));
});

// ---------- Local development build tasks ----------

// Compiles scss into css without minifying so debugging is easier
gulp.task("styles-dev", function() {
  return gulp.src(paths.styles)
    .pipe(concat("app.scss"))
    .pipe(sass().on("error", sass.logError))
    .pipe(rename("app.styles.css"))
    .pipe(gulp.dest("dist"));
});

// ---------- Bump version number tasks ----------

// Pre-release update for bower and npm versions
gulp.task("bump-prerelease", function() {
  gulp.src(["./bower.json", "./package.json"])
  .pipe(bump({
        type  : "prerelease",
        preid : "SNAPSHOT"
    }))
  .pipe(gulp.dest("./"));
});

// Micro update for bower and npm versions
gulp.task("bump-patch", function() {
  gulp.src(["./bower.json", "./package.json"])
  .pipe(bump({
        type : "patch"
    }))
  .pipe(gulp.dest("./"));
});

// Minor update for bower and npm versions
gulp.task("bump-minor", function() {
  gulp.src(["./bower.json", "./package.json"])
  .pipe(bump({
        type : "minor"
    }))
  .pipe(gulp.dest("./"));
});

// Major update for bower and npm versions
gulp.task("bump-major", function() {
  gulp.src(["./bower.json", "./package.json"])
  .pipe(bump({
        type : "major"
    }))
  .pipe(gulp.dest("./"));
});

// ---------- Git tasks ----------

// Tag the git repository using the version number in the package.json
gulp.task("git-tag", function() {
  return gulp.src(["./package.json"])
    .pipe(git.commit("Releasing new version"))
    .pipe(tag_version());
});

// ---------- Watch task ----------

// Rerun tasks when a file changes, for local development
gulp.task("watch", function() {
  gulp.watch(paths.styles, ["styles-dev"]);
});

// ---------- Release tasks ----------

// Dev release
gulp.task("dev-release",   ["code-check", "build"]);
// Check code standards, update the version numbers as
// needed, create the release artefact, tag the branch in git and commit it
gulp.task("micro-release", ["code-check", "bump-patch", "build", "git-tag"]);
gulp.task("minor-release", ["code-check", "bump-minor", "build", "git-tag"]);
gulp.task("major-release", ["code-check", "bump-major", "build", "git-tag"]);

// ---------- Default task ----------

// Compile the scss into css but don"t minify incase of debugging, watch for changes
gulp.task("default", ["code-check", "styles-dev", "watch"]);
<commit_msg>#21 Commenting out temporarily unused gulp dependancy<commit_after>// ---------- Plugins and paths ----------

var gulp = require("gulp"),
    clean = require("gulp-clean"),
    zip = require("gulp-zip"),
    concat = require("gulp-concat"),
    rename = require("gulp-rename"),
    //uglify = require("gulp-uglify"),
    sass = require("gulp-sass"),
    cssnano = require("gulp-cssnano"),
    htmlreplace = require("gulp-html-replace"),
    eslint = require("gulp-eslint"),
    scsslint = require("gulp-scss-lint"),
    bump = require("gulp-bump"),
    git = require("gulp-git"),
    tag_version = require("gulp-tag-version"),
    paths = {
        // All JS files - for linting
        allscripts : ["src/app/**/*.js", "gulpfile.js"],
        // Only source JS files - for building the artefact
        appscripts : ["src/app/app.module.js", "src/app/**/*.js"],
        // All scss files
        styles     : "src/assets/styles/*.scss",
        // All image files
        images     : "src/assets/images/**/*.png",
        // The config settings for the app
        config     : "src/app/app.config.json"
    };

// ---------- Code lint and tidy up tasks ----------

// Clean /dist and remove everything
gulp.task("clean", function () {
  return gulp.src("dist/*", {read:false})
    .pipe(clean({
        force : true
    }));
});

// Check the JS code against ESLint standards
gulp.task("eslint", function() {
  return gulp.src(paths.allscripts).pipe(eslint({
    extends : "eslint:recommended",
    rules : {
        "quotes" : [1, "double"],
        "semi"   : [1, "always"]
    },
    globals : {
        "angular"      : true,
        "keijiban"     : true,
        "window"       : true,
        "baseSlice"    : true,
        "chunk"        : true,
        "buildToggler" : true,
        "require"      : true
    }
  }))
  .pipe(eslint.format())
  .pipe(eslint.failOnError()); // Fail task on lint errors
});

// Check the SCSS code against scss-lint standards
gulp.task("scsslint", function() {
  return gulp.src(paths.styles)
    .pipe(scsslint())
    .pipe(scsslint.failReporter()); // Report failures in the console
});

// Combination task which checks the .js and .scss files against coding standards
gulp.task("code-check", ["eslint", "scsslint"]);

// ---------- Production build tasks ----------

// Build an artefact and zip everything up
gulp.task("build", ["scripts", "bower_components", "styles", "html", "images", "index", "config", "misc"], function() {
  return gulp.src("dist/**/**")
    .pipe(zip("keijiban.zip"))
    .pipe(gulp.dest("dist"));
});

// Combine all the src JS, minify and then uglify
gulp.task("scripts", function() {
  return gulp.src(paths.appscripts)
    .pipe(concat("app.js"))
    .pipe(gulp.dest("dist"))
    .pipe(rename("app.min.js"))
    //.pipe(uglify()) // Causes problems loading bower.json
    .pipe(gulp.dest("dist"));
});

// Combine sccs into one file, compile into css, minify
gulp.task("styles", function() {
  return gulp.src(paths.styles)
    .pipe(sass().on("error", sass.logError)) // Log sass errors
    .pipe(concat("app.min.css"))
    .pipe(cssnano())
    .pipe(gulp.dest("dist"));
});

// Move all the html into /dist
gulp.task("html", function() {
  return gulp.src("src/app/**/*.html")
    .pipe(gulp.dest("dist/src/app"));
});

// Move the images into /dist
gulp.task("images", function() {
  return gulp.src(paths.images)
    .pipe(gulp.dest("dist/src/assets/images/"));
});

// Move the app config into /dist
gulp.task("config", function() {
  return gulp.src(paths.config)
    .pipe(gulp.dest("dist/src/app"));
});

// Move index.html into /dist and replace the filepaths as required
gulp.task("index", function() {
  return gulp.src("index.html")
    .pipe(htmlreplace({
        "css" : "app.min.css",
        "js"  : "app.min.js"
    }))
    .pipe(gulp.dest("dist"));
});

// Copy all the required bower dependencies into /dist
gulp.task("bower_components", function() {
  return gulp.src(["bower_components/angular/angular.min.js",
                   "bower_components/angular-animate/angular-animate.min.js",
                   "bower_components/angular-aria/angular-aria.min.js",
                   "bower_components/angular-material/angular-material.min.js",
                   "bower_components/angular-route/angular-route.min.js",
                   "bower_components/angular-material/angular-material.min.css",
                   "bower_components/font-awesome/**"],
                   {base : "bower_components/"})
    .pipe(gulp.dest("dist/bower_components"));
});

// Move other misc files into /dist
gulp.task("misc", function() {
  return gulp.src(["bower.json", "package.json", "README.md"])
    .pipe(gulp.dest("dist/"));
});

// ---------- Local development build tasks ----------

// Compiles scss into css without minifying so debugging is easier
gulp.task("styles-dev", function() {
  return gulp.src(paths.styles)
    .pipe(concat("app.scss"))
    .pipe(sass().on("error", sass.logError))
    .pipe(rename("app.styles.css"))
    .pipe(gulp.dest("dist"));
});

// ---------- Bump version number tasks ----------

// Pre-release update for bower and npm versions
gulp.task("bump-prerelease", function() {
  gulp.src(["./bower.json", "./package.json"])
  .pipe(bump({
        type  : "prerelease",
        preid : "SNAPSHOT"
    }))
  .pipe(gulp.dest("./"));
});

// Micro update for bower and npm versions
gulp.task("bump-patch", function() {
  gulp.src(["./bower.json", "./package.json"])
  .pipe(bump({
        type : "patch"
    }))
  .pipe(gulp.dest("./"));
});

// Minor update for bower and npm versions
gulp.task("bump-minor", function() {
  gulp.src(["./bower.json", "./package.json"])
  .pipe(bump({
        type : "minor"
    }))
  .pipe(gulp.dest("./"));
});

// Major update for bower and npm versions
gulp.task("bump-major", function() {
  gulp.src(["./bower.json", "./package.json"])
  .pipe(bump({
        type : "major"
    }))
  .pipe(gulp.dest("./"));
});

// ---------- Git tasks ----------

// Tag the git repository using the version number in the package.json
gulp.task("git-tag", function() {
  return gulp.src(["./package.json"])
    .pipe(git.commit("Releasing new version"))
    .pipe(tag_version());
});

// ---------- Watch task ----------

// Rerun tasks when a file changes, for local development
gulp.task("watch", function() {
  gulp.watch(paths.styles, ["styles-dev"]);
});

// ---------- Release tasks ----------

// Dev release
gulp.task("dev-release",   ["code-check", "build"]);
// Check code standards, update the version numbers as
// needed, create the release artefact, tag the branch in git and commit it
gulp.task("micro-release", ["code-check", "bump-patch", "build", "git-tag"]);
gulp.task("minor-release", ["code-check", "bump-minor", "build", "git-tag"]);
gulp.task("major-release", ["code-check", "bump-major", "build", "git-tag"]);

// ---------- Default task ----------

// Compile the scss into css but don"t minify incase of debugging, watch for changes
gulp.task("default", ["code-check", "styles-dev", "watch"]);
<|endoftext|>


<commit_before>// Please visit http://go.microsoft.com/fwlink/?LinkID=761099&clcid=0x409 for more information on settting up Github Webhooks
var request = require('request');

module.exports = function (context, data) {

    const REQUESTS_APP_WEBHOOKS_ENDPOINT = process.env['REQUESTS_APP_WEBHOOKS_ENDPOINT'];
    const AAD_TENANT_GUID = process.env['REACT_APP_TENANT_ID'];
    const AAD_REQUESTS_APP_CLIENT_ID = process.env['REACT_APP_CLIENT_ID'];
    const AAD_REQUESTS_APP_CLIENT_SECRET = process.env['REQUESTS_APP_CLIENT_SECRET'];

    // do nothing if required config settings are missing
    if (!REQUESTS_APP_WEBHOOKS_ENDPOINT || !AAD_TENANT_GUID || !AAD_REQUESTS_APP_CLIENT_ID || !AAD_REQUESTS_APP_CLIENT_SECRET) {
        context.done();
        return;
    }

    const GITHUB_EVENTS_TO_WATCH = (process.env['GITHUB_EVENTS_TO_WATCH'] || '').split(';');
    const GITHUB_LOGINS_TO_WATCH = (process.env['REACT_APP_GITHUB_BOT_LOGIN'] || '').split(';');

    // do nothing if there's nothing to watch
    if (!GITHUB_EVENTS_TO_WATCH || !GITHUB_LOGINS_TO_WATCH || GITHUB_EVENTS_TO_WATCH.length < 1 || GITHUB_LOGINS_TO_WATCH.length < 1) {
        context.done();
        return;
    }

    // do nothing if the incoming data is empty
    if (!context.req || !data) {
        context.done();
        return;
    }

    // only watch specific GitHub events
    // see https://developer.github.com/webhooks/#events
    const gitHubEvent = context.req.headers['x-github-event'] || context.req.headers['X-GitHub-Event'];
    if (!gitHubEvent || GITHUB_EVENTS_TO_WATCH.indexOf(gitHubEvent) < 0) {
        context.done();
        return;
    }

    // only watch specific GitHub logins
    const issueCreatorLogin = data.issue.user.login;
    if (!issueCreatorLogin || GITHUB_LOGINS_TO_WATCH.indexOf(issueCreatorLogin) < 0) {
        context.done();
        return;
    }

    request.post(
        {
            url: `https://login.windows.net/${AAD_TENANT_GUID}/oauth2/token`,
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
                'Cache-Control': 'no-cache'
            },
            formData: {
                'grant_type': 'client_credentials',
                'client_id': AAD_REQUESTS_APP_CLIENT_ID,
                'client_secret': AAD_REQUESTS_APP_CLIENT_SECRET,
                'resource': AAD_REQUESTS_APP_CLIENT_ID
            },
            timeout: 2000
        },
        function (error, response, body) {
            if (error) {
                context.log('failed to get authorization token:', error);
                context.done(error);
            }
            else {
                const tokenResponse = JSON.parse(body);

                request.post({
                    url: REQUESTS_APP_WEBHOOKS_ENDPOINT,
                    headers: {
                        'Content-Type': 'application/json',
                        'Cache-Control': 'no-cache',
                        'X-GitHub-Event': gitHubEvent
                    },
                    auth: {
                        bearer: tokenResponse.access_token,
                        sendImmediately: true
                    },
                    json: data,
                    timeout: 2000
                });

                context.done();
            }
        }
    );
};<commit_msg>Add error messages to `context.done()`<commit_after>// Please visit http://go.microsoft.com/fwlink/?LinkID=761099&clcid=0x409 for more information on settting up Github Webhooks
var request = require('request');

module.exports = function (context, data) {

    // do nothing if the incoming data is empty
    if (!data) {
        context.done();
        return;
    }

    const REQUESTS_APP_WEBHOOKS_ENDPOINT = process.env['REQUESTS_APP_WEBHOOKS_ENDPOINT'];
    if (!REQUESTS_APP_WEBHOOKS_ENDPOINT || REQUESTS_APP_WEBHOOKS_ENDPOINT.length < 1) {
        context.done(`'REQUESTS_APP_WEBHOOKS_ENDPOINT' is either missing or empty`);
        return;
    }

    const AAD_TENANT_GUID = process.env['REACT_APP_TENANT_ID'];
    if (!AAD_TENANT_GUID || AAD_TENANT_GUID.length < 1) {
        context.done(`'AAD_TENANT_GUID' is either missing or empty`);
        return;
    }

    const AAD_REQUESTS_APP_CLIENT_ID = process.env['REACT_APP_CLIENT_ID'];
    if (!AAD_REQUESTS_APP_CLIENT_ID || AAD_REQUESTS_APP_CLIENT_ID.length < 1) {
        context.done(`'AAD_REQUESTS_APP_CLIENT_ID' is either missing or empty`);
        return;
    }

    const AAD_REQUESTS_APP_CLIENT_SECRET = process.env['REQUESTS_APP_CLIENT_SECRET'];
    if (!AAD_REQUESTS_APP_CLIENT_SECRET || AAD_REQUESTS_APP_CLIENT_SECRET.length < 1) {
        context.done(`'REQUESTS_APP_CLIENT_SECRET' is either missing or empty`);
        return;
    }

    const GITHUB_EVENTS_TO_WATCH = (process.env['GITHUB_EVENTS_TO_WATCH'] || '').split(';');
    if (!GITHUB_EVENTS_TO_WATCH || GITHUB_EVENTS_TO_WATCH.length < 1) {
        context.done();
        return;
    }

    const GITHUB_LOGINS_TO_WATCH = (process.env['REACT_APP_GITHUB_BOT_LOGIN'] || '').split(';');
    if (!GITHUB_LOGINS_TO_WATCH || GITHUB_LOGINS_TO_WATCH.length < 1) {
        context.done();
        return;
    }

    // only watch specific GitHub events
    // see https://developer.github.com/webhooks/#events
    const gitHubEvent = context.req.headers['x-github-event'] || context.req.headers['X-GitHub-Event'];
    if (!gitHubEvent || GITHUB_EVENTS_TO_WATCH.indexOf(gitHubEvent) < 0) {
        context.done();
        return;
    }

    // only watch specific GitHub logins
    const issueCreatorLogin = data.issue.user.login;
    if (!issueCreatorLogin || GITHUB_LOGINS_TO_WATCH.indexOf(issueCreatorLogin) < 0) {
        context.done();
        return;
    }

    request.post(
        {
            url: `https://login.windows.net/${AAD_TENANT_GUID}/oauth2/token`,
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
                'Cache-Control': 'no-cache'
            },
            formData: {
                'grant_type': 'client_credentials',
                'client_id': AAD_REQUESTS_APP_CLIENT_ID,
                'client_secret': AAD_REQUESTS_APP_CLIENT_SECRET,
                'resource': AAD_REQUESTS_APP_CLIENT_ID
            },
            timeout: 2000
        },
        function (error, response, body) {
            if (error) {
                context.log('failed to get authorization token:', error);
                context.done(error);
            }
            else {
                const tokenResponse = JSON.parse(body);

                request.post({
                    url: REQUESTS_APP_WEBHOOKS_ENDPOINT,
                    headers: {
                        'Content-Type': 'application/json',
                        'Cache-Control': 'no-cache',
                        'X-GitHub-Event': gitHubEvent
                    },
                    auth: {
                        bearer: tokenResponse.access_token,
                        sendImmediately: true
                    },
                    json: data,
                    timeout: 2000
                });

                context.done();
            }
        }
    );
};<|endoftext|>


<commit_before>// mutator for adding observable properties to a class
addMutator("observable", {
	// the special identifier is "__observable_"
	onCreate : function(klass, parent) {
		var mutator = this;
		// re-assign the observable so that it produces copies across child classes
		klass.observable = extend({}, parent.observable || {});
		// shortcut method for adding observable properties
		klass.addObservableProperty = function(name, property) {
			return klass.addProperty(name, property, mutator.propPrefix);
		};
		// shortcut method for removing observable properties
		klass.removeObservableProperty = function(name) {
			return klass.removeProperty(mutator.propPrefix + name);
		};
	},
	onPropAdd : function(klass, parent, name, property) {
		// add the observable to the internal observable array
		klass.observable[name] = property;
		// we need to add the observable property from all children as well as the current class
		each(klass.subclass, function(k) {
			// add it only if it is not redefined in the child classes
			if (!hasOwn.call(k.observable, name)) {
				k.addObservableProperty(name, property);
			}
		});
	},
	onPropRemove : function(klass, name) {
		// keep a reference to the current observable property
		var tmp = klass.observable[name];
		// we need to delete the observable property from all children as well as the current class
		each(klass.subclass, function(k) {
			// remove it only if it is equal to the parent class
			if (k.observable[name] === tmp) {
				k.removeObservableProperty(name);
			}
		});
		// garbage collection
		klass.observable[name] = null;
		// then try to remove the property
		try {
			delete klass.observable[name];
		} catch (e) {
		}
	},
	onInit : function(instance, klass) {
		var prop, observables = klass.observable || null;
		// if there are no observable properties, just continue
		if (observables === null) {
			return;
		}
		// initialize the observable properties if any
		for (prop in observables) {
			if (hasOwn.call(observables, prop)) {
				instance[prop] = new Observer(instance, prop, observables[prop]);
			}
		}
	}
});
<commit_msg>Attempt to start migration to Object.defineProperty when possible<commit_after>// mutator for adding observable properties to a class
addMutator("observable", {
	// the special identifier is "__observable_"
	onCreate : function(klass, parent) {
		var mutator = this;
		// re-assign the observable so that it produces copies across child classes
		klass.observable = extend({}, parent.observable || {});
		// shortcut method for adding observable properties
		klass.addObservableProperty = function(name, property) {
			return klass.addProperty(name, property, mutator.propPrefix);
		};
		// shortcut method for removing observable properties
		klass.removeObservableProperty = function(name) {
			return klass.removeProperty(mutator.propPrefix + name);
		};
	},
	onPropAdd : function(klass, parent, name, property) {
		// add the observable to the internal observable array
		klass.observable[name] = property;
		// we need to add the observable property from all children as well as the current class
		each(klass.subclass, function(k) {
			// add it only if it is not redefined in the child classes
			if (!hasOwn.call(k.observable, name)) {
				k.addObservableProperty(name, property);
			}
		});
	},
	onPropRemove : function(klass, name) {
		// keep a reference to the current observable property
		var tmp = klass.observable[name];
		// we need to delete the observable property from all children as well as the current class
		each(klass.subclass, function(k) {
			// remove it only if it is equal to the parent class
			if (k.observable[name] === tmp) {
				k.removeObservableProperty(name);
			}
		});
		// garbage collection
		klass.observable[name] = null;
		// then try to remove the property
		try {
			delete klass.observable[name];
		} catch (e) {
		}
	},
	onInit : function(instance, klass) {
		var prop, observables = klass.observable || null;
		// if there are no observable properties, just continue
		if (observables === null) {
			return;
		}
		// initialize the observable properties if any
		for (prop in observables) {
			if (hasOwn.call(observables, prop)) {
				objectDefineProperty(instance, prop, new Observer(instance, prop, observables[prop]));
			}
		}
	}
});
<|endoftext|>


<commit_before>var babel   = require('gulp-babel');
var clean   = require('gulp-rimraf');
var gulp    = require('gulp');
var mocha   = require('gulp-mocha');
var plumber = require('gulp-plumber');

gulp.task('clean', function() {
  return gulp.src([
    'dist/*',
    'lib/*',
    'spec/**/*.js'
  ]).pipe(clean());
});

gulp.task('build', function() {
  return gulp.src('src/**/*.js')
    .pipe(plumber())
    .pipe(babel())
    .pipe(gulp.dest('.'));
});

gulp.task('spec', function() {
  return gulp.src('spec/**/*.js', {read: false})
    .pipe(plumber())
    .pipe(mocha({bail: true}));
});

gulp.task('rebuild', gulp.series(
  'clean', 'build'
));

gulp.task('watch', function() {
  return gulp.watch('src/**/*.js', gulp.series(
    'build', 'spec'
  ));
});

gulp.task('default', gulp.series(
  'rebuild', 'spec', 'watch'
));
<commit_msg>Use del instead of gulp-rimraf<commit_after>var babel   = require('gulp-babel');
var del     = require('del');
var gulp    = require('gulp');
var mocha   = require('gulp-mocha');
var plumber = require('gulp-plumber');

gulp.task('clean', function(cb) {
  return del([
    'dist/*',
    'lib/*',
    'spec/**/*.js'
  ], cb)
});

gulp.task('build', function() {
  return gulp.src('src/**/*.js')
    .pipe(plumber())
    .pipe(babel())
    .pipe(gulp.dest('.'));
});

gulp.task('spec', function() {
  return gulp.src('spec/**/*.js', {read: false})
    .pipe(plumber())
    .pipe(mocha({bail: true}));
});

gulp.task('rebuild', gulp.series(
  'clean', 'build'
));

gulp.task('watch', function() {
  return gulp.watch('src/**/*.js', gulp.series(
    'build', 'spec'
  ));
});

gulp.task('default', gulp.series(
  'rebuild', 'spec', 'watch'
));
<|endoftext|>


<commit_before>/*
  module-shinylogging.js
*/
exports.type = 'event';

var util = require('util');
var toplog = require('../toplog');

var logger = new toplog({concern: 'irc'});
logger.properties.colors.INFO = '37;1';

exports.init = function(config, app, irc, command) {

  /*
    'app.events' event stream:
    these events are sort of system-level: stuff like major IRC events (quit),
    new modules (module.new), ...
    EventEmitter2 lets you listen to wildcard events, eg module.*.
  */
  app.onAny(function() {
    var evt = this.event;

    if (evt == 'module.unload' ||
        evt == 'module.reload') {
        logger.log(evt + ' ' + arguments[1]);
    }

    else if (/^quit\..*/.test(evt)) {
      logger.log('QUITTING ' + evt);
    }

    else if (evt == 'ready') {
      logger.log('ready to join channels!');
    }

    else {
      if (config.loglevel >= 3)
        logger.log(arguments);
    }
  });

  /*
    'app.commandevents' event stream:
    these events fire when someone uses !command. the events contain the exact
    same arguments as one would expect for listener functions in the 'command'
    event type - the respective IRC line, the list of words the user spoke (
    including the command) and the respond function.
  */
  command.onAny(function(ircline) {
    var evt = this.event;
    logger.log('\x1b[37;0m' + ircline.prefix + ' is using ' + evt + '('+ircline.params[1]+')');
  });

  /*
    'app.ircevents' event stream:
    these are IRC lines broadcast as a more palatable format as returned by
    parseIRCLine.

    Say, an event would be Welcome, or PRIVMSG, or other numerics translated
    into appropriate commands. (See constants.json)
  */
  irc.onAny(function(ircline) {
    var evt = this.event;
    if (evt == 'PRIVMSG') {
      // detect /me's
      var text = ircline.params[1];
      if (/\x01ACTION.*\x01/.test(text)) {
        var meText = text.replace('\x01ACTION','').replace('\x01','');
        logger.log(util.format('\x1b[36;1m(%s) * %s %s\x1b[0m',
                    ircline.params[0], ircline.channel, meText));
      }
      else {
        logger.log(util.format('\x1b[37;1m(%s) <%s> %s\x1b[0m',
                    ircline.params[0], ircline.nick, text));
      }
    }

    else if (evt == 'JOIN') {
      logger.log(util.format('\x1b[36;1m%s (%s) joined %s (%s)\x1b[0m',
                  ircline.nick, ircline.prefix, ircline.params[0],
                  ircline.params[1]));
    }
    else if (evt == 'PART') {
      logger.log(util.format('\x1b[36;1m%s (%s) left %s (%s)\x1b[0m',
                  ircline.nick, ircline.prefix, ircline.params[0],
                  ircline.params[1]));
    }
    else if (evt == 'QUIT') {
      logger.log(util.format('\x1b[36;1m%s (%s) quit (%s)\x1b[0m',
                  ircline.nick, ircline.prefix, ircline.params[0]));
    }
    else if (evt == 'PING') {
      logger.log('\x1b[37;1mpong!\x1b[0m');
    }
    else {
      if (config.loglevel >= 3) {
        logger.log('\x1b[33;1mapp.ircevents emitted: ' + this.event,
          arguments, '\x1b[0m');
      }
    }
  });
};
<commit_msg>add new sections to shinylogging so more events get pretty logs<commit_after>/*
  module-shinylogging.js
*/
exports.type = 'event';

var util = require('util');
var toplog = require('../toplog');

var logger = new toplog({concern: 'irc'});
logger.properties.colors.INFO = '37;1';

// events for which we'll just log all parameters
var ircEventParamLog = ['ISupport', 'MOTD', 'EndOfMOTD', 'LUserChannels',
    'LUserClient', 'LUserMe', 'MyInfo', 'Welcome', 'YourHost', 'NamReply',
    'EndOfNames', 'Created'];

exports.init = function(app, irc, command, u) {

  app.onAny(function() {
    var evt = this.event;

    if (evt == 'module.unload' ||
        evt == 'module.reload') {
        logger.verbose(evt + ' ' + arguments[1]);
    }

    else if (/^quit\..*/.test(evt)) {
      logger.verbose('(app) QUITTING ' + evt);
    }

    else if (evt == 'ready') {
      logger.verbose('(app) ready to join channels!');
    }

    else {
      if (u.config.get('loglevel') >= 3 && evt != 'sock.data')
        logger.verbose('(app) ' + evt + ' ' + arguments);
    }
  });

  command.onAny(function(ircline) {
    var evt = this.event;
    debugger;
    logger.verbose('\x1b[37;0m' + ircline.prefix + ' is using ' + evt + '('+ircline.params[1]+')');
  });

  irc.onAny(function(ircline) {
    var evt = this.event;

    // Channel / private messages
    if (evt == 'PRIVMSG') {
      // detect /me's
      var text = ircline.params[1];
      if (/\x01ACTION.*\x01/.test(text)) {
        var meText = text.replace('\x01ACTION','').replace('\x01','');
        logger.verbose(util.format('\x1b[36;1m(%s) * %s %s\x1b[0m',
                    ircline.params[0], ircline.nick, meText));
      }
      else {
        logger.verbose(util.format('\x1b[37;1m(%s) <%s> %s\x1b[0m',
                    ircline.params[0], ircline.nick, text));
      }
    }

    // Channel / user notices
    else if (evt == 'NOTICE') {

      var target = ircline.nick || ircline.prefix;

      var mynick = u.config.get('nick', 'boxnode');
      if (ircline.params[0] !== mynick) {
        target += '/' + ircline.params[0];
      }
      logger.verbose(util.format('\x1b[36;1m-%s- %s\x1b[0m', target, ircline.params[1]));
    }

    // Joins / parts / quits
    else if (evt == 'JOIN') {
      logger.verbose(util.format('\x1b[36;1m%s (%s) joined %s\x1b[0m',
                  ircline.nick, ircline.prefix, ircline.params[0]));
    }
    else if (evt == 'PART') {
      logger.verbose(util.format('\x1b[36;1m%s (%s) left %s (%s)\x1b[0m',
                  ircline.nick, ircline.prefix, ircline.params[0],
                  ircline.params[1]));
    }
    else if (evt == 'QUIT') {
      logger.verbose(util.format('\x1b[36;1m%s (%s) quit (%s)\x1b[0m',
                  ircline.nick, ircline.prefix, ircline.params[0]));
    }

    // Ping replies
    else if (evt == 'PING') {
      logger.verbose('\x1b[37;1mpong!\x1b[0m');
    }

    // MOTD
    else if (evt == 'MOTD' || evt == 'EndOfMOTD' || evt == 'MOTDStart') {
      logger.verbose(evt+':', ircline.params[0], ircline.params[1]);
    }

    // various pointless messages
    else if (ircEventParamLog.indexOf(evt) !== -1) {
      logger.verbose('*** ' + evt, ircline.params.join(' '));
    }

    // Default logging is very loud
    else {
      if (u.config.get('loglevel') >= 3) {
        logger.verbose('\x1b[33;1mapp.ircevents emitted: ' + this.event + ' ' +
          util.inspect(arguments) + '\x1b[0m');
      }
    }
  });
};
<|endoftext|>


<commit_before>var gulp = require('gulp');
var filter = require('gulp-filter');
var jade = require('gulp-jade');
var rename = require("gulp-rename");
var strip = require('gulp-strip-comments');
var typescript = require('gulp-typescript');
var watch = require('gulp-watch');
var exec = require('child_process').exec;
var fork = require('child_process').fork;
var karma = require('karma').Server;
var path = require('path');
var runSequence = require('run-sequence');
var through2 = require('through2');

var APP_NAME = 'ngReactNative';
var PATHS = {
  sources: {
    doc: 'doc/pages/*.jade',
    src: 'src/**/*.ts',
    sample: 'sample/**/*.ts',
    sampleAssets: 'sample/**/*.png',
    test: 'test/**/*.ts'
  },
  destination: 'dist/code',
  app: 'dist/app',
  doc: 'dist/doc',
  modules: [
    'node_modules/angular2/**/*',
    'node_modules/es6-shim/**/*',
    'node_modules/hammerjs/**/*',
    'node_modules/reflect-metadata/**/*',
    'node_modules/rxjs/**/*',
    'node_modules/zone.js/**/*'
  ]
};

/**********************************************************************************/
/*******************************   SAMPLE    **************************************/
/**********************************************************************************/
gulp.task('clean', function (done) {
  var del = require('del');
  del([PATHS.app], done);
});
gulp.task('!create', ['clean'], function(done) {
  executeInAppDir('react-native init ' + APP_NAME, done, true);
});
gulp.task('!postcreate', ['!create'], function() {
  return gulp.src(PATHS.app + '/' + APP_NAME + '/android/app/src/main/AndroidManifest.xml')
    .pipe(transformAndroidManifest())
    .pipe(gulp.dest(PATHS.app + '/' + APP_NAME + '/android/app/src/main/'));

});
gulp.task('init', ['!postcreate'], function() {
  var filterJS = filter('angular2/**/*.js', {restore: true});
  //TODO: remove hack once Babbel is somehow fixed
  var tmpHack = filter('rxjs/util/SymbolShim.js', {restore: true});
  var tmpHack2 = filter('reflect-metadata/Reflect.js', {restore: true});
  return gulp.src(PATHS.modules, { base: './node_modules/' })
  .pipe(filterJS)
  .pipe(strip())
  .pipe(filterJS.restore)
  .pipe(tmpHack)
  .pipe(transformSymbolShim())
  .pipe(tmpHack.restore)
  .pipe(tmpHack2)
  .pipe(transformReflect())
  .pipe(tmpHack2.restore)
  .pipe(gulp.dest(PATHS.app + '/' + APP_NAME + '/node_modules'));
});

gulp.task('!assets', function () {
  return gulp.src(PATHS.sources.sampleAssets).pipe(gulp.dest(PATHS.app + '/' + APP_NAME));
});
gulp.task('!compile', ['!assets'], function () {
  ts2js(PATHS.sources.sample, PATHS.app + '/' + APP_NAME);
  return ts2js(PATHS.sources.src, PATHS.app + '/' + APP_NAME + '/node_modules/react-native-renderer');
});
gulp.task('!launch.android', ['!compile'], function(done) {
  executeInAppDir('react-native run-android', done);
});
gulp.task('!launch.ios', ['!compile'], function(done) {
  executeInAppDir('react-native run-ios', done);
});
gulp.task('!start.android', ['!launch.android'], function(neverDone) {
  if (/^win/.test(process.platform)) {
    executeInAppDir('react-native start');
  }
});
gulp.task('watch', function(neverDone) {
  watch([PATHS.sources.src, PATHS.sources.sample], function() {
    runSequence('!compile');
  });
});
gulp.task('start.android', ['!start.android', 'watch'], function (neverDone) {
});
gulp.task('start.ios', ['!launch.ios', 'watch'], function (neverDone) {
});

function executeInAppDir(command, done, inParentFolder) {
  var cmd = 'mkdir -p dist' + path.sep + 'app';
  exec(cmd, function(e, stdout) {
    var dir = './dist/app';
    if (!inParentFolder) dir += '/' + APP_NAME;
    exec(command, {cwd: dir, maxBuffer: 5000 * 1024}, function(e, stdout) {
      if (e) console.log(e);
      if (done) done();
    }).stdout.on('data', function(data) {
      console.log(data);
    });
  });
}

/**********************************************************************************/
/*******************************    NODE     **************************************/
/**********************************************************************************/
gulp.task('ts2commonjs', ['clean.code'], function () {
  ts2js(PATHS.sources.sample, PATHS.destination + '/sample');
  ts2js(PATHS.sources.test, PATHS.destination + '/test', false);
  return ts2js(PATHS.sources.src, PATHS.destination + '/src');
});

gulp.task('transformTests', ['ts2commonjs'], function() {
  return gulp.src(PATHS.destination + '/test/**/*_spec.js')
    .pipe(transformCommonJSTests())
    .pipe(gulp.dest(PATHS.destination + '/test'));
});

var treatTestErrorsAsFatal = true;
gulp.task('test.node/ci', ['transformTests'], function(done) {
  runJasmine([PATHS.destination + '/test/**/*_spec.js'], done);
});

gulp.task('test.node', function(neverDone) {
  treatTestErrorsAsFatal = false;
  runSequence(
    'test.node/ci',
    function() {
      watch([PATHS.sources.src, PATHS.sources.test], function() {
        runSequence('test.node/ci');
      });
    }
  );
});

/**********************************************************************************/
/*******************************   BROWSER   **************************************/
/**********************************************************************************/
gulp.task('ts2system', ['clean.code'], function () {
  ts2js(PATHS.sources.sample, PATHS.destination + '/sample', true);
  ts2js(PATHS.sources.test, PATHS.destination + '/test', true);
  return ts2js(PATHS.sources.src, PATHS.destination + '/src', true);
});

gulp.task('karma-launch', function() {
  new karma({
    configFile: path.join(__dirname, 'karma.conf.js')
  }).start();
});

gulp.task('karma-run', function (done) {
  runKarma('karma.conf.js', done);
});

gulp.task('test.browser', ['ts2system'], function (neverDone) {
  runSequence(
    'karma-launch',
    function() {
      watch([PATHS.sources.src, PATHS.sources.test], function() {
        runSequence('ts2system', 'karma-run');
      });
    }
  );
});

gulp.task('test.browser/ci', ['ts2system'], function(done) {
  new karma({
    configFile: path.join(__dirname, 'karma.conf.js'),
    singleRun: true
  }, done).start();
});

/**********************************************************************************/
/*********************************   DOC    ***************************************/
/**********************************************************************************/
var parser = require('./doc/parser');
gulp.task('!doc', function() {
  var components = parser.parseComponents();
  gulp.src(PATHS.sources.doc)
    .pipe(jade({
      locals: {components: components}
    }))
    .pipe(gulp.dest(PATHS.doc));
  for (var key in components) {
    var name = components[key].description.name.toLowerCase();
    gulp.src('doc/template/component.jade')
      .pipe(rename(name + '.html'))
      .pipe(jade({
        locals: {components: components, component: components[key]}
      }))
      .pipe(gulp.dest(PATHS.doc));
  }
});

gulp.task('doc', ['!doc'], function (neverDone) {
      watch(['./doc/**/*', PATHS.sources.src], function() {
        runSequence('!doc');
      });
});

/**********************************************************************************/
/*******************************    UTIL     **************************************/
/**********************************************************************************/
gulp.task('clean.code', function (done) {
  var del = require('del');
  del([PATHS.destination], done);
});

function ts2js(path, dest, toSystem) {
  var tsResult = gulp.src([path].concat(['typings/main.d.ts', 'src/react-native-renderer.d.ts']))
    .pipe(typescript({
      noImplicitAny: true,
      module: toSystem ? 'system' : 'commonjs',
      target: 'ES5',
      moduleResolution: 'node',
      emitDecoratorMetadata: true,
      experimentalDecorators: true
    },
      undefined,
      customReporter()));
  return tsResult.js.pipe(gulp.dest(dest));
}

function runKarma(configFile, done) {
  var cmd = process.platform === 'win32' ? 'node_modules\\.bin\\karma run ' :
    'node node_modules/.bin/karma run ';
  cmd += configFile;
  exec(cmd, function(e, stdout) {
    // ignore errors, we don't want to fail the build in the interactive (non-ci) mode
    // karma server will print all test failures
    done();
  });
}

function runJasmine(globs, done) {
  var args = ['--'].concat(globs);
  fork('./jasmine-test-shim', args, {stdio: 'inherit'})
    .on('close', function jasmineCloseHandler(exitCode) {
      if (exitCode && treatTestErrorsAsFatal) {
        var err = new Error('Jasmine tests failed');
        // Mark the error for gulp similar to how gulp-utils.PluginError does it.
        // The stack is not useful in this context.
        err.showStack = false;
        done(err);
      } else {
        done();
      }
    });
}

function transformCommonJSTests() {
  return through2.obj(function (file, encoding, done) {
    var content = `var parse5Adapter = require('angular2/src/platform/server/parse5_adapter');\r\n` +
      `parse5Adapter.Parse5DomAdapter.makeCurrent();\r\n` + String(file.contents);
    file.contents = new Buffer(content);
    this.push(file);
    done();
  });
}

function transformSymbolShim() {
  return through2.obj(function (file, encoding, done) {
    file.contents = new Buffer(fixedSymbolShim);
    this.push(file);
    done();
  });
}

function transformReflect() {
  return through2.obj(function (file, encoding, done) {
    var content = String(file.contents).replace('&& require("crypto")', '');
    file.contents = new Buffer(content);
    this.push(file);
    done();
  });
}

function transformAndroidManifest() {
  return through2.obj(function (file, encoding, done) {
    var content = String(file.contents);
    content = content.replace('<uses-permission android:name="android.permission.INTERNET" />',
    `<uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />`);
    file.contents = new Buffer(content);
    this.push(file);
    done();
  });
}

function customReporter() {
  return {
    error: (error) => {
      if (error.relativeFilename && error.message.indexOf(`Module '"react-native"' has no exported member`) == -1 &&
        error.message.indexOf(`Module '"react-native-renderer/react-native-renderer"' has no exported member`) == -1 &&
        error.message.indexOf(`src\\react-native-renderer.d.ts`) == -1 &&
        error.message.indexOf(`does not exist on type 'Global'.`) == -1) {
        console.error(error.message);
      }
    },
    finish: typescript.reporter.defaultFinishHandler
  };
}

var fixedSymbolShim = `var root_1 = require('./root');
function polyfillSymbol(root) {
    var Symbol = ensureSymbol(root);
    ensureIterator(Symbol, root);
    ensureObservable(Symbol);
    ensureFor(Symbol);
    return Symbol;
}
exports.polyfillSymbol = polyfillSymbol;
function ensureFor(Symboll) {
    if (!Symboll.for) {
        Symboll.for = symbolForPolyfill;
    }
}
exports.ensureFor = ensureFor;
var id = 0;
function ensureSymbol(root) {
    if (!root.Symbol) {
        root.Symbol = function symbolFuncPolyfill(description) {
            return "@@Symbol(" + description + "):" + id++;
        };
    }
    return root.Symbol;
}
exports.ensureSymbol = ensureSymbol;
function symbolForPolyfill(key) {
    return '@@' + key;
}
exports.symbolForPolyfill = symbolForPolyfill;
function ensureIterator(Symboll, root) {
    if (!Symboll.iterator) {
        if (typeof Symboll.for === 'function') {
            Symboll.iterator = Symboll.for('iterator');
        }
        else if (root.Set && typeof new root.Set()['@@iterator'] === 'function') {
            // Bug for mozilla version
            Symboll.iterator = '@@iterator';
        }
        else if (root.Map) {
            // es6-shim specific logic
            var keys = Object.getOwnPropertyNames(root.Map.prototype);
            for (var i = 0; i < keys.length; ++i) {
                var key = keys[i];
                if (key !== 'entries' && key !== 'size' && root.Map.prototype[key] === root.Map.prototype['entries']) {
                    Symboll.iterator = key;
                    break;
                }
            }
        }
        else {
            Symboll.iterator = '@@iterator';
        }
    }
}
exports.ensureIterator = ensureIterator;
function ensureObservable(Symboll) {
    if (!Symboll.observable) {
        if (typeof Symboll.for === 'function') {
            Symboll.observable = Symboll.for('observable');
        }
        else {
            Symboll.observable = '@@observable';
        }
    }
}
exports.ensureObservable = ensureObservable;
exports.SymbolShim = polyfillSymbol(root_1.root);
//# sourceMappingURL=SymbolShim.js.map`;
<commit_msg>build(gulp): fix race condition when running tests<commit_after>var gulp = require('gulp');
var filter = require('gulp-filter');
var jade = require('gulp-jade');
var rename = require("gulp-rename");
var strip = require('gulp-strip-comments');
var typescript = require('gulp-typescript');
var watch = require('gulp-watch');
var exec = require('child_process').exec;
var fork = require('child_process').fork;
var karma = require('karma').Server;
var path = require('path');
var runSequence = require('run-sequence');
var through2 = require('through2');

var APP_NAME = 'ngReactNative';
var PATHS = {
  sources: {
    doc: 'doc/pages/*.jade',
    src: 'src/**/*.ts',
    sample: 'sample/**/*.ts',
    sampleAssets: 'sample/**/*.png',
    test: 'test/**/*.ts'
  },
  destination: 'dist/code',
  app: 'dist/app',
  doc: 'dist/doc',
  modules: [
    'node_modules/angular2/**/*',
    'node_modules/es6-shim/**/*',
    'node_modules/hammerjs/**/*',
    'node_modules/reflect-metadata/**/*',
    'node_modules/rxjs/**/*',
    'node_modules/zone.js/**/*'
  ]
};

/**********************************************************************************/
/*******************************   SAMPLE    **************************************/
/**********************************************************************************/
gulp.task('clean', function (done) {
  var del = require('del');
  del([PATHS.app], done);
});
gulp.task('!create', ['clean'], function(done) {
  executeInAppDir('react-native init ' + APP_NAME, done, true);
});
gulp.task('!postcreate', ['!create'], function() {
  return gulp.src(PATHS.app + '/' + APP_NAME + '/android/app/src/main/AndroidManifest.xml')
    .pipe(transformAndroidManifest())
    .pipe(gulp.dest(PATHS.app + '/' + APP_NAME + '/android/app/src/main/'));

});
gulp.task('init', ['!postcreate'], function() {
  var filterJS = filter('angular2/**/*.js', {restore: true});
  //TODO: remove hack once Babbel is somehow fixed
  var tmpHack = filter('rxjs/util/SymbolShim.js', {restore: true});
  var tmpHack2 = filter('reflect-metadata/Reflect.js', {restore: true});
  return gulp.src(PATHS.modules, { base: './node_modules/' })
  .pipe(filterJS)
  .pipe(strip())
  .pipe(filterJS.restore)
  .pipe(tmpHack)
  .pipe(transformSymbolShim())
  .pipe(tmpHack.restore)
  .pipe(tmpHack2)
  .pipe(transformReflect())
  .pipe(tmpHack2.restore)
  .pipe(gulp.dest(PATHS.app + '/' + APP_NAME + '/node_modules'));
});

gulp.task('!assets', function () {
  return gulp.src(PATHS.sources.sampleAssets).pipe(gulp.dest(PATHS.app + '/' + APP_NAME));
});
gulp.task('!compile', ['!assets'], function () {
  ts2js(PATHS.sources.sample, PATHS.app + '/' + APP_NAME);
  return ts2js(PATHS.sources.src, PATHS.app + '/' + APP_NAME + '/node_modules/react-native-renderer');
});
gulp.task('!launch.android', ['!compile'], function(done) {
  executeInAppDir('react-native run-android', done);
});
gulp.task('!launch.ios', ['!compile'], function(done) {
  executeInAppDir('react-native run-ios', done);
});
gulp.task('!start.android', ['!launch.android'], function(neverDone) {
  if (/^win/.test(process.platform)) {
    executeInAppDir('react-native start');
  }
});
gulp.task('watch', function(neverDone) {
  watch([PATHS.sources.src, PATHS.sources.sample], function() {
    runSequence('!compile');
  });
});
gulp.task('start.android', ['!start.android', 'watch'], function (neverDone) {
});
gulp.task('start.ios', ['!launch.ios', 'watch'], function (neverDone) {
});

function executeInAppDir(command, done, inParentFolder) {
  var cmd = 'mkdir -p dist' + path.sep + 'app';
  exec(cmd, function(e, stdout) {
    var dir = './dist/app';
    if (!inParentFolder) dir += '/' + APP_NAME;
    exec(command, {cwd: dir, maxBuffer: 5000 * 1024}, function(e, stdout) {
      if (e) console.log(e);
      if (done) done();
    }).stdout.on('data', function(data) {
      console.log(data);
    });
  });
}

/**********************************************************************************/
/*******************************    NODE     **************************************/
/**********************************************************************************/
gulp.task('ts2commonjs.sample', function () {
  return ts2js(PATHS.sources.sample, PATHS.destination + '/sample');
});
gulp.task('ts2commonjs.test', function () {
  return ts2js(PATHS.sources.test, PATHS.destination + '/test');
});
gulp.task('ts2commonjs.src', function () {
  return ts2js(PATHS.sources.src, PATHS.destination + '/src');
});
gulp.task('ts2commonjs', function (done) {
  runSequence('clean.code', ['ts2commonjs.sample', 'ts2commonjs.test', 'ts2commonjs.src'], done);
});

gulp.task('transformTests', ['ts2commonjs'], function() {
  return gulp.src(PATHS.destination + '/test/**/*_spec.js')
    .pipe(transformCommonJSTests())
    .pipe(gulp.dest(PATHS.destination + '/test'));
});

var treatTestErrorsAsFatal = true;
gulp.task('test.node/ci', ['transformTests'], function(done) {
  runJasmine([PATHS.destination + '/test/**/*_spec.js'], done);
});

gulp.task('test.node', function(neverDone) {
  treatTestErrorsAsFatal = false;
  runSequence(
    'test.node/ci',
    function() {
      watch([PATHS.sources.src, PATHS.sources.test], function() {
        runSequence('test.node/ci');
      });
    }
  );
});

/**********************************************************************************/
/*******************************   BROWSER   **************************************/
/**********************************************************************************/
gulp.task('ts2system.sample', function () {
  return ts2js(PATHS.sources.sample, PATHS.destination + '/sample', true);
});
gulp.task('ts2system.test', function () {
  return ts2js(PATHS.sources.test, PATHS.destination + '/test', true);
});
gulp.task('ts2system.src', function () {
  return ts2js(PATHS.sources.src, PATHS.destination + '/src', true);
});
gulp.task('ts2system', function (done) {
  runSequence('clean.code', ['ts2system.sample', 'ts2system.test', 'ts2system.src'], done);
});

gulp.task('karma-launch', function() {
  new karma({
    configFile: path.join(__dirname, 'karma.conf.js')
  }).start();
});

gulp.task('karma-run', function (done) {
  runKarma('karma.conf.js', done);
});

gulp.task('test.browser', ['ts2system'], function (neverDone) {
  runSequence(
    'karma-launch',
    function() {
      watch([PATHS.sources.src, PATHS.sources.test], function() {
        runSequence('ts2system', 'karma-run');
      });
    }
  );
});

gulp.task('test.browser/ci', ['ts2system'], function(done) {
  new karma({
    configFile: path.join(__dirname, 'karma.conf.js'),
    singleRun: true
  }, done).start();
});

/**********************************************************************************/
/*********************************   DOC    ***************************************/
/**********************************************************************************/
var parser = require('./doc/parser');
gulp.task('!doc', function() {
  var components = parser.parseComponents();
  gulp.src(PATHS.sources.doc)
    .pipe(jade({
      locals: {components: components}
    }))
    .pipe(gulp.dest(PATHS.doc));
  for (var key in components) {
    var name = components[key].description.name.toLowerCase();
    gulp.src('doc/template/component.jade')
      .pipe(rename(name + '.html'))
      .pipe(jade({
        locals: {components: components, component: components[key]}
      }))
      .pipe(gulp.dest(PATHS.doc));
  }
});

gulp.task('doc', ['!doc'], function (neverDone) {
      watch(['./doc/**/*', PATHS.sources.src], function() {
        runSequence('!doc');
      });
});

/**********************************************************************************/
/*******************************    UTIL     **************************************/
/**********************************************************************************/
gulp.task('clean.code', function (done) {
  var del = require('del');
  del([PATHS.destination], done);
});

function ts2js(path, dest, toSystem) {
  var tsResult = gulp.src([path].concat(['typings/main.d.ts', 'src/react-native-renderer.d.ts']))
    .pipe(typescript({
      noImplicitAny: true,
      module: toSystem ? 'system' : 'commonjs',
      target: 'ES5',
      moduleResolution: 'node',
      emitDecoratorMetadata: true,
      experimentalDecorators: true
    },
      undefined,
      customReporter()));
  return tsResult.js.pipe(gulp.dest(dest));
}

function runKarma(configFile, done) {
  var cmd = process.platform === 'win32' ? 'node_modules\\.bin\\karma run ' :
    'node node_modules/.bin/karma run ';
  cmd += configFile;
  exec(cmd, function(e, stdout) {
    // ignore errors, we don't want to fail the build in the interactive (non-ci) mode
    // karma server will print all test failures
    done();
  });
}

function runJasmine(globs, done) {
  var args = ['--'].concat(globs);
  fork('./jasmine-test-shim', args, {stdio: 'inherit'})
    .on('close', function jasmineCloseHandler(exitCode) {
      if (exitCode && treatTestErrorsAsFatal) {
        var err = new Error('Jasmine tests failed');
        // Mark the error for gulp similar to how gulp-utils.PluginError does it.
        // The stack is not useful in this context.
        err.showStack = false;
        done(err);
      } else {
        done();
      }
    });
}

function transformCommonJSTests() {
  return through2.obj(function (file, encoding, done) {
    var content = `var parse5Adapter = require('angular2/src/platform/server/parse5_adapter');\r\n` +
      `parse5Adapter.Parse5DomAdapter.makeCurrent();\r\n` + String(file.contents);
    file.contents = new Buffer(content);
    this.push(file);
    done();
  });
}

function transformSymbolShim() {
  return through2.obj(function (file, encoding, done) {
    file.contents = new Buffer(fixedSymbolShim);
    this.push(file);
    done();
  });
}

function transformReflect() {
  return through2.obj(function (file, encoding, done) {
    var content = String(file.contents).replace('&& require("crypto")', '');
    file.contents = new Buffer(content);
    this.push(file);
    done();
  });
}

function transformAndroidManifest() {
  return through2.obj(function (file, encoding, done) {
    var content = String(file.contents);
    content = content.replace('<uses-permission android:name="android.permission.INTERNET" />',
    `<uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />`);
    file.contents = new Buffer(content);
    this.push(file);
    done();
  });
}

function customReporter() {
  return {
    error: (error) => {
      if (error.relativeFilename && error.message.indexOf(`Module '"react-native"' has no exported member`) == -1 &&
        error.message.indexOf(`Module '"react-native-renderer/react-native-renderer"' has no exported member`) == -1 &&
        error.message.indexOf(`src\\react-native-renderer.d.ts`) == -1 &&
        error.message.indexOf(`does not exist on type 'Global'.`) == -1) {
        console.error(error.message);
      }
    },
    finish: typescript.reporter.defaultFinishHandler
  };
}

var fixedSymbolShim = `var root_1 = require('./root');
function polyfillSymbol(root) {
    var Symbol = ensureSymbol(root);
    ensureIterator(Symbol, root);
    ensureObservable(Symbol);
    ensureFor(Symbol);
    return Symbol;
}
exports.polyfillSymbol = polyfillSymbol;
function ensureFor(Symboll) {
    if (!Symboll.for) {
        Symboll.for = symbolForPolyfill;
    }
}
exports.ensureFor = ensureFor;
var id = 0;
function ensureSymbol(root) {
    if (!root.Symbol) {
        root.Symbol = function symbolFuncPolyfill(description) {
            return "@@Symbol(" + description + "):" + id++;
        };
    }
    return root.Symbol;
}
exports.ensureSymbol = ensureSymbol;
function symbolForPolyfill(key) {
    return '@@' + key;
}
exports.symbolForPolyfill = symbolForPolyfill;
function ensureIterator(Symboll, root) {
    if (!Symboll.iterator) {
        if (typeof Symboll.for === 'function') {
            Symboll.iterator = Symboll.for('iterator');
        }
        else if (root.Set && typeof new root.Set()['@@iterator'] === 'function') {
            // Bug for mozilla version
            Symboll.iterator = '@@iterator';
        }
        else if (root.Map) {
            // es6-shim specific logic
            var keys = Object.getOwnPropertyNames(root.Map.prototype);
            for (var i = 0; i < keys.length; ++i) {
                var key = keys[i];
                if (key !== 'entries' && key !== 'size' && root.Map.prototype[key] === root.Map.prototype['entries']) {
                    Symboll.iterator = key;
                    break;
                }
            }
        }
        else {
            Symboll.iterator = '@@iterator';
        }
    }
}
exports.ensureIterator = ensureIterator;
function ensureObservable(Symboll) {
    if (!Symboll.observable) {
        if (typeof Symboll.for === 'function') {
            Symboll.observable = Symboll.for('observable');
        }
        else {
            Symboll.observable = '@@observable';
        }
    }
}
exports.ensureObservable = ensureObservable;
exports.SymbolShim = polyfillSymbol(root_1.root);
//# sourceMappingURL=SymbolShim.js.map`;
<|endoftext|>