<commit_before>// ==========================================================================
// Gulp build script
// ==========================================================================
/* eslint no-console: "off" */

const path = require('path');
const gulp = require('gulp');
// ------------------------------------
// JavaScript
// ------------------------------------
const terser = require('gulp-terser');
const rollup = require('gulp-better-rollup');
const babel = require('rollup-plugin-babel');
const commonjs = require('rollup-plugin-commonjs');
const resolve = require('rollup-plugin-node-resolve');
// ------------------------------------
// CSS
// ------------------------------------
const sass = require('gulp-sass');
const clean = require('gulp-clean-css');
const prefix = require('gulp-autoprefixer');
// ------------------------------------
// Images
// ------------------------------------
const svgstore = require('gulp-svgstore');
const imagemin = require('gulp-imagemin');
// ------------------------------------
// Utils
// ------------------------------------
const del = require('del');
const filter = require('gulp-filter');
const header = require('gulp-header');
const gitbranch = require('git-branch');
const rename = require('gulp-rename');
const replace = require('gulp-replace');
const ansi = require('ansi-colors');
const log = require('fancy-log');
const open = require('gulp-open');
const plumber = require('gulp-plumber');
const size = require('gulp-size');
const sourcemaps = require('gulp-sourcemaps');
const through = require('through2');
const browserSync = require('browser-sync').create();
// ------------------------------------
// Deployment
// ------------------------------------
const aws = require('aws-sdk');
const publish = require('gulp-awspublish');
const FastlyPurge = require('fastly-purge');
// ------------------------------------
// Configs
// ------------------------------------
const pkg = require('./package.json');
const build = require('./build.json');
const deploy = require('./deploy.json');
// ------------------------------------
// Info from package
// ------------------------------------
const { browserslist: browsers, version } = pkg;
const minSuffix = '.min';

// Get AWS config
Object.values(deploy).forEach(target => {
    Object.assign(target, {
        publisher: publish.create({
            region: target.region,
            params: {
                Bucket: target.bucket,
            },
            credentials: new aws.SharedIniFileCredentials({ profile: 'plyr' }),
        }),
    });
});

// Paths
const paths = {
    plyr: {
        // Source paths
        src: {
            sass: path.join(__dirname, 'src/sass/**/*.scss'),
            js: path.join(__dirname, 'src/js/**/*.js'),
            sprite: path.join(__dirname, 'src/sprite/*.svg'),
        },

        // Output paths
        output: path.join(__dirname, 'dist/'),
    },
    demo: {
        // Source paths
        src: {
            sass: path.join(__dirname, 'demo/src/sass/**/*.scss'),
            js: path.join(__dirname, 'demo/src/js/**/*.js'),
        },

        // Output paths
        output: path.join(__dirname, 'demo/dist/'),

        // Demo
        root: path.join(__dirname, 'demo/'),
    },
    upload: [
        path.join(__dirname, `dist/*${minSuffix}.*`),
        path.join(__dirname, 'dist/*.css'),
        path.join(__dirname, 'dist/*.svg'),
        path.join(__dirname, `demo/dist/*${minSuffix}.*`),
        path.join(__dirname, 'demo/dist/*.css'),
        path.join(__dirname, 'demo/dist/*.svg'),
    ],
};

// Task arrays
const tasks = {
    css: [],
    js: [],
    sprite: [],
    clean: 'clean',
};

// Size plugin
const sizeOptions = { showFiles: true, gzip: true };

// Clean out /dist
gulp.task(tasks.clean, done => {
    const dirs = [paths.plyr.output, paths.demo.output].map(dir => path.join(dir, '**/*'));

    // Don't delete the mp4
    dirs.push(`!${path.join(paths.plyr.output, '**/*.mp4')}`);

    del(dirs);

    done();
});

// JavaScript
Object.entries(build.js).forEach(([filename, entry]) => {
    const { dist, formats, namespace, polyfill, src } = entry;

    formats.forEach(format => {
        const name = `js:${filename}:${format}`;
        const extension = format === 'es' ? 'mjs' : 'js';
        tasks.js.push(name);

        gulp.task(name, () =>
            gulp
                .src(src)
                .pipe(plumber())
                .pipe(sourcemaps.init())
                .pipe(
                    rollup(
                        {
                            plugins: [
                                resolve(),
                                commonjs(),
                                babel({
                                    presets: [
                                        [
                                            '@babel/env',
                                            {
                                                // debug: true,
                                                useBuiltIns: polyfill ? 'usage' : false,
                                                corejs: polyfill ? 3 : undefined,
                                            },
                                        ],
                                    ],
                                    babelrc: false,
                                    exclude: [/\/core-js\//],
                                }),
                            ],
                        },
                        {
                            name: namespace,
                            format,
                        },
                    ),
                )
                .pipe(header('typeof navigator === "object" && ')) // "Support" SSR (#935)
                .pipe(
                    rename({
                        extname: `.${extension}`,
                    }),
                )
                .pipe(gulp.dest(dist))
                .pipe(filter(`**/*.${extension}`))
                .pipe(terser())
                .pipe(rename({ suffix: minSuffix }))
                .pipe(size(sizeOptions))
                .pipe(sourcemaps.write(''))
                .pipe(gulp.dest(dist)),
        );
    });
});

// CSS
Object.entries(build.css).forEach(([filename, entry]) => {
    const { dist, src } = entry;
    const name = `css:${filename}`;
    tasks.css.push(name);

    gulp.task(name, () =>
        gulp
            .src(src)
            .pipe(plumber())
            .pipe(sass())
            .pipe(
                prefix(browsers, {
                    cascade: false,
                }),
            )
            .pipe(clean())
            .pipe(size(sizeOptions))
            .pipe(gulp.dest(dist)),
    );
});

// SVG Sprites
Object.entries(build.sprite).forEach(([filename, entry]) => {
    const { dist, src } = entry;
    const name = `sprite:${filename}`;
    tasks.sprite.push(name);

    gulp.task(name, () =>
        gulp
            .src(src)
            .pipe(plumber())
            .pipe(
                imagemin([
                    imagemin.svgo({
                        plugins: [{ removeViewBox: false }],
                    }),
                ]),
            )
            .pipe(svgstore())
            .pipe(rename({ basename: path.parse(filename).name }))
            .pipe(size(sizeOptions))
            .pipe(gulp.dest(dist)),
    );
});

// Build all JS
gulp.task('js', () => gulp.parallel(...tasks.js));

// Watch for file changes
gulp.task('watch', () => {
    // Plyr core
    gulp.watch(paths.plyr.src.js, gulp.parallel(...tasks.js));
    gulp.watch(paths.plyr.src.sass, gulp.parallel(...tasks.css));
    gulp.watch(paths.plyr.src.sprite, gulp.parallel(...tasks.sprite));

    // Demo
    gulp.watch(paths.demo.src.js, gulp.parallel(...tasks.js));
    gulp.watch(paths.demo.src.sass, gulp.parallel(...tasks.css));
});

// Serve via browser sync
gulp.task('serve', () =>
    browserSync.init({
        server: {
            baseDir: paths.demo.root,
        },
        notify: false,
        watch: true,
    }),
);

// Build distribution
gulp.task('build', gulp.series(tasks.clean, gulp.parallel(...tasks.js, ...tasks.css, ...tasks.sprite)));

// Default gulp task
gulp.task('default', gulp.series('build', gulp.parallel('serve', 'watch')));

// Publish a version to CDN and demo
// --------------------------------------------
// Get deployment config
let credentials = {};
try {
    credentials = require('./credentials.json'); //eslint-disable-line
} catch (e) {
    // Do nothing
}

// Get branch info
const branch = {
    current: gitbranch.sync(),
    master: 'master',
    beta: 'beta',
};

const maxAge = 31536000; // 1 year
const options = {
    cdn: {
        headers: {
            'Cache-Control': `max-age=${maxAge}`,
        },
    },
    demo: {
        uploadPath: branch.current === branch.beta ? 'beta' : null,
        headers: {
            'Cache-Control': 'no-cache, no-store, must-revalidate, max-age=0',
        },
    },
    symlinks(ver, filename) {
        return {
            headers: {
                // http://stackoverflow.com/questions/2272835/amazon-s3-object-redirect
                'x-amz-website-redirect-location': `/${ver}/${filename}`,
                'Cache-Control': 'no-cache, no-store, must-revalidate, max-age=0',
            },
        };
    },
};

const regex =
    '(?:0|[1-9][0-9]*)\\.(?:0|[1-9][0-9]*).(?:0|[1-9][0-9]*)(?:-[\\da-z\\-]+(?:.[\\da-z\\-]+)*)?(?:\\+[\\da-z\\-]+(?:.[\\da-z\\-]+)*)?';
const semver = new RegExp(`v${regex}`, 'gi');
const localPath = new RegExp('(../)?dist', 'gi');
const versionPath = `https://${deploy.cdn.domain}/${version}`;
const cdnpath = new RegExp(`${deploy.cdn.domain}/${regex}/`, 'gi');

const renameFile = rename(p => {
    p.basename = p.basename.replace(minSuffix, ''); // eslint-disable-line
    p.dirname = p.dirname.replace('.', version); // eslint-disable-line
});

// Check we're on the correct branch to deploy
const canDeploy = () => {
    const allowed = [branch.master, branch.beta];

    if (!allowed.includes(branch.current)) {
        console.error(`Must be on ${allowed.join(', ')} to publish! (current: ${branch.current})`);

        return false;
    }

    return true;
};

gulp.task('version', done => {
    if (!canDeploy()) {
        done();
        return null;
    }

    const { domain } = deploy.cdn;

    log(`Uploading ${ansi.green.bold(version)} to ${ansi.cyan(domain)}...`);

    // Replace versioned URLs in source
    const files = ['plyr.js', 'plyr.polyfilled.js', 'config/defaults.js'];

    return gulp
        .src(
            files.map(file => path.join(__dirname, `src/js/${file}`)),
            { base: '.' },
        )
        .pipe(replace(semver, `v${version}`))
        .pipe(replace(cdnpath, `${domain}/${version}/`))
        .pipe(gulp.dest('./'));
});

// Publish version to CDN bucket
gulp.task('cdn', done => {
    if (!canDeploy()) {
        done();
        return null;
    }

    const { domain, publisher } = deploy.cdn;

    if (!publisher) {
        throw new Error('No publisher instance. Check AWS configuration.');
    }

    log(`Uploading ${ansi.green.bold(pkg.version)} to ${ansi.cyan(domain)}...`);

    // Upload to CDN
    return (
        gulp
            .src(paths.upload)
            .pipe(renameFile)
            // Remove min suffix from source map URL
            .pipe(
                replace(
                    /sourceMappingURL=([\w-?.]+)/,
                    (match, filename) => `sourceMappingURL=${filename.replace(minSuffix, '')}`,
                ),
            )
            .pipe(size(sizeOptions))
            .pipe(replace(localPath, versionPath))
            .pipe(publisher.publish(options.cdn.headers))
            .pipe(publish.reporter())
    );
});

// Purge the fastly cache incase any 403/404 are cached
gulp.task('purge', () => {
    if (!Object.keys(credentials).includes('fastly')) {
        throw new Error('Fastly credentials required to purge cache.');
    }

    const { fastly } = credentials;
    const list = [];

    return gulp
        .src(paths.upload)
        .pipe(
            through.obj((file, enc, cb) => {
                const filename = file.path.split('/').pop();
                list.push(`${versionPath}/${filename.replace(minSuffix, '')}`);
                cb(null);
            }),
        )
        .on('end', () => {
            const purge = new FastlyPurge(fastly.token);

            list.forEach(url => {
                log(`Purging ${ansi.cyan(url)}...`);

                purge.url(url, (error, result) => {
                    if (error) {
                        log.error(error);
                    } else if (result) {
                        log(result);
                    }
                });
            });
        });
});

// Publish to demo bucket
gulp.task('demo', done => {
    if (!canDeploy()) {
        done();
        return null;
    }

    const { publisher } = deploy.demo;
    const { domain } = deploy.cdn;

    if (!publisher) {
        throw new Error('No publisher instance. Check AWS configuration.');
    }

    log(`Uploading ${ansi.green.bold(pkg.version)} to ${ansi.cyan(domain)}...`);

    // Replace versioned files in readme.md
    gulp.src([`${__dirname}/readme.md`])
        .pipe(replace(cdnpath, `${domain}/${version}/`))
        .pipe(gulp.dest(__dirname));

    // Replace local file paths with remote paths in demo HTML
    // e.g. "../dist/plyr.js" to "https://cdn.plyr.io/x.x.x/plyr.js"
    const index = `${paths.demo.root}index.html`;
    const error = `${paths.demo.root}error.html`;
    const pages = [index];

    if (branch.current === branch.master) {
        pages.push(error);
    }

    return gulp
        .src(pages)
        .pipe(replace(localPath, versionPath))
        .pipe(publisher.publish(options.demo.headers))
        .pipe(publish.reporter());
});

gulp.task('error', done => {
    // Only update CDN for master (prod)
    if (!canDeploy() || branch.current !== branch.master) {
        done();
        return null;
    }

    const { publisher } = deploy.cdn;

    if (!publisher) {
        throw new Error('No publisher instance. Check AWS configuration.');
    }

    // Replace local file paths with remote paths in demo HTML
    // e.g. "../dist/plyr.js" to "https://cdn.plyr.io/x.x.x/plyr.js"
    // Upload error.html to cdn
    return gulp
        .src(`${paths.demo.root}error.html`)
        .pipe(replace(localPath, versionPath))
        .pipe(publisher.publish(options.demo.headers))
        .pipe(publish.reporter());
});

// Open the demo site to check it's ok
gulp.task('open', () => {
    const { domain } = deploy.demo;

    return gulp.src(__filename).pipe(
        open({
            uri: `https://${domain}/${branch.current === branch.beta ? 'beta' : ''}`,
        }),
    );
});

// Do everything
gulp.task(
    'deploy',
    gulp.series(
        'version',
        tasks.clean,
        gulp.parallel(...tasks.js, ...tasks.css, ...tasks.sprite),
        'cdn',
        'demo',
        'purge',
        'open',
    ),
);
<commit_msg>Fix issue with browser sync preview<commit_after>// ==========================================================================
// Gulp build script
// ==========================================================================
/* eslint no-console: "off" */

const path = require('path');
const gulp = require('gulp');
// ------------------------------------
// JavaScript
// ------------------------------------
const terser = require('gulp-terser');
const rollup = require('gulp-better-rollup');
const babel = require('rollup-plugin-babel');
const commonjs = require('rollup-plugin-commonjs');
const resolve = require('rollup-plugin-node-resolve');
// ------------------------------------
// CSS
// ------------------------------------
const sass = require('gulp-sass');
const clean = require('gulp-clean-css');
const prefix = require('gulp-autoprefixer');
// ------------------------------------
// Images
// ------------------------------------
const svgstore = require('gulp-svgstore');
const imagemin = require('gulp-imagemin');
// ------------------------------------
// Utils
// ------------------------------------
const del = require('del');
const filter = require('gulp-filter');
const header = require('gulp-header');
const gitbranch = require('git-branch');
const rename = require('gulp-rename');
const replace = require('gulp-replace');
const ansi = require('ansi-colors');
const log = require('fancy-log');
const open = require('gulp-open');
const plumber = require('gulp-plumber');
const size = require('gulp-size');
const sourcemaps = require('gulp-sourcemaps');
const through = require('through2');
const browserSync = require('browser-sync').create();
// ------------------------------------
// Deployment
// ------------------------------------
const aws = require('aws-sdk');
const publish = require('gulp-awspublish');
const FastlyPurge = require('fastly-purge');
// ------------------------------------
// Configs
// ------------------------------------
const pkg = require('./package.json');
const build = require('./build.json');
const deploy = require('./deploy.json');
// ------------------------------------
// Info from package
// ------------------------------------
const { browserslist: browsers, version } = pkg;
const minSuffix = '.min';

// Get AWS config
Object.values(deploy).forEach(target => {
    Object.assign(target, {
        publisher: publish.create({
            region: target.region,
            params: {
                Bucket: target.bucket,
            },
            credentials: new aws.SharedIniFileCredentials({ profile: 'plyr' }),
        }),
    });
});

// Paths
const paths = {
    plyr: {
        // Source paths
        src: {
            sass: path.join(__dirname, 'src/sass/**/*.scss'),
            js: path.join(__dirname, 'src/js/**/*.js'),
            sprite: path.join(__dirname, 'src/sprite/*.svg'),
        },

        // Output paths
        output: path.join(__dirname, 'dist/'),
    },
    demo: {
        // Source paths
        src: {
            sass: path.join(__dirname, 'demo/src/sass/**/*.scss'),
            js: path.join(__dirname, 'demo/src/js/**/*.js'),
        },

        // Output paths
        output: path.join(__dirname, 'demo/dist/'),

        // Demo
        root: path.join(__dirname, 'demo/'),
    },
    upload: [
        path.join(__dirname, `dist/*${minSuffix}.*`),
        path.join(__dirname, 'dist/*.css'),
        path.join(__dirname, 'dist/*.svg'),
        path.join(__dirname, `demo/dist/*${minSuffix}.*`),
        path.join(__dirname, 'demo/dist/*.css'),
        path.join(__dirname, 'demo/dist/*.svg'),
    ],
};

// Task arrays
const tasks = {
    css: [],
    js: [],
    sprite: [],
    clean: 'clean',
};

// Size plugin
const sizeOptions = { showFiles: true, gzip: true };

// Clean out /dist
gulp.task(tasks.clean, done => {
    const dirs = [paths.plyr.output, paths.demo.output].map(dir => path.join(dir, '**/*'));

    // Don't delete the mp4
    dirs.push(`!${path.join(paths.plyr.output, '**/*.mp4')}`);

    del(dirs);

    done();
});

// JavaScript
Object.entries(build.js).forEach(([filename, entry]) => {
    const { dist, formats, namespace, polyfill, src } = entry;

    formats.forEach(format => {
        const name = `js:${filename}:${format}`;
        const extension = format === 'es' ? 'mjs' : 'js';
        tasks.js.push(name);

        gulp.task(name, () =>
            gulp
                .src(src)
                .pipe(plumber())
                .pipe(sourcemaps.init())
                .pipe(
                    rollup(
                        {
                            plugins: [
                                resolve(),
                                commonjs(),
                                babel({
                                    presets: [
                                        [
                                            '@babel/env',
                                            {
                                                // debug: true,
                                                useBuiltIns: polyfill ? 'usage' : false,
                                                corejs: polyfill ? 3 : undefined,
                                            },
                                        ],
                                    ],
                                    babelrc: false,
                                    exclude: [/\/core-js\//],
                                }),
                            ],
                        },
                        {
                            name: namespace,
                            format,
                        },
                    ),
                )
                .pipe(header('typeof navigator === "object" && ')) // "Support" SSR (#935)
                .pipe(
                    rename({
                        extname: `.${extension}`,
                    }),
                )
                .pipe(gulp.dest(dist))
                .pipe(filter(`**/*.${extension}`))
                .pipe(terser())
                .pipe(rename({ suffix: minSuffix }))
                .pipe(size(sizeOptions))
                .pipe(sourcemaps.write(''))
                .pipe(gulp.dest(dist)),
        );
    });
});

// CSS
Object.entries(build.css).forEach(([filename, entry]) => {
    const { dist, src } = entry;
    const name = `css:${filename}`;
    tasks.css.push(name);

    gulp.task(name, () =>
        gulp
            .src(src)
            .pipe(plumber())
            .pipe(sass())
            .pipe(
                prefix(browsers, {
                    cascade: false,
                }),
            )
            .pipe(clean())
            .pipe(size(sizeOptions))
            .pipe(gulp.dest(dist)),
    );
});

// SVG Sprites
Object.entries(build.sprite).forEach(([filename, entry]) => {
    const { dist, src } = entry;
    const name = `sprite:${filename}`;
    tasks.sprite.push(name);

    gulp.task(name, () =>
        gulp
            .src(src)
            .pipe(plumber())
            .pipe(
                imagemin([
                    imagemin.svgo({
                        plugins: [{ removeViewBox: false }],
                    }),
                ]),
            )
            .pipe(svgstore())
            .pipe(rename({ basename: path.parse(filename).name }))
            .pipe(size(sizeOptions))
            .pipe(gulp.dest(dist)),
    );
});

// Build all JS
gulp.task('js', () => gulp.parallel(...tasks.js));

// Watch for file changes
gulp.task('watch', () => {
    // Plyr core
    gulp.watch(paths.plyr.src.js, gulp.parallel(...tasks.js));
    gulp.watch(paths.plyr.src.sass, gulp.parallel(...tasks.css));
    gulp.watch(paths.plyr.src.sprite, gulp.parallel(...tasks.sprite));

    // Demo
    gulp.watch(paths.demo.src.js, gulp.parallel(...tasks.js));
    gulp.watch(paths.demo.src.sass, gulp.parallel(...tasks.css));
});

// Serve via browser sync
gulp.task('serve', () =>
    browserSync.init({
        server: {
            baseDir: paths.demo.root,
        },
        notify: false,
        watch: true,
        ghostMode: false,
    }),
);

// Build distribution
gulp.task('build', gulp.series(tasks.clean, gulp.parallel(...tasks.js, ...tasks.css, ...tasks.sprite)));

// Default gulp task
gulp.task('default', gulp.series('build', gulp.parallel('serve', 'watch')));

// Publish a version to CDN and demo
// --------------------------------------------
// Get deployment config
let credentials = {};
try {
    credentials = require('./credentials.json'); //eslint-disable-line
} catch (e) {
    // Do nothing
}

// Get branch info
const branch = {
    current: gitbranch.sync(),
    master: 'master',
    beta: 'beta',
};

const maxAge = 31536000; // 1 year
const options = {
    cdn: {
        headers: {
            'Cache-Control': `max-age=${maxAge}`,
        },
    },
    demo: {
        uploadPath: branch.current === branch.beta ? 'beta' : null,
        headers: {
            'Cache-Control': 'no-cache, no-store, must-revalidate, max-age=0',
        },
    },
    symlinks(ver, filename) {
        return {
            headers: {
                // http://stackoverflow.com/questions/2272835/amazon-s3-object-redirect
                'x-amz-website-redirect-location': `/${ver}/${filename}`,
                'Cache-Control': 'no-cache, no-store, must-revalidate, max-age=0',
            },
        };
    },
};

const regex =
    '(?:0|[1-9][0-9]*)\\.(?:0|[1-9][0-9]*).(?:0|[1-9][0-9]*)(?:-[\\da-z\\-]+(?:.[\\da-z\\-]+)*)?(?:\\+[\\da-z\\-]+(?:.[\\da-z\\-]+)*)?';
const semver = new RegExp(`v${regex}`, 'gi');
const localPath = new RegExp('(../)?dist', 'gi');
const versionPath = `https://${deploy.cdn.domain}/${version}`;
const cdnpath = new RegExp(`${deploy.cdn.domain}/${regex}/`, 'gi');

const renameFile = rename(p => {
    p.basename = p.basename.replace(minSuffix, ''); // eslint-disable-line
    p.dirname = p.dirname.replace('.', version); // eslint-disable-line
});

// Check we're on the correct branch to deploy
const canDeploy = () => {
    const allowed = [branch.master, branch.beta];

    if (!allowed.includes(branch.current)) {
        console.error(`Must be on ${allowed.join(', ')} to publish! (current: ${branch.current})`);

        return false;
    }

    return true;
};

gulp.task('version', done => {
    if (!canDeploy()) {
        done();
        return null;
    }

    const { domain } = deploy.cdn;

    log(`Uploading ${ansi.green.bold(version)} to ${ansi.cyan(domain)}...`);

    // Replace versioned URLs in source
    const files = ['plyr.js', 'plyr.polyfilled.js', 'config/defaults.js'];

    return gulp
        .src(
            files.map(file => path.join(__dirname, `src/js/${file}`)),
            { base: '.' },
        )
        .pipe(replace(semver, `v${version}`))
        .pipe(replace(cdnpath, `${domain}/${version}/`))
        .pipe(gulp.dest('./'));
});

// Publish version to CDN bucket
gulp.task('cdn', done => {
    if (!canDeploy()) {
        done();
        return null;
    }

    const { domain, publisher } = deploy.cdn;

    if (!publisher) {
        throw new Error('No publisher instance. Check AWS configuration.');
    }

    log(`Uploading ${ansi.green.bold(pkg.version)} to ${ansi.cyan(domain)}...`);

    // Upload to CDN
    return (
        gulp
            .src(paths.upload)
            .pipe(renameFile)
            // Remove min suffix from source map URL
            .pipe(
                replace(
                    /sourceMappingURL=([\w-?.]+)/,
                    (match, filename) => `sourceMappingURL=${filename.replace(minSuffix, '')}`,
                ),
            )
            .pipe(size(sizeOptions))
            .pipe(replace(localPath, versionPath))
            .pipe(publisher.publish(options.cdn.headers))
            .pipe(publish.reporter())
    );
});

// Purge the fastly cache incase any 403/404 are cached
gulp.task('purge', () => {
    if (!Object.keys(credentials).includes('fastly')) {
        throw new Error('Fastly credentials required to purge cache.');
    }

    const { fastly } = credentials;
    const list = [];

    return gulp
        .src(paths.upload)
        .pipe(
            through.obj((file, enc, cb) => {
                const filename = file.path.split('/').pop();
                list.push(`${versionPath}/${filename.replace(minSuffix, '')}`);
                cb(null);
            }),
        )
        .on('end', () => {
            const purge = new FastlyPurge(fastly.token);

            list.forEach(url => {
                log(`Purging ${ansi.cyan(url)}...`);

                purge.url(url, (error, result) => {
                    if (error) {
                        log.error(error);
                    } else if (result) {
                        log(result);
                    }
                });
            });
        });
});

// Publish to demo bucket
gulp.task('demo', done => {
    if (!canDeploy()) {
        done();
        return null;
    }

    const { publisher } = deploy.demo;
    const { domain } = deploy.cdn;

    if (!publisher) {
        throw new Error('No publisher instance. Check AWS configuration.');
    }

    log(`Uploading ${ansi.green.bold(pkg.version)} to ${ansi.cyan(domain)}...`);

    // Replace versioned files in readme.md
    gulp.src([`${__dirname}/readme.md`])
        .pipe(replace(cdnpath, `${domain}/${version}/`))
        .pipe(gulp.dest(__dirname));

    // Replace local file paths with remote paths in demo HTML
    // e.g. "../dist/plyr.js" to "https://cdn.plyr.io/x.x.x/plyr.js"
    const index = `${paths.demo.root}index.html`;
    const error = `${paths.demo.root}error.html`;
    const pages = [index];

    if (branch.current === branch.master) {
        pages.push(error);
    }

    return gulp
        .src(pages)
        .pipe(replace(localPath, versionPath))
        .pipe(publisher.publish(options.demo.headers))
        .pipe(publish.reporter());
});

gulp.task('error', done => {
    // Only update CDN for master (prod)
    if (!canDeploy() || branch.current !== branch.master) {
        done();
        return null;
    }

    const { publisher } = deploy.cdn;

    if (!publisher) {
        throw new Error('No publisher instance. Check AWS configuration.');
    }

    // Replace local file paths with remote paths in demo HTML
    // e.g. "../dist/plyr.js" to "https://cdn.plyr.io/x.x.x/plyr.js"
    // Upload error.html to cdn
    return gulp
        .src(`${paths.demo.root}error.html`)
        .pipe(replace(localPath, versionPath))
        .pipe(publisher.publish(options.demo.headers))
        .pipe(publish.reporter());
});

// Open the demo site to check it's ok
gulp.task('open', () => {
    const { domain } = deploy.demo;

    return gulp.src(__filename).pipe(
        open({
            uri: `https://${domain}/${branch.current === branch.beta ? 'beta' : ''}`,
        }),
    );
});

// Do everything
gulp.task(
    'deploy',
    gulp.series(
        'version',
        tasks.clean,
        gulp.parallel(...tasks.js, ...tasks.css, ...tasks.sprite),
        'cdn',
        'demo',
        'purge',
        'open',
    ),
);
<|endoftext|>


<commit_before>'use strict';

var gulp = require('gulp');
var plugins = require('gulp-load-plugins')();
var pkg = require('./package');
var scripts = {
      name: 'viewer.js',
      min: 'viewer.min.js',
      all: [
        'gulpfile.js',
        'dist/viewer.js',
        'demo/js/main.js',
        'docs/js/main.js',
        'examples/*/js/main.js',
        'test/**/*.js'
      ],
      list: [
        'src/js/intro.js',
        'src/js/variables.js',
        'src/js/utilities.js',
        'src/js/viewer.js',
        'src/js/init.js',
        'src/js/build.js',
        'src/js/bind.js',
        'src/js/render.js',
        'src/js/handlers.js',
        'src/js/methods.js',
        'src/js/others.js',
        'src/js/prototype.js',
        'src/js/defaults.js',
        'src/js/template.js',
        'src/js/plugin.js',
        'src/js/outro.js'
      ],
      main: 'dist/viewer.js',
      src: 'src/*.js',
      dest: 'dist'
    };
var styles = {
      name: 'viewer.css',
      min: 'viewer.min.css',
      all: [
        'dist/viewer.css',
        'docs/css/*.css'
      ],
      scss: 'src/scss/*.scss',
      main: 'dist/viewer.css',
      src: 'src/scss/viewer.scss',
      dest: 'dist'
    };
var replacement = {
      regexp: /@\w+/g,
      filter: function (placeholder) {
        switch (placeholder) {
          case '@VERSION':
            placeholder = pkg.version;
            break;

          case '@YEAR':
            placeholder = (new Date()).getFullYear();
            break;

          case '@DATE':
            placeholder = (new Date()).toISOString();
            break;
        }

        return placeholder;
      }
    };

gulp.task('js+', function () {
  return gulp.src(scripts.list).
    pipe(plugins.concat(scripts.name)).
    pipe(gulp.dest(scripts.dest));
});

gulp.task('jshint', ['js+'], function () {
  return gulp.src(scripts.all).
    pipe(plugins.jshint()).
    pipe(plugins.jshint.reporter('default'));
});

gulp.task('jscs', ['js+'], function () {
  return gulp.src(scripts.all).
    pipe(plugins.jscs()).
    pipe(plugins.jscs.reporter());
});

gulp.task('js', ['jshint', 'jscs'], function () {
  return gulp.src(scripts.main).
    pipe(plugins.replace(replacement.regexp, replacement.filter)).
    pipe(gulp.dest(scripts.dest)).
    pipe(plugins.rename(scripts.min)).
    pipe(plugins.uglify({
      preserveComments: 'license'
    })).
    pipe(gulp.dest(scripts.dest));
});

gulp.task('concat', function () {
  return gulp.src(scripts.list).
    pipe(plugins.sourcemaps.init()).
    pipe(plugins.concat(scripts.name)).
    pipe(plugins.sourcemaps.write('./')).
    pipe(gulp.dest(scripts.dest));
});

gulp.task('css+', function () {
  return gulp.src(styles.src).
    pipe(plugins.sass()).
    pipe(gulp.dest(styles.dest));
});

gulp.task('csslint', ['css+'], function () {
  return gulp.src(styles.all).
    pipe(plugins.csslint('.csslintrc')).
    pipe(plugins.csslint.reporter());
});

gulp.task('css', ['csslint'], function () {
  return gulp.src(styles.main).
    pipe(plugins.replace(replacement.regexp, replacement.filter)).
    pipe(plugins.autoprefixer({
      browsers: [
        'Android 2.3',
        'Android >= 4',
        'Chrome >= 20',
        'Firefox >= 24',
        'Explorer >= 8',
        'iOS >= 6',
        'Opera >= 12',
        'Safari >= 6'
      ]
    })).
    pipe(plugins.csscomb()).
    pipe(gulp.dest(styles.dest)).
    pipe(plugins.rename(styles.min)).
    pipe(plugins.minifyCss({
      compatibility: 'ie8',
      keepSpecialComments: 1
    })).
    pipe(gulp.dest(styles.dest));
});

gulp.task('sass', function () {
  return gulp.src(styles.src).
    pipe(plugins.sourcemaps.init()).
    pipe(plugins.sass()).
    pipe(plugins.sourcemaps.write('./')).
    pipe(gulp.dest(styles.dest));
});

gulp.task('release', ['js', 'css'], function () {
  return gulp.src('dist/*.{js,css}').
    pipe(gulp.dest('_releases/' + pkg.version));
});

gulp.task('htmlcomb:demo', function () {
  return gulp.src('demo/*.html').
    pipe(plugins.htmlcomb()).
    pipe(gulp.dest('demo'));
});

gulp.task('htmlcomb:docs', function () {
  return gulp.src('docs/*.html').
    pipe(plugins.htmlcomb()).
    pipe(gulp.dest('docs'));
});

gulp.task('htmlcomb', ['htmlcomb:demo', 'htmlcomb:docs']);

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

gulp.task('assets:fonts', function () {
  return gulp.src([
      'bower_components/bootstrap/fonts/*'
    ]).
    pipe(gulp.dest('assets/fonts'));
});

gulp.task('assets:css', ['assets:fonts'], function () {
  return gulp.src([
      'bower_components/bootstrap/dist/css/bootstrap.min.css'
    ]).
    pipe(gulp.dest('assets/css'));
});

gulp.task('assets', ['assets:js', 'assets:css']);

gulp.task('docs:js', function () {
  return gulp.src('dist/*.js').
    pipe(gulp.dest('_gh_pages/js'));
});

gulp.task('docs:css', function () {
  return gulp.src('dist/*.css').
    pipe(gulp.dest('_gh_pages/css'));
});

gulp.task('docs:img', function () {
  return gulp.src('assets/img/**').
    pipe(gulp.dest('_gh_pages/img'));
});

gulp.task('docs:html', function () {
  return gulp.src('docs/**').
    pipe(gulp.dest('_gh_pages'));
});

gulp.task('docs', ['docs:html', 'docs:js', 'docs:css', 'docs:img']);

gulp.task('watch', function () {
  gulp.watch(scripts.list, ['concat']);
  gulp.watch(styles.scss, ['sass']);
  gulp.watch('docs/**', ['docs:html']);
});

gulp.task('default', ['watch']);
<commit_msg>Update file paths<commit_after>'use strict';

var gulp = require('gulp');
var plugins = require('gulp-load-plugins')();
var pkg = require('./package');
var scripts = {
      name: 'viewer.js',
      min: 'viewer.min.js',
      all: [
        'gulpfile.js',
        'dist/viewer.js',
        'demo/js/main.js',
        'docs/js/main.js',
        'examples/*/js/main.js',
        'test/**/*.js'
      ],
      list: [
        'src/js/intro.js',
        'src/js/variables.js',
        'src/js/utilities.js',
        'src/js/viewer.js',
        'src/js/init.js',
        'src/js/build.js',
        'src/js/bind.js',
        'src/js/render.js',
        'src/js/handlers.js',
        'src/js/methods.js',
        'src/js/others.js',
        'src/js/prototype.js',
        'src/js/defaults.js',
        'src/js/template.js',
        'src/js/plugin.js',
        'src/js/outro.js'
      ],
      main: 'dist/viewer.js',
      src: 'src/*.js',
      dest: 'dist'
    };
var styles = {
      name: 'viewer.css',
      min: 'viewer.min.css',
      all: [
        'dist/viewer.css',
        'demo/css/main.css',
        'docs/css/main.css'
      ],
      scss: 'src/scss/*.scss',
      main: 'dist/viewer.css',
      src: 'src/scss/viewer.scss',
      dest: 'dist'
    };
var replacement = {
      regexp: /@\w+/g,
      filter: function (placeholder) {
        switch (placeholder) {
          case '@VERSION':
            placeholder = pkg.version;
            break;

          case '@YEAR':
            placeholder = (new Date()).getFullYear();
            break;

          case '@DATE':
            placeholder = (new Date()).toISOString();
            break;
        }

        return placeholder;
      }
    };

gulp.task('js+', function () {
  return gulp.src(scripts.list).
    pipe(plugins.concat(scripts.name)).
    pipe(gulp.dest(scripts.dest));
});

gulp.task('jshint', ['js+'], function () {
  return gulp.src(scripts.all).
    pipe(plugins.jshint()).
    pipe(plugins.jshint.reporter('default'));
});

gulp.task('jscs', ['js+'], function () {
  return gulp.src(scripts.all).
    pipe(plugins.jscs()).
    pipe(plugins.jscs.reporter());
});

gulp.task('js', ['jshint', 'jscs'], function () {
  return gulp.src(scripts.main).
    pipe(plugins.replace(replacement.regexp, replacement.filter)).
    pipe(gulp.dest(scripts.dest)).
    pipe(plugins.rename(scripts.min)).
    pipe(plugins.uglify({
      preserveComments: 'license'
    })).
    pipe(gulp.dest(scripts.dest));
});

gulp.task('concat', function () {
  return gulp.src(scripts.list).
    pipe(plugins.sourcemaps.init()).
    pipe(plugins.concat(scripts.name)).
    pipe(plugins.sourcemaps.write('./')).
    pipe(gulp.dest(scripts.dest));
});

gulp.task('css+', function () {
  return gulp.src(styles.src).
    pipe(plugins.sass()).
    pipe(gulp.dest(styles.dest));
});

gulp.task('csslint', ['css+'], function () {
  return gulp.src(styles.all).
    pipe(plugins.csslint('.csslintrc')).
    pipe(plugins.csslint.reporter());
});

gulp.task('css', ['csslint'], function () {
  return gulp.src(styles.main).
    pipe(plugins.replace(replacement.regexp, replacement.filter)).
    pipe(plugins.autoprefixer({
      browsers: [
        'Android 2.3',
        'Android >= 4',
        'Chrome >= 20',
        'Firefox >= 24',
        'Explorer >= 8',
        'iOS >= 6',
        'Opera >= 12',
        'Safari >= 6'
      ]
    })).
    pipe(plugins.csscomb()).
    pipe(gulp.dest(styles.dest)).
    pipe(plugins.rename(styles.min)).
    pipe(plugins.minifyCss({
      compatibility: 'ie8',
      keepSpecialComments: 1
    })).
    pipe(gulp.dest(styles.dest));
});

gulp.task('sass', function () {
  return gulp.src(styles.src).
    pipe(plugins.sourcemaps.init()).
    pipe(plugins.sass()).
    pipe(plugins.sourcemaps.write('./')).
    pipe(gulp.dest(styles.dest));
});

gulp.task('release', ['js', 'css'], function () {
  return gulp.src('dist/*.{js,css}').
    pipe(gulp.dest('_releases/' + pkg.version));
});

gulp.task('htmlcomb:demo', function () {
  return gulp.src('demo/*.html').
    pipe(plugins.htmlcomb()).
    pipe(gulp.dest('demo'));
});

gulp.task('htmlcomb:docs', function () {
  return gulp.src('docs/*.html').
    pipe(plugins.htmlcomb()).
    pipe(gulp.dest('docs'));
});

gulp.task('htmlcomb', ['htmlcomb:demo', 'htmlcomb:docs']);

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

gulp.task('assets:fonts', function () {
  return gulp.src([
      'bower_components/bootstrap/fonts/*'
    ]).
    pipe(gulp.dest('assets/fonts'));
});

gulp.task('assets:css', ['assets:fonts'], function () {
  return gulp.src([
      'bower_components/bootstrap/dist/css/bootstrap.min.css'
    ]).
    pipe(gulp.dest('assets/css'));
});

gulp.task('assets', ['assets:js', 'assets:css']);

gulp.task('docs:js', function () {
  return gulp.src('dist/*.js').
    pipe(gulp.dest('_gh_pages/js'));
});

gulp.task('docs:css', function () {
  return gulp.src('dist/*.css').
    pipe(gulp.dest('_gh_pages/css'));
});

gulp.task('docs:img', function () {
  return gulp.src('assets/img/**').
    pipe(gulp.dest('_gh_pages/img'));
});

gulp.task('docs:html', function () {
  return gulp.src('docs/**').
    pipe(gulp.dest('_gh_pages'));
});

gulp.task('docs', ['docs:html', 'docs:js', 'docs:css', 'docs:img']);

gulp.task('watch', function () {
  gulp.watch(scripts.list, ['concat']);
  gulp.watch(styles.scss, ['sass']);
  gulp.watch('docs/**', ['docs:html']);
});

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


<commit_before>var gulp = require('gulp');
var webpack = require('./');
var rimraf = require('rimraf');

gulp.task('default', function() {
  rimraf.sync('tmp');
  return gulp.src('test/fixtures/entry.js')
    .pipe(webpack())
    .pipe(gulp.dest('tmp/'));
});
<commit_msg>Add watch to gulpfile<commit_after>var gulp = require('gulp');
var webpack = require('./');
var rimraf = require('rimraf');

gulp.task('default', function() {
  rimraf.sync('tmp');
  return gulp.src('test/fixtures/entry.js')
    .pipe(webpack())
    .pipe(gulp.dest('tmp/'));
});

gulp.task('watch', function() {
  gulp.watch('test/fixtures/*.js', ['default']);
});
<|endoftext|>


<commit_before>var gulp = require('gulp');
var babel = require('gulp-babel');
var debug = require('gulp-debug');
var cache = require('gulp-cached');
var replace = require('gulp-replace-task');
var electron = require('electron-connect').server.create();
var async = require('async');
var tcpPortUsed = require('tcp-port-used');
var CONFIG = require('./src/config');

var replaceOptions = {
  patterns: [
    {
      match: 'PORT',
      replace: CONFIG.PORT
    }
  ]
};

var isPortUsed = function (port, cb) {
  tcpPortUsed
    .check(port, '127.0.0.1')
    .then(function (inUse) {
      cb(null, inUse);
    }, function (err) {
      cb(err);
  });
};

gulp.task('check-port', function (cb) {
  isPortUsed(CONFIG.PORT, function (err, portInUse) {
    if (err) {
      return cb('An unknown error occured');
    }
    if (portInUse)
      return cb('The port ' + CONFIG.PORT + ' is already in use');

    cb();
  });
});

gulp.task('electron:start', ['check-port', 'transpile', 'copy'], function() {
  electron.start();
});

gulp.task('electron:restart', ['transpile', 'copy'], function() {
  electron.restart();
});

gulp.task('watch', ['electron:start'], function () {
  gulp.watch(['src/**/*'], ['transpile', 'copy', 'electron:restart']);
});

gulp.task('transpile', function (cb) {
  gulp.src(['src/**/*.js'])
    .pipe(cache('transpile'))
    .pipe(debug())
    .pipe(replace(replaceOptions))
    .pipe(babel({
      presets: ['es2015', 'react']
    }))
    .pipe(gulp.dest('dist'))
    .on('end', cb);
});

gulp.task('copy', function (cb) {
  gulp.src(['src/**/*.*', '!src/**/*.js'])
    .pipe(cache('copy'))
    .pipe(debug())
    .pipe(replace(replaceOptions))
    .pipe(gulp.dest('dist'))
    .on('end', cb);
});

gulp.task('default', ['transpile', 'copy', 'check-port', 'electron:start', 'watch']);
<commit_msg>Stop Electron before restarting it<commit_after>var gulp = require('gulp');
var babel = require('gulp-babel');
var debug = require('gulp-debug');
var cache = require('gulp-cached');
var replace = require('gulp-replace-task');
var electron = require('electron-connect').server.create();
var async = require('async');
var tcpPortUsed = require('tcp-port-used');
var CONFIG = require('./src/config');

var replaceOptions = {
  patterns: [
    {
      match: 'PORT',
      replace: CONFIG.PORT
    }
  ]
};

var isPortUsed = function (port, cb) {
  tcpPortUsed
    .check(port, '127.0.0.1')
    .then(function (inUse) {
      cb(null, inUse);
    }, function (err) {
      cb(err);
  });
};

gulp.task('check-port', function (cb) {
  isPortUsed(CONFIG.PORT, function (err, portInUse) {
    if (err) {
      return cb('An unknown error occured');
    }
    if (portInUse)
      return cb('The port ' + CONFIG.PORT + ' is already in use');

    cb();
  });
});

gulp.task('electron:start', ['check-port', 'transpile', 'copy'], function() {
  electron.start();
});

gulp.task('electron:restart', ['transpile', 'copy'], function() {
  electron.stop();
  electron.restart();
});

gulp.task('watch', ['electron:start'], function () {
  gulp.watch(['src/**/*'], ['transpile', 'copy', 'electron:restart']);
});

gulp.task('transpile', function (cb) {
  gulp.src(['src/**/*.js'])
    .pipe(cache('transpile'))
    .pipe(debug())
    .pipe(replace(replaceOptions))
    .pipe(babel({
      presets: ['es2015', 'react']
    }))
    .pipe(gulp.dest('dist'))
    .on('end', cb);
});

gulp.task('copy', function (cb) {
  gulp.src(['src/**/*.*', '!src/**/*.js'])
    .pipe(cache('copy'))
    .pipe(debug())
    .pipe(replace(replaceOptions))
    .pipe(gulp.dest('dist'))
    .on('end', cb);
});

gulp.task('default', ['transpile', 'copy', 'check-port', 'electron:start', 'watch']);
<|endoftext|>


<commit_before>var gulp = require("gulp");
var gulpSync = require("gulp-sync")(gulp);
var path = require("path");

var wonderPackage = require("wonder-package");

var bundleDTS = wonderPackage.bundleDTS;
var compileTs = wonderPackage.compileTs;
var package = wonderPackage.package;
var format = wonderPackage.format;

var config = require("./build/gulp_task/common/config");

var tsFilePaths = config.tsFilePaths;
var tsFileDir = config.tsFileDir;
var distPath = config.distPath;
var tsconfigFile = config.tsconfigFile;
var indexFileDir = config.indexFileDir;
var glslFilePaths = config.glslFilePaths;

var createShaderChunk = require("./build/gulp_task/createInnerFile/ShaderChunk/create").createShaderChunk;

require("./build/gulp_task/clean/clean");
require("./build/gulp_task/test/test");

var generateIndex = require("wonder-tool-generate_es2015_index").generate;
var ts = require("typescript");

gulp.task("generateIndex", function(done) {
    var rootDir = path.join(process.cwd(), "src"),
        destDir = "./src/";

    generateIndex("/", rootDir, ["*.ts", "**/*.ts"], destDir, {
        target: ts.ScriptTarget.ES5,
        module: ts.ModuleKind.System
    }, {
        exclude: ["System.ts", ".d.ts", "Utils.ts"]
    });

    done();
});

gulp.task("compileTsES2015", function(done) {
    compileTs.compileTsES2015(path.join(process.cwd(), tsconfigFile), {
        sourceDir: tsFileDir,
        cwd:"/",
        targetDir:path.join(distPath, "./es2015/")
    }, done);
});

gulp.task("compileTsCommonjs", function(done) {
    compileTs.compileTsCommonjs(path.join(process.cwd(), tsconfigFile), {
        sourceDir: tsFileDir,
        cwd:"/",
        targetDir:path.join(distPath, "./commonjs/")
    }, done);
});

gulp.task("generateDTS", function(done) {
    var indexDTSPath = path.join(indexFileDir, "index.d.ts");

    bundleDTS.generateES2015DTS(indexDTSPath, "wonder.js/dist/es2015", path.join(distPath, "wd.es2015.d.ts"));
    bundleDTS.generateCommonjsDTS(indexDTSPath, "wonder.js/dist/commonjs", path.join(distPath, "wd.commonjs.d.ts"));

    done();
});

gulp.task("rollup", function(done) {
    package.rollup(path.join(process.cwd(), "./rollup.config.js"), done);
});

gulp.task("formatTs", function(done) {
    format.formatTs(tsFilePaths, "/", done);
});

gulp.task("createShaderChunk", function() {
    return createShaderChunk(glslFilePaths);
});

gulp.task("build", gulpSync.sync(["clean", "createShaderChunk", "generateIndex", "compileTsES2015", "compileTsCommonjs", "generateDTS", "rollup", "formatTs"]));

gulp.task("watch", function(){
    var totalPaths = tsFilePaths.concat(glslFilePaths);

    // gulp.watch(totalPaths, gulpSync.sync(["createShaderChunk", "compileTsES2015", "rollup"]));
    // gulp.watch(totalPaths, gulpSync.sync(["compileTsES2015", "rollup"]));
    gulp.watch(totalPaths, gulpSync.sync(["generateIndex", "compileTsES2015"]));
});

gulp.task("watchForTest", function(){
    var totalPaths = tsFilePaths.concat(glslFilePaths);

    gulp.watch(totalPaths, gulpSync.sync(["generateIndex", "compileTsES2015", "rollup"]));
});
<commit_msg>feat: add "rollupRenderWorker", "rollupNoWorker" gulp tasks<commit_after>var gulp = require("gulp");
var gulpSync = require("gulp-sync")(gulp);
var path = require("path");

var wonderPackage = require("wonder-package");

var bundleDTS = wonderPackage.bundleDTS;
var compileTs = wonderPackage.compileTs;
var package = wonderPackage.package;
var format = wonderPackage.format;

var config = require("./build/gulp_task/common/config");

var tsFilePaths = config.tsFilePaths;
var tsFileDir = config.tsFileDir;
var distPath = config.distPath;
var tsconfigFile = config.tsconfigFile;
var indexFileDir = config.indexFileDir;
var glslFilePaths = config.glslFilePaths;

var createShaderChunk = require("./build/gulp_task/createInnerFile/ShaderChunk/create").createShaderChunk;

require("./build/gulp_task/clean/clean");
require("./build/gulp_task/test/test");

var generateIndex = require("wonder-tool-generate_es2015_index").generate;
var ts = require("typescript");

gulp.task("generateIndex", function(done) {
    var rootDir = path.join(process.cwd(), "src"),
        destDir = "./src/";

    generateIndex("/", rootDir, ["*.ts", "**/*.ts"], destDir, {
        target: ts.ScriptTarget.ES5,
        module: ts.ModuleKind.System
    }, {
        exclude: ["System.ts", ".d.ts", "Utils.ts"]
    });

    done();
});

gulp.task("compileTsES2015", function(done) {
    compileTs.compileTsES2015(path.join(process.cwd(), tsconfigFile), {
        sourceDir: tsFileDir,
        cwd:"/",
        targetDir:path.join(distPath, "./es2015/")
    }, done);
});

gulp.task("compileTsCommonjs", function(done) {
    compileTs.compileTsCommonjs(path.join(process.cwd(), tsconfigFile), {
        sourceDir: tsFileDir,
        cwd:"/",
        targetDir:path.join(distPath, "./commonjs/")
    }, done);
});

gulp.task("generateDTS", function(done) {
    var indexDTSPath = path.join(indexFileDir, "index.d.ts");

    bundleDTS.generateES2015DTS(indexDTSPath, "wonder.js/dist/es2015", path.join(distPath, "wd.es2015.d.ts"));
    bundleDTS.generateCommonjsDTS(indexDTSPath, "wonder.js/dist/commonjs", path.join(distPath, "wd.commonjs.d.ts"));

    done();
});

gulp.task("formatTs", function(done) {
    format.formatTs(tsFilePaths, "/", done);
});

gulp.task("createShaderChunk", function() {
    return createShaderChunk(glslFilePaths);
});

gulp.task("rollupRenderWorker", function(done) {
    package.rollup(path.join(process.cwd(), "./rollup.config.js"), done);
});

gulp.task("rollupNoWorker", function(done) {
    package.rollup(path.join(process.cwd(), "./rollup.config.renderWorker.js"), done);
});

gulp.task("rollup", gulpSync.sync(["rollupNoWorker", "rollupRenderWorker"]));

gulp.task("build", gulpSync.sync(["clean", "createShaderChunk", "generateIndex", "compileTsES2015", "compileTsCommonjs", "generateDTS", "rollup", "formatTs"]));

gulp.task("watch", function(){
    var totalPaths = tsFilePaths.concat(glslFilePaths);

    // gulp.watch(totalPaths, gulpSync.sync(["createShaderChunk", "compileTsES2015", "rollup"]));
    // gulp.watch(totalPaths, gulpSync.sync(["compileTsES2015", "rollup"]));
    gulp.watch(totalPaths, gulpSync.sync(["generateIndex", "compileTsES2015"]));
});

gulp.task("watchForTest", function(){
    var totalPaths = tsFilePaths.concat(glslFilePaths);

    gulp.watch(totalPaths, gulpSync.sync(["generateIndex", "compileTsES2015", "rollup"]));
});

gulp.task("watchForTestNoWorker", function(){
    var totalPaths = tsFilePaths.concat(glslFilePaths);

    gulp.watch(totalPaths, gulpSync.sync(["generateIndex", "compileTsES2015", "rollupNoWorker"]));
});

gulp.task("watchForTestRenderWorker", function(){
    var totalPaths = tsFilePaths.concat(glslFilePaths);

    gulp.watch(totalPaths, gulpSync.sync(["generateIndex", "compileTsES2015", "rollupRenderWorker"]));
});
<|endoftext|>


<commit_before>var gulp = require('gulp');
var uglify = require('gulp-uglify');
var gulpIf = require('gulp-if');
var jshint = require('gulp-jshint');
var rename = require('gulp-rename');
var sass = require('gulp-sass');
var livereload = require('gulp-livereload');
var ts = require('gulp-typescript');

gulp.task('minify', function() {
	gulp.src('./js/*.js')
    .pipe(uglify())
	.pipe(rename({
		suffix: '.min'
	}))
    .pipe(gulp.dest('./js/build/'))
    .pipe(livereload());
});

gulp.task('jsLint', function () {
	gulp.src('./js/*.js')
	.pipe(jshint())
	.pipe(jshint.reporter());
});

gulp.task('sass', function() {
	gulp.src('./css/*.scss')
	.pipe(sass())
	.pipe(gulp.dest('./css/'))
    .pipe(livereload());
});

gulp.task('typescript', function() {
	gulp.src('./typescript/*.ts')
	.pipe(ts({
		out: 'ts-script.js'
	}))
	.pipe(gulp.dest('./js/build'));
});

gulp.task('watch-js', function() {
	livereload.listen();
	gulp.watch(['./js/*.js', './css/*.scss'], ['minify', 'jsLint', 'sass']);
});<commit_msg>Comment out unused code<commit_after>var gulp = require('gulp');
var uglify = require('gulp-uglify');
var gulpIf = require('gulp-if');
var jshint = require('gulp-jshint');
var rename = require('gulp-rename');
var sass = require('gulp-sass');
var livereload = require('gulp-livereload');
//var ts = require('gulp-typescript');

gulp.task('minify', function() {
	gulp.src('./js/*.js')
    .pipe(uglify())
	.pipe(rename({
		suffix: '.min'
	}))
    .pipe(gulp.dest('./js/build/'))
    .pipe(livereload());
});

gulp.task('jsLint', function () {
	gulp.src('./js/*.js')
	.pipe(jshint())
	.pipe(jshint.reporter());
});

gulp.task('sass', function() {
	gulp.src('./css/*.scss')
	.pipe(sass())
	.pipe(gulp.dest('./css/'))
    .pipe(livereload());
});

//gulp.task('typescript', function() {
//	gulp.src('./typescript/*.ts')
//	.pipe(ts({
//		out: 'ts-script.js'
//	}))
//	.pipe(gulp.dest('./js/build'));
//});

gulp.task('watch-js', function() {
	livereload.listen();
	gulp.watch(['./js/*.js', './css/*.scss'], ['minify', 'jsLint', 'sass']);
});<|endoftext|>


<commit_before>'use strict';

/*!
 * Monic
 * https://github.com/MonicBuilder/Monic
 *
 * Released under the MIT license
 * https://github.com/MonicBuilder/Monic/blob/master/LICENSE
 */

const
	gulp = require('gulp'),
	async = require('async'),
	through = require('through2'),
	fs = require('fs');

const
	babel = require('gulp-babel'),
	bump = require('gulp-bump'),
	header = require('gulp-header'),
	replace = require('gulp-replace'),
	cached = require('gulp-cached'),
	run = require('gulp-run');

function getVersion() {
	const file = fs.readFileSync('./monic.js');
	return /VERSION\s*(?::|=)\s*\[(\d+,\s*\d+,\s*\d+)]/.exec(file)[1]
		.split(/\s*,\s*/)
		.join('.');
}

function getHead(opt_version) {
	return '' +
		'/*!\n' +
		' * Monic' + (opt_version ? ' v' + getVersion() : '') + '\n' +
		' * https://github.com/MonicBuilder/Monic\n' +
		' *\n' +
		' * Released under the MIT license\n' +
		' * https://github.com/MonicBuilder/Monic/blob/master/LICENSE\n';
}

function error(cb) {
	return (err) => {
		console.error(err.message);
		cb();
	};
}

const
	headRgxp = /(\/\*![\s\S]*?\*\/\n{2})/;

let
	readyToWatcher = null;

gulp.task('copyright', (cb) => {
	gulp.src('./LICENSE')
		.pipe(replace(/(Copyright \(c\) )(\d+)-?(\d*)/, (sstr, intro, from, to) => {
			const year = new Date().getFullYear();
			return intro + from + (to || from != year ? '-' + year : '');
		}))

		.pipe(gulp.dest('./'))
		.on('end', cb);
});

gulp.task('head', (cb) => {
	readyToWatcher = false;

	const
		fullHead = `${getHead()} */\n\n`;

	function test() {
		return through.obj(function (file, enc, cb) {
			if (!headRgxp.exec(file.contents.toString()) || RegExp.$1 !== fullHead) {
				this.push(file);
			}

			return cb();
		});
	}

	async.parallel([
		(cb) => {
			gulp.src(['./@(src|test)/*.js', './@(monic|gulpfile).js'], {base: './'})
				.pipe(test())
				.pipe(replace(headRgxp, ''))
				.pipe(header(fullHead))
				.pipe(gulp.dest('./'))
				.on('end', cb);
		},

		(cb) => {
			gulp.src('./bin/monic.js')
				.pipe(test())
				.pipe(replace(headRgxp, ''))
				.pipe(replace(/^#!.*\n{2}/, (sstr) => sstr + fullHead))
				.pipe(gulp.dest('./bin'))
				.on('end', cb);
		}

	], () => {
		readyToWatcher = true;
		cb();
	});
});

gulp.task('build', ['bump'], (cb) => {
	const fullHead =
		getHead(true) +
		' *\n' +
		' * Date: ' + new Date().toUTCString() + '\n' +
		' */\n\n';

	gulp.src('./src/*.js')
		.pipe(cached('build'))
		.pipe(replace(headRgxp, ''))
		.pipe(babel())
		.on('error', error(cb))
		.pipe(header(fullHead))
		.pipe(gulp.dest('./dist'))
		.on('end', cb);
});

gulp.task('bump', (cb) => {
	gulp.src('./*.json')
		.pipe(bump({version: getVersion()}))
		.pipe(gulp.dest('./'))
		.on('end', cb);
});

gulp.task('npmignore', (cb) => {
	gulp.src('./.npmignore')
		.pipe(replace(/([\s\S]*?)(?=# NPM ignore list)/, fs.readFileSync('./.gitignore') + '\n'))
		.pipe(gulp.dest('./'))
		.on('end', cb);
});

function test(cb) {
	run('node test').exec()
		.on('error', error(cb))
		.on('finish', cb);
}

gulp.task('full-build', ['build'], test);
gulp.task('test', test);
gulp.task('yaspeller', (cb) => {
	run('yaspeller ./').exec()
		.on('error', error(cb))
		.on('finish', cb);
});

gulp.task('watch', ['default'], () => {
	function unbind(name) {
		return (e) => {
			if (e.type === 'deleted') {
				delete cached.caches[name][e.path];
			}
		};
	}

	async.whilst(
		() =>
			readyToWatcher === false,

		(cb) =>
			setTimeout(cb, 500),

		() => {
			gulp.watch('./src/*.js', ['full-build']).on('change', unbind('build'));
			gulp.watch('./monic.js', ['bump']);
			gulp.watch(['./test/**/*', './monic.js'], ['test']);
			gulp.watch('./*.md', ['yaspeller']);
			gulp.watch('./.gitignore', ['npmignore']);
		}

	);
});

gulp.task('default', ['copyright', 'head', 'full-build', 'yaspeller', 'npmignore']);
<commit_msg>:art:<commit_after>'use strict';

/*!
 * Monic
 * https://github.com/MonicBuilder/Monic
 *
 * Released under the MIT license
 * https://github.com/MonicBuilder/Monic/blob/master/LICENSE
 */

const
	gulp = require('gulp'),
	async = require('async'),
	through = require('through2'),
	fs = require('fs');

const
	babel = require('gulp-babel'),
	bump = require('gulp-bump'),
	header = require('gulp-header'),
	replace = require('gulp-replace'),
	cached = require('gulp-cached'),
	run = require('gulp-run');

function getVersion() {
	const file = fs.readFileSync('./monic.js');
	return /VERSION\s*(?::|=)\s*\[(\d+,\s*\d+,\s*\d+)]/.exec(file)[1]
		.split(/\s*,\s*/)
		.join('.');
}

function getHead(opt_version) {
	return '' +
		'/*!\n' +
		` * Monic${opt_version ? ' v' + getVersion() : ''}\n` +
		' * https://github.com/MonicBuilder/Monic\n' +
		' *\n' +
		' * Released under the MIT license\n' +
		' * https://github.com/MonicBuilder/Monic/blob/master/LICENSE\n';
}

function error(cb) {
	return (err) => {
		console.error(err.message);
		cb();
	};
}

const
	headRgxp = /(\/\*![\s\S]*?\*\/\n{2})/;

let
	readyToWatcher = null;

gulp.task('copyright', (cb) => {
	gulp.src('./LICENSE')
		.pipe(replace(/(Copyright \(c\) )(\d+)-?(\d*)/, (sstr, intro, from, to) => {
			const year = new Date().getFullYear();
			return intro + from + (to || from != year ? '-' + year : '');
		}))

		.pipe(gulp.dest('./'))
		.on('end', cb);
});

gulp.task('head', (cb) => {
	readyToWatcher = false;

	const
		fullHead = `${getHead()} */\n\n`;

	function test() {
		return through.obj(function (file, enc, cb) {
			if (!headRgxp.exec(file.contents.toString()) || RegExp.$1 !== fullHead) {
				this.push(file);
			}

			return cb();
		});
	}

	async.parallel([
		(cb) => {
			gulp.src(['./@(src|test)/*.js', './@(monic|gulpfile).js'], {base: './'})
				.pipe(test())
				.pipe(replace(headRgxp, ''))
				.pipe(header(fullHead))
				.pipe(gulp.dest('./'))
				.on('end', cb);
		},

		(cb) => {
			gulp.src('./bin/monic.js')
				.pipe(test())
				.pipe(replace(headRgxp, ''))
				.pipe(replace(/^#!.*\n{2}/, (sstr) => sstr + fullHead))
				.pipe(gulp.dest('./bin'))
				.on('end', cb);
		}

	], () => {
		readyToWatcher = true;
		cb();
	});
});

gulp.task('build', ['bump'], (cb) => {
	const fullHead =
		getHead(true) +
		' *\n' +
		` * Date: ${new Date().toUTCString()}\n` +
		' */\n\n';

	gulp.src('./src/*.js')
		.pipe(cached('build'))
		.pipe(replace(headRgxp, ''))
		.pipe(babel())
		.on('error', error(cb))
		.pipe(header(fullHead))
		.pipe(gulp.dest('./dist'))
		.on('end', cb);
});

gulp.task('bump', (cb) => {
	gulp.src('./*.json')
		.pipe(bump({version: getVersion()}))
		.pipe(gulp.dest('./'))
		.on('end', cb);
});

gulp.task('npmignore', (cb) => {
	gulp.src('./.npmignore')
		.pipe(replace(/([\s\S]*?)(?=# NPM ignore list)/, `${fs.readFileSync('./.gitignore')}\n`))
		.pipe(gulp.dest('./'))
		.on('end', cb);
});

function test(cb) {
	run('node test').exec()
		.on('error', error(cb))
		.on('finish', cb);
}

gulp.task('full-build', ['build'], test);
gulp.task('test', test);
gulp.task('yaspeller', (cb) => {
	run('yaspeller ./').exec()
		.on('error', error(cb))
		.on('finish', cb);
});

gulp.task('watch', ['default'], () => {
	function unbind(name) {
		return (e) => {
			if (e.type === 'deleted') {
				delete cached.caches[name][e.path];
			}
		};
	}

	async.whilst(
		() =>
			readyToWatcher === false,

		(cb) =>
			setTimeout(cb, 500),

		() => {
			gulp.watch('./src/*.js', ['full-build']).on('change', unbind('build'));
			gulp.watch('./monic.js', ['bump']);
			gulp.watch(['./test/**/*', './monic.js'], ['test']);
			gulp.watch('./*.md', ['yaspeller']);
			gulp.watch('./.gitignore', ['npmignore']);
		}

	);
});

gulp.task('default', ['copyright', 'head', 'full-build', 'yaspeller', 'npmignore']);
<|endoftext|>


<commit_before>const browserify = require('browserify');
const buffer = require('vinyl-buffer');
const del = require('del');
const frontmatter = require('frontmatter');
const fs = require('fs');
const glob = require('glob');
const gulp = require('gulp');
const htmlMinifier = require('html-minifier').minify;
const runSequence = require('run-sequence');
const sass = require('gulp-sass');
const source = require('vinyl-source-stream');
const spawn = require('child_process').spawn;
const swPrecache = require('sw-precache');

const BUILD_DIR = 'build';

gulp.task('clean', () => {
  return del(BUILD_DIR);
});

gulp.task('jekyll:build', callback => {
  spawn('bundle', ['exec', 'jekyll', 'build', '--destination', BUILD_DIR], {stdio: 'inherit'})
    .on('exit', callback);
});

gulp.task('site-metadata', callback => {
  const posts = glob.sync('_posts/**/*.markdown').map(post => {
    const markdown = fs.readFileSync(post, 'utf-8');
    const parsedFrontmatter = frontmatter(markdown);
    return {
      url: post.replace(/^_posts\//, '').replace(/-/g, '/').replace('markdown', 'html'),
      title: parsedFrontmatter.data.title,
      date: parsedFrontmatter.data.date,
      excerpt: parsedFrontmatter.data.excerpt
    };
  }).sort((a, b) => a.date < b.date);

  fs.writeFile(`${BUILD_DIR}/posts.json`, JSON.stringify(posts), callback);
});

gulp.task('copy-raw-files', () => {
  // See https://github.com/blog/572-bypassing-jekyll-on-github-pages
  fs.closeSync(fs.openSync(`${BUILD_DIR}/.nojekyll`, 'w'));

  return gulp.src([
    '{_includes,_layouts,_posts}/**/*.{html,markdown}',
    '_config.yml'
  ]).pipe(gulp.dest(BUILD_DIR));
});

gulp.task('minify:html', () => {
  glob.sync(`${BUILD_DIR}/**/*.html`)
    .filter(file => !file.startsWith(`${BUILD_DIR}/_`))
    .forEach(file => {
      const originalHtml = fs.readFileSync(file, 'utf-8');
      const minifiedHtml = htmlMinifier(originalHtml, {
        collapseWhitespace: true,
        decodeEntities: true,
      });
      fs.writeFileSync(file, minifiedHtml);
    });
});

const bundler = browserify({
  entries: 'src/jekyll-behavior-import.js',
}).transform('babelify', {
  plugins: ['transform-async-to-generator', 'transform-es2015-modules-commonjs']
});

gulp.task('bundle', () => {
  return bundler.bundle()
    .on('error', console.error)
    .pipe(source('jekyll-behavior-import.js'))
    .pipe(buffer())
    .pipe(gulp.dest(BUILD_DIR));
});

gulp.task('bundle:watch', ['bundle'], () => {
  return gulp.watch('src/**/*.js', ['bundle']);
});

gulp.task('minify:js', callback => {
  spawn('node_modules/.bin/babili', [
    `${BUILD_DIR}/jekyll-behavior-import.js`,
    '-d', '.',
    '--no-comments'
  ]).on('exit', callback);
});

gulp.task('service-worker', () => {
  return swPrecache.write(`${BUILD_DIR}/service-worker.js`, {
    stripPrefix: `${BUILD_DIR}/`,
    staticFileGlobs: [
      '_config.yml',
      'posts.json',
      'manifest.json',
      '_layouts/**/*.html',
      '_includes/**/*.html',
      '_posts/**/*.markdown'
    ].map(glob => `${BUILD_DIR}/${glob}`),
    importScripts: ['jekyll-behavior-import.js'],
    runtimeCaching: [{
      urlPattern: /\/assets\/images\//,
      handler: 'cacheFirst',
      options: {
        cache: {
          maxEntries: 20,
          name: 'images'
        }
      }
    }]
  });
});

gulp.task('build', callback => {
  runSequence(
    'clean',
    'jekyll:build',
    ['site-metadata', 'copy-raw-files', 'bundle'],
    ['minify:html', 'minify:js'],
    'service-worker',
    callback
  );
});

gulp.task('deploy', ['build'], callback => {
  spawn('node_modules/.bin/firebase', ['deploy'])
    .on('exit', callback);
});

gulp.task('localhost', callback => {
  spawn('node_modules/.bin/http-server', [
    BUILD_DIR,
    '-p', '8000',
    '-a', '127.0.0.1',
    '-c', '-1'
  ]).on('exit', callback);
});
<commit_msg>Switch to firebase serve<commit_after>const browserify = require('browserify');
const buffer = require('vinyl-buffer');
const del = require('del');
const frontmatter = require('frontmatter');
const fs = require('fs');
const glob = require('glob');
const gulp = require('gulp');
const htmlMinifier = require('html-minifier').minify;
const runSequence = require('run-sequence');
const source = require('vinyl-source-stream');
const spawn = require('child_process').spawn;
const swPrecache = require('sw-precache');

const BUILD_DIR = 'build';

gulp.task('clean', () => {
  return del(BUILD_DIR);
});

gulp.task('jekyll:build', callback => {
  spawn('bundle', ['exec', 'jekyll', 'build', '--destination', BUILD_DIR], {stdio: 'inherit'})
    .on('exit', callback);
});

gulp.task('site-metadata', callback => {
  const posts = glob.sync('_posts/**/*.markdown').map(post => {
    const markdown = fs.readFileSync(post, 'utf-8');
    const parsedFrontmatter = frontmatter(markdown);
    return {
      url: post.replace(/^_posts\//, '').replace(/-/g, '/').replace('markdown', 'html'),
      title: parsedFrontmatter.data.title,
      date: parsedFrontmatter.data.date,
      excerpt: parsedFrontmatter.data.excerpt
    };
  }).sort((a, b) => a.date < b.date);

  fs.writeFile(`${BUILD_DIR}/posts.json`, JSON.stringify(posts), callback);
});

gulp.task('copy-raw-files', () => {
  // See https://github.com/blog/572-bypassing-jekyll-on-github-pages
  fs.closeSync(fs.openSync(`${BUILD_DIR}/.nojekyll`, 'w'));

  return gulp.src([
    '{_includes,_layouts,_posts}/**/*.{html,markdown}',
    '_config.yml'
  ]).pipe(gulp.dest(BUILD_DIR));
});

gulp.task('minify:html', () => {
  glob.sync(`${BUILD_DIR}/**/*.html`)
    .filter(file => !file.startsWith(`${BUILD_DIR}/_`))
    .forEach(file => {
      const originalHtml = fs.readFileSync(file, 'utf-8');
      const minifiedHtml = htmlMinifier(originalHtml, {
        collapseWhitespace: true,
        decodeEntities: true,
      });
      fs.writeFileSync(file, minifiedHtml);
    });
});

const bundler = browserify({
  entries: 'src/jekyll-behavior-import.js',
}).transform('babelify', {
  plugins: ['transform-async-to-generator', 'transform-es2015-modules-commonjs']
});

gulp.task('bundle', () => {
  return bundler.bundle()
    .on('error', console.error)
    .pipe(source('jekyll-behavior-import.js'))
    .pipe(buffer())
    .pipe(gulp.dest(BUILD_DIR));
});

gulp.task('bundle:watch', ['bundle'], () => {
  return gulp.watch('src/**/*.js', ['bundle']);
});

gulp.task('minify:js', callback => {
  spawn('node_modules/.bin/babili', [
    `${BUILD_DIR}/jekyll-behavior-import.js`,
    '-d', '.',
    '--no-comments'
  ]).on('exit', callback);
});

gulp.task('service-worker', () => {
  return swPrecache.write(`${BUILD_DIR}/service-worker.js`, {
    stripPrefix: `${BUILD_DIR}/`,
    staticFileGlobs: [
      '_config.yml',
      'posts.json',
      'manifest.json',
      '_layouts/**/*.html',
      '_includes/**/*.html',
      '_posts/**/*.markdown'
    ].map(glob => `${BUILD_DIR}/${glob}`),
    importScripts: ['jekyll-behavior-import.js'],
    runtimeCaching: [{
      urlPattern: /\/assets\/images\//,
      handler: 'cacheFirst',
      options: {
        cache: {
          maxEntries: 20,
          name: 'images'
        }
      }
    }]
  });
});

gulp.task('build', callback => {
  runSequence(
    'clean',
    'jekyll:build',
    ['site-metadata', 'copy-raw-files', 'bundle'],
    ['minify:html', 'minify:js'],
    'service-worker',
    callback
  );
});

gulp.task('deploy', ['build'], callback => {
  spawn('node_modules/.bin/firebase', ['deploy'])
    .on('exit', callback);
});

gulp.task('localhost', callback => {
  // The server is on http://localhost:5000
  spawn('node_modules/.bin/firebase', ['serve'])
    .on('exit', callback);
});
<|endoftext|>


<commit_before>'use strict';
var path = require('path');
var gulp = require('gulp');
var excludeGitignore = require('gulp-exclude-gitignore');
var mocha = require('gulp-mocha');
var istanbul = require('gulp-istanbul');
var nsp = require('gulp-nsp');
var plumber = require('gulp-plumber');
var coveralls = require('gulp-coveralls');

gulp.task('nsp', function (cb) {
    nsp({package: path.resolve('package.json')}, cb);
});

gulp.task('pre-test', function () {
    return gulp.src('src/**/*.js')
        .pipe(excludeGitignore())
        .pipe(istanbul({
            includeUntested: true
        }))
        .pipe(istanbul.hookRequire());
});

gulp.task('test', ['pre-test'], function (cb) {
    var mochaErr;

    gulp.src('test/**/*.js')
        .pipe(plumber())
        .pipe(mocha({reporter: 'spec'}))
        .on('error', function (err) {
            mochaErr = err;
        })
        .pipe(istanbul.writeReports())
        .on('end', function () {
            cb(mochaErr);
        });
});

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

gulp.task('coveralls', ['test'], function () {
    if (!process.env.CI) {
        return;
    }

    return gulp.src(path.join(__dirname, 'coverage/lcov.info'))
        .pipe(coveralls());
});

gulp.task('prepublish', ['nsp']);
gulp.task('default', ['test', 'coveralls']);<commit_msg>EOF EOL<commit_after>'use strict';
var path = require('path');
var gulp = require('gulp');
var excludeGitignore = require('gulp-exclude-gitignore');
var mocha = require('gulp-mocha');
var istanbul = require('gulp-istanbul');
var nsp = require('gulp-nsp');
var plumber = require('gulp-plumber');
var coveralls = require('gulp-coveralls');

gulp.task('nsp', function (cb) {
    nsp({package: path.resolve('package.json')}, cb);
});

gulp.task('pre-test', function () {
    return gulp.src('src/**/*.js')
        .pipe(excludeGitignore())
        .pipe(istanbul({
            includeUntested: true
        }))
        .pipe(istanbul.hookRequire());
});

gulp.task('test', ['pre-test'], function (cb) {
    var mochaErr;

    gulp.src('test/**/*.js')
        .pipe(plumber())
        .pipe(mocha({reporter: 'spec'}))
        .on('error', function (err) {
            mochaErr = err;
        })
        .pipe(istanbul.writeReports())
        .on('end', function () {
            cb(mochaErr);
        });
});

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

gulp.task('coveralls', ['test'], function () {
    if (!process.env.CI) {
        return;
    }

    return gulp.src(path.join(__dirname, 'coverage/lcov.info'))
        .pipe(coveralls());
});

gulp.task('prepublish', ['nsp']);
gulp.task('default', ['test', 'coveralls']);
<|endoftext|>


<commit_before>// See: http://gulpjs.com/

var gulp = require('gulp');
var jshint = require('gulp-jshint');
var jscs = require('gulp-jscs');
var less = require('gulp-less');
var autoprefixer = require('gulp-autoprefixer');
var csso = require('gulp-csso');
var mochaPhantomJS = require('gulp-mocha-phantomjs');

gulp.task('lint', function () {
    return gulp
        .src(['./index.js', './gulpfile.js'])
        .pipe(jshint())
        .pipe(jshint.reporter('jshint-stylish'))
        .pipe(jscs());
});

gulp.task('less', function () {
    gulp.src('./css/style.less')
        .pipe(less())
        .pipe(autoprefixer({
            browsers: ['last 2 versions', 'ie 8'],
            cascade: false,
        }))
        .pipe(csso())
        .pipe(gulp.dest('./css/build'));
});

gulp.task('test', function () {
    return gulp
        .src('./test/index-test.html')
        .pipe(mochaPhantomJS({
            reporter: 'spec',
        }));
});

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

gulp.task('default', ['lint', 'test']);
<commit_msg>Gulp: lint +index-test.js<commit_after>// See: http://gulpjs.com/

var gulp = require('gulp');
var jshint = require('gulp-jshint');
var jscs = require('gulp-jscs');
var less = require('gulp-less');
var autoprefixer = require('gulp-autoprefixer');
var csso = require('gulp-csso');
var mochaPhantomJS = require('gulp-mocha-phantomjs');

gulp.task('lint', function () {
    return gulp
        .src(['./index.js', './test/index-test.js', './gulpfile.js'])
        .pipe(jshint())
        .pipe(jshint.reporter('jshint-stylish'))
        .pipe(jscs());
});

gulp.task('less', function () {
    gulp.src('./css/style.less')
        .pipe(less())
        .pipe(autoprefixer({
            browsers: ['last 2 versions', 'ie 8'],
            cascade: false,
        }))
        .pipe(csso())
        .pipe(gulp.dest('./css/build'));
});

gulp.task('test', function () {
    return gulp
        .src('./test/index-test.html')
        .pipe(mochaPhantomJS({
            reporter: 'spec',
        }));
});

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

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


<commit_before>'use strict';

var autoprefixer = require('gulp-autoprefixer'),
	minify = require('gulp-minify-css'),
	gulp = require('gulp'),
	header = require('gulp-header'),
	sass = require('gulp-sass'),
	sync = require('browser-sync').create();

require('gulp-release-it')(gulp);

// Banner

var pkg = require('./package.json');
var banner = `/**
 * ${ pkg.description }
 * ${ pkg.name } v${ pkg.version }, ${ pkg.homepage }
 * @copyright 2010–${ new Date().getFullYear() } ${ pkg.author.name }, ${ pkg.author.url }
 * @license ${ pkg.license }
 */
`;

// Server

gulp.task('default', ['styles'], function() {
	sync.init({
		notify: false,
		server: {
			baseDir: './',
			routes: {
				'/shower-core': '../shower-core'
			}
		}
	});

	gulp.watch('styles/**/*.scss', ['styles']);
	gulp.watch('index.html').on('change', sync.reload);
});

// Styles

gulp.task('styles', function () {
	return gulp.src('styles/screen-*.scss')
		.pipe(sass().on('error', sass.logError))
		.pipe(autoprefixer())
		.pipe(minify())
		.pipe(header(banner, { pkg: pkg }))
		.pipe(gulp.dest('styles/'))
		.pipe(sync.stream());
});
<commit_msg>Trailing slashes removed, BS ui turned off<commit_after>'use strict';

var autoprefixer = require('gulp-autoprefixer'),
	minify = require('gulp-minify-css'),
	gulp = require('gulp'),
	header = require('gulp-header'),
	sass = require('gulp-sass'),
	sync = require('browser-sync').create();

require('gulp-release-it')(gulp);

// Banner

var pkg = require('./package.json');
var banner = `/**
 * ${ pkg.description }
 * ${ pkg.name } v${ pkg.version }, ${ pkg.homepage }
 * @copyright 2010–${ new Date().getFullYear() } ${ pkg.author.name }, ${ pkg.author.url }
 * @license ${ pkg.license }
 */
`;

// Server

gulp.task('default', ['styles'], function() {
	sync.init({
		ui: false,
		notify: false,
		server: {
			baseDir: '.',
			routes: {
				'/shower-core': '../shower-core'
			}
		}
	});

	gulp.watch('styles/**/*.scss', ['styles']);
	gulp.watch('index.html').on('change', sync.reload);
});

// Styles

gulp.task('styles', function () {
	return gulp.src('styles/screen-*.scss')
		.pipe(sass().on('error', sass.logError))
		.pipe(autoprefixer())
		.pipe(minify())
		.pipe(header(banner, { pkg: pkg }))
		.pipe(gulp.dest('styles'))
		.pipe(sync.stream());
});
<|endoftext|>


<commit_before>/* jshint camelcase:false */
var gulp = require('gulp');
var pkg = require('./package.json');
var common = require('./gulp/common.js');
var plug = require('gulp-load-plugins')();
var env = plug.util.env;
var log = plug.util.log;

gulp.task('help', plug.taskListing);

/**
 * @desc Annotate only
 *  Mostly for show.
 *  See the output of each file?
 *      Uncomment rename, comment concat and uglify
 *  See min'd and concat'd output?
 *      Comment rename, uncomment concat and uglify,
 *      add to index.html, then run it with `gulp serve-dev`.
 */
gulp.task('ngAnnotateTest', function() {
    log('Annotating AngularJS dependencies');
    var source = [].concat(pkg.paths.js);
    return gulp
        // .src(source)
        .src(pkg.paths.client + '/app/avengers/avengers.js')
        .pipe(plug.ngAnnotate({add: true, single_quotes: true}))
        .pipe(plug.rename(function(path) {
            path.extname = '.annotated.js';
        }))
        // .pipe(plug.concat('all.min.js'))
        // .pipe(plug.uglify({mangle: true}))
        // .pipe(gulp.dest(pkg.paths.client + '/app'));
        .pipe(gulp.dest(pkg.paths.client + '/app/avengers'));
});

/**
 * @desc Lint the code
 */
gulp.task('analyze', function() {
    log('Linting the JavaScript');

    var sources = [].concat(pkg.paths.js, pkg.paths.nodejs);
    return gulp
        .src(sources)
        .pipe(plug.jshint('./.jshintrc'))
        .pipe(plug.jshint.reporter('jshint-stylish'))
        .pipe(plug.jscs('./.jscsrc'));
});

/**
 * @desc Create $templateCache from the html templates
 */
gulp.task('templatecache', function() {
    log('Creating an AngularJS $templateCache');

    return gulp
        .src(pkg.paths.htmltemplates)
        .pipe(plug.angularTemplatecache('templates.js', {
            module: 'app.core',
            standalone: false,
            root: 'app/'
        }))
        .pipe(gulp.dest(pkg.paths.stage));
});

/**
 * @desc Minify and bundle the app's JavaScript
 */
gulp.task('js', ['analyze', 'templatecache'], function() {
    log('Bundling, minifying, and copying the app\'s JavaScript');

    var source = [].concat(pkg.paths.js, pkg.paths.stage + 'templates.js');
    return gulp
        .src(source)
       // .pipe(plug.sourcemaps.init()) // get screwed up in the file rev process
        .pipe(plug.concat('all.min.js'))
        .pipe(plug.ngAnnotate({add: true, single_quotes: true}))
        .pipe(plug.bytediff.start())
        .pipe(plug.uglify({mangle: true}))
        .pipe(plug.bytediff.stop(common.bytediffFormatter))
        // .pipe(plug.sourcemaps.write('./'))
        .pipe(gulp.dest(pkg.paths.stage));
});

/**
 * @desc Copy the Vendor JavaScript
 */
gulp.task('vendorjs', function() {
    log('Bundling, minifying, and copying the Vendor JavaScript');
    return gulp.src(pkg.paths.vendorjs)
        .pipe(plug.concat('vendor.min.js'))
        .pipe(plug.bytediff.start())
        .pipe(plug.uglify())
        .pipe(plug.bytediff.stop(common.bytediffFormatter))
        .pipe(gulp.dest(pkg.paths.stage)); // + 'vendor'));
});

/**
 * @desc Minify and bundle the CSS
 */
gulp.task('css', function() {
    log('Bundling, minifying, and copying the app\'s CSS');
    return gulp.src(pkg.paths.css)
        .pipe(plug.concat('all.min.css')) // Before bytediff or after
        .pipe(plug.autoprefixer('last 2 version', '> 5%'))
        .pipe(plug.bytediff.start())
        .pipe(plug.minifyCss({}))
        .pipe(plug.bytediff.stop(common.bytediffFormatter))
//        .pipe(plug.concat('all.min.css')) // Before bytediff or after
        .pipe(gulp.dest(pkg.paths.stage + 'content'));
});

/**
 * @desc Minify and bundle the Vendor CSS
 */
gulp.task('vendorcss', function() {
    log('Compressing, bundling, copying vendor CSS');
    return gulp.src(pkg.paths.vendorcss)
        .pipe(plug.concat('vendor.min.css'))
        .pipe(plug.bytediff.start())
        .pipe(plug.minifyCss({}))
        .pipe(plug.bytediff.stop(common.bytediffFormatter))
        .pipe(gulp.dest(pkg.paths.stage + 'content'));
});

/**
 * @desc Copy fonts
 */
gulp.task('fonts', function() {
    var dest = pkg.paths.stage + 'fonts';
    log('Copying fonts');
    return gulp
        .src(pkg.paths.fonts)
        .pipe(gulp.dest(dest));
});

/**
 * @desc Compress images
 */
gulp.task('images', function() {
    var dest = pkg.paths.stage + 'content/images';
    log('Compressing, caching, and copying images');
    return gulp
        .src(pkg.paths.images)
        .pipe(plug.cache(plug.imagemin({optimizationLevel: 3})))
        .pipe(gulp.dest(dest));
});

/**
 * @desc Inject all the files into the new index.html
 * rev, but no map
 */
gulp.task('rev-and-inject',
    ['js', 'vendorjs', 'css', 'vendorcss'], function() {
        log('Rev\'ing files and building index.html');

        var minified = pkg.paths.stage + '**/*.min.*';
        var index = pkg.paths.client + 'index.html';
        var minFilter = plug.filter(['**/*.min.*', '!**/*.map']);
        var indexFilter = plug.filter(['index.html']);

        var stream = gulp
            // Write the revisioned files
            .src([].concat(minified, index)) // add all staged min files and index.html
            .pipe(minFilter) // filter the stream to minified css and js
            .pipe(plug.rev()) // create files with rev's
            .pipe(gulp.dest(pkg.paths.stage)) // write the rev files
            .pipe(minFilter.restore()) // remove filter, back to original stream

            // inject the files into index.html
            .pipe(indexFilter) // filter to index.html
            .pipe(inject('content/vendor.min.css', 'inject-vendor'))
            .pipe(inject('content/all.min.css'))
            .pipe(inject('vendor.min.js', 'inject-vendor'))
            .pipe(inject('all.min.js'))
            .pipe(gulp.dest(pkg.paths.stage)) // write the rev files
            .pipe(indexFilter.restore()) // remove filter, back to original stream

            // replace the files referenced in index.html with the rev'd files
            .pipe(plug.revReplace())         // Substitute in new filenames
            .pipe(gulp.dest(pkg.paths.stage)) // write the index.html file changes
            .pipe(plug.rev.manifest()) // create the manifest (must happen last or we screw up the injection)
            .pipe(gulp.dest(pkg.paths.stage)); // write the manifest

        function inject(path, name) {
            var glob = pkg.paths.stage + path;
            var options = {
                ignorePath: pkg.paths.stage.substring(1),
                read: false
            };
            if (name) { options.name = name; }
            return plug.inject(gulp.src(glob), options);
        }
    });

/**
 * @desc Stage the optimized app
 */
gulp.task('stage',
    ['rev-and-inject', 'images', 'fonts'], function() {
        log('Staging the optimized app');

        return gulp.src('').pipe(plug.notify({
            onLast: true,
            message: 'Deployed code to stage!'
        }));
    });

/**
 * @desc Remove all files from the build folder
 * One way to run clean before all tasks is to run
 * from the cmd line: gulp clean && gulp stage
 */
gulp.task('clean', function() {
    var paths = pkg.paths.build;
    log('Cleaning: ' + plug.util.colors.blue(paths));

    return gulp
        .src(paths, {read: false})
        .pipe(plug.rimraf({force: true}));
});

/**
 * @desc Watch files and build
 */
gulp.task('watch', function() {
    log('Watching all files');

    var css = ['gulpfile.js'].concat(pkg.paths.css, pkg.paths.vendorcss);
    var images = ['gulpfile.js'].concat(pkg.paths.images);
    var js = ['gulpfile.js'].concat(pkg.paths.js);

    gulp
        .watch(js, ['js', 'vendorjs'])
        .on('change', logWatch);

    gulp
        .watch(css, ['css', 'vendorcss'])
        .on('change', logWatch);

    gulp
        .watch(images, ['images'])
        .on('change', logWatch);

    function logWatch(event) {
        log('*** File ' + event.path + ' was ' + event.type + ', running tasks...');
    }
});

/**
 * @desc Run all tests
 */
gulp.task('test-serve-midway', function() {
    log('Pre test serve');
    var testFiles = [pkg.paths.test + 'spec.mocha/*[Ss]pec.js'];
    var options = {
        script: pkg.paths.server + 'app.js',
        env: {'NODE_ENV': 'dev', 'PORT': 8888}
    };
});

//gulp.task('test', ['test-serve-midway'], function() {
gulp.task('test', function() {
    log('Running tests');
    var testFiles = [pkg.paths.test + 'spec.mocha/*[Ss]pec.js'];
    // var options = {
    //     script: pkg.paths.server + 'app.js',
    //     env: {'NODE_ENV': 'dev', 'PORT': 8888}
    // };
    // plug.nodemon(options);

    return gulp
        .src('./useKarmaConfAndNotThis')
        .pipe(plug.plumber())
        .pipe(plug.karma({
            configFile: pkg.paths.test + '/karma.conf.js',
//            singleRun: true,
            delay: 5,
            action: 'run'  // run or watch
        }))
        // .pipe(plug.plumber.stop())
        .on('error', function(err) {
            // failed tests cause gulp to exit
            log(err);
            throw err;
        });
});

/**
 * serve the dev environment, with debug,
 * and with node inspector
 */
gulp.task('serve-dev-debug', function() {
    serve({env: 'dev', debug: '--debug'});
    startLivereload('development');
});

/**
 * serve the dev environment, with debug-brk,
 * and with node inspector
 */
gulp.task('serve-dev-debug-brk', function() {
    serve({env: 'dev', debug: '--debug-brk'});
    startLivereload('development');
});

/**
 * serve the dev environment
 */
gulp.task('serve-dev', function() {
    serve({env: 'dev'});
    startLivereload('development');
});

/**
 * serve the staging environment
 */
gulp.task('serve-stage', function() {
    serve({env: 'stage'});
    startLivereload('stage');
});

function startLivereload(env) {

    //TODO: gulp-livereload is failing due to tiny-lr issue. Re-enable when fixed.

    // var path = (env === 'stage' ? [pkg.paths.stage, pkg.paths.client + '/**'] : [pkg.paths.client + '/**']);
    // var options = {auto: true};
    // plug.livereload.listen(options);
    // gulp
    //     .watch(path)
    //     .on('change', function(file) {
    //         plug.livereload.changed(file.path);
    //     });

    // log('Serving from ' + env);
}

function serve(args) {
    var options = {
        script: pkg.paths.server + 'app.js',
        delayTime: 1,
        ext: 'html js',
        env: {'NODE_ENV': args.env},
        watch: [
            'gulpfile.js',
            'package.json',
            pkg.paths.server,
            pkg.paths.client
        ]
    };

    if (args.debug) {
        gulp.src('', {read: false})
            .pipe(plug.shell(['node-inspector']));
        options.nodeArgs = [args.debug + '=5858'];
    }

    return plug.nodemon(options)
        //.on('change', tasks)
        .on('restart', function() {
            log('restarted!');
        });
}<commit_msg>modular: clarify "run v. watch" comment in gulp test task<commit_after>/* jshint camelcase:false */
var gulp = require('gulp');
var pkg = require('./package.json');
var common = require('./gulp/common.js');
var plug = require('gulp-load-plugins')();
var env = plug.util.env;
var log = plug.util.log;

gulp.task('help', plug.taskListing);

/**
 * @desc Annotate only
 *  Mostly for show.
 *  See the output of each file?
 *      Uncomment rename, comment concat and uglify
 *  See min'd and concat'd output?
 *      Comment rename, uncomment concat and uglify,
 *      add to index.html, then run it with `gulp serve-dev`.
 */
gulp.task('ngAnnotateTest', function() {
    log('Annotating AngularJS dependencies');
    var source = [].concat(pkg.paths.js);
    return gulp
        // .src(source)
        .src(pkg.paths.client + '/app/avengers/avengers.js')
        .pipe(plug.ngAnnotate({add: true, single_quotes: true}))
        .pipe(plug.rename(function(path) {
            path.extname = '.annotated.js';
        }))
        // .pipe(plug.concat('all.min.js'))
        // .pipe(plug.uglify({mangle: true}))
        // .pipe(gulp.dest(pkg.paths.client + '/app'));
        .pipe(gulp.dest(pkg.paths.client + '/app/avengers'));
});

/**
 * @desc Lint the code
 */
gulp.task('analyze', function() {
    log('Linting the JavaScript');

    var sources = [].concat(pkg.paths.js, pkg.paths.nodejs);
    return gulp
        .src(sources)
        .pipe(plug.jshint('./.jshintrc'))
        .pipe(plug.jshint.reporter('jshint-stylish'))
        .pipe(plug.jscs('./.jscsrc'));
});

/**
 * @desc Create $templateCache from the html templates
 */
gulp.task('templatecache', function() {
    log('Creating an AngularJS $templateCache');

    return gulp
        .src(pkg.paths.htmltemplates)
        .pipe(plug.angularTemplatecache('templates.js', {
            module: 'app.core',
            standalone: false,
            root: 'app/'
        }))
        .pipe(gulp.dest(pkg.paths.stage));
});

/**
 * @desc Minify and bundle the app's JavaScript
 */
gulp.task('js', ['analyze', 'templatecache'], function() {
    log('Bundling, minifying, and copying the app\'s JavaScript');

    var source = [].concat(pkg.paths.js, pkg.paths.stage + 'templates.js');
    return gulp
        .src(source)
       // .pipe(plug.sourcemaps.init()) // get screwed up in the file rev process
        .pipe(plug.concat('all.min.js'))
        .pipe(plug.ngAnnotate({add: true, single_quotes: true}))
        .pipe(plug.bytediff.start())
        .pipe(plug.uglify({mangle: true}))
        .pipe(plug.bytediff.stop(common.bytediffFormatter))
        // .pipe(plug.sourcemaps.write('./'))
        .pipe(gulp.dest(pkg.paths.stage));
});

/**
 * @desc Copy the Vendor JavaScript
 */
gulp.task('vendorjs', function() {
    log('Bundling, minifying, and copying the Vendor JavaScript');
    return gulp.src(pkg.paths.vendorjs)
        .pipe(plug.concat('vendor.min.js'))
        .pipe(plug.bytediff.start())
        .pipe(plug.uglify())
        .pipe(plug.bytediff.stop(common.bytediffFormatter))
        .pipe(gulp.dest(pkg.paths.stage)); // + 'vendor'));
});

/**
 * @desc Minify and bundle the CSS
 */
gulp.task('css', function() {
    log('Bundling, minifying, and copying the app\'s CSS');
    return gulp.src(pkg.paths.css)
        .pipe(plug.concat('all.min.css')) // Before bytediff or after
        .pipe(plug.autoprefixer('last 2 version', '> 5%'))
        .pipe(plug.bytediff.start())
        .pipe(plug.minifyCss({}))
        .pipe(plug.bytediff.stop(common.bytediffFormatter))
//        .pipe(plug.concat('all.min.css')) // Before bytediff or after
        .pipe(gulp.dest(pkg.paths.stage + 'content'));
});

/**
 * @desc Minify and bundle the Vendor CSS
 */
gulp.task('vendorcss', function() {
    log('Compressing, bundling, copying vendor CSS');
    return gulp.src(pkg.paths.vendorcss)
        .pipe(plug.concat('vendor.min.css'))
        .pipe(plug.bytediff.start())
        .pipe(plug.minifyCss({}))
        .pipe(plug.bytediff.stop(common.bytediffFormatter))
        .pipe(gulp.dest(pkg.paths.stage + 'content'));
});

/**
 * @desc Copy fonts
 */
gulp.task('fonts', function() {
    var dest = pkg.paths.stage + 'fonts';
    log('Copying fonts');
    return gulp
        .src(pkg.paths.fonts)
        .pipe(gulp.dest(dest));
});

/**
 * @desc Compress images
 */
gulp.task('images', function() {
    var dest = pkg.paths.stage + 'content/images';
    log('Compressing, caching, and copying images');
    return gulp
        .src(pkg.paths.images)
        .pipe(plug.cache(plug.imagemin({optimizationLevel: 3})))
        .pipe(gulp.dest(dest));
});

/**
 * @desc Inject all the files into the new index.html
 * rev, but no map
 */
gulp.task('rev-and-inject',
    ['js', 'vendorjs', 'css', 'vendorcss'], function() {
        log('Rev\'ing files and building index.html');

        var minified = pkg.paths.stage + '**/*.min.*';
        var index = pkg.paths.client + 'index.html';
        var minFilter = plug.filter(['**/*.min.*', '!**/*.map']);
        var indexFilter = plug.filter(['index.html']);

        var stream = gulp
            // Write the revisioned files
            .src([].concat(minified, index)) // add all staged min files and index.html
            .pipe(minFilter) // filter the stream to minified css and js
            .pipe(plug.rev()) // create files with rev's
            .pipe(gulp.dest(pkg.paths.stage)) // write the rev files
            .pipe(minFilter.restore()) // remove filter, back to original stream

            // inject the files into index.html
            .pipe(indexFilter) // filter to index.html
            .pipe(inject('content/vendor.min.css', 'inject-vendor'))
            .pipe(inject('content/all.min.css'))
            .pipe(inject('vendor.min.js', 'inject-vendor'))
            .pipe(inject('all.min.js'))
            .pipe(gulp.dest(pkg.paths.stage)) // write the rev files
            .pipe(indexFilter.restore()) // remove filter, back to original stream

            // replace the files referenced in index.html with the rev'd files
            .pipe(plug.revReplace())         // Substitute in new filenames
            .pipe(gulp.dest(pkg.paths.stage)) // write the index.html file changes
            .pipe(plug.rev.manifest()) // create the manifest (must happen last or we screw up the injection)
            .pipe(gulp.dest(pkg.paths.stage)); // write the manifest

        function inject(path, name) {
            var glob = pkg.paths.stage + path;
            var options = {
                ignorePath: pkg.paths.stage.substring(1),
                read: false
            };
            if (name) { options.name = name; }
            return plug.inject(gulp.src(glob), options);
        }
    });

/**
 * @desc Stage the optimized app
 */
gulp.task('stage',
    ['rev-and-inject', 'images', 'fonts'], function() {
        log('Staging the optimized app');

        return gulp.src('').pipe(plug.notify({
            onLast: true,
            message: 'Deployed code to stage!'
        }));
    });

/**
 * @desc Remove all files from the build folder
 * One way to run clean before all tasks is to run
 * from the cmd line: gulp clean && gulp stage
 */
gulp.task('clean', function() {
    var paths = pkg.paths.build;
    log('Cleaning: ' + plug.util.colors.blue(paths));

    return gulp
        .src(paths, {read: false})
        .pipe(plug.rimraf({force: true}));
});

/**
 * @desc Watch files and build
 */
gulp.task('watch', function() {
    log('Watching all files');

    var css = ['gulpfile.js'].concat(pkg.paths.css, pkg.paths.vendorcss);
    var images = ['gulpfile.js'].concat(pkg.paths.images);
    var js = ['gulpfile.js'].concat(pkg.paths.js);

    gulp
        .watch(js, ['js', 'vendorjs'])
        .on('change', logWatch);

    gulp
        .watch(css, ['css', 'vendorcss'])
        .on('change', logWatch);

    gulp
        .watch(images, ['images'])
        .on('change', logWatch);

    function logWatch(event) {
        log('*** File ' + event.path + ' was ' + event.type + ', running tasks...');
    }
});

/**
 * @desc Run all tests
 */
gulp.task('test-serve-midway', function() {
    log('Pre test serve');
    var testFiles = [pkg.paths.test + 'spec.mocha/*[Ss]pec.js'];
    var options = {
        script: pkg.paths.server + 'app.js',
        env: {'NODE_ENV': 'dev', 'PORT': 8888}
    };
});

//gulp.task('test', ['test-serve-midway'], function() {
gulp.task('test', function() {
    log('Running tests');
    var testFiles = [pkg.paths.test + 'spec.mocha/*[Ss]pec.js'];
    // var options = {
    //     script: pkg.paths.server + 'app.js',
    //     env: {'NODE_ENV': 'dev', 'PORT': 8888}
    // };
    // plug.nodemon(options);

    return gulp
        .src('./useKarmaConfAndNotThis')
        .pipe(plug.plumber())
        .pipe(plug.karma({
            configFile: pkg.paths.test + '/karma.conf.js',
//            singleRun: true,
            delay: 5,
            action: 'run'  // run (once) or watch (keep open)
        }))
        // .pipe(plug.plumber.stop())
        .on('error', function(err) {
            // failed tests cause gulp to exit
            log(err);
            throw err;
        });
});

/**
 * serve the dev environment, with debug,
 * and with node inspector
 */
gulp.task('serve-dev-debug', function() {
    serve({env: 'dev', debug: '--debug'});
    startLivereload('development');
});

/**
 * serve the dev environment, with debug-brk,
 * and with node inspector
 */
gulp.task('serve-dev-debug-brk', function() {
    serve({env: 'dev', debug: '--debug-brk'});
    startLivereload('development');
});

/**
 * serve the dev environment
 */
gulp.task('serve-dev', function() {
    serve({env: 'dev'});
    startLivereload('development');
});

/**
 * serve the staging environment
 */
gulp.task('serve-stage', function() {
    serve({env: 'stage'});
    startLivereload('stage');
});

function startLivereload(env) {

    //TODO: gulp-livereload is failing due to tiny-lr issue. Re-enable when fixed.

    // var path = (env === 'stage' ? [pkg.paths.stage, pkg.paths.client + '/**'] : [pkg.paths.client + '/**']);
    // var options = {auto: true};
    // plug.livereload.listen(options);
    // gulp
    //     .watch(path)
    //     .on('change', function(file) {
    //         plug.livereload.changed(file.path);
    //     });

    // log('Serving from ' + env);
}

function serve(args) {
    var options = {
        script: pkg.paths.server + 'app.js',
        delayTime: 1,
        ext: 'html js',
        env: {'NODE_ENV': args.env},
        watch: [
            'gulpfile.js',
            'package.json',
            pkg.paths.server,
            pkg.paths.client
        ]
    };

    if (args.debug) {
        gulp.src('', {read: false})
            .pipe(plug.shell(['node-inspector']));
        options.nodeArgs = [args.debug + '=5858'];
    }

    return plug.nodemon(options)
        //.on('change', tasks)
        .on('restart', function() {
            log('restarted!');
        });
}<|endoftext|>