<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', '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 browser sync vs watch issues<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,
    }),
);

// 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>/**
 * Created by tomersela on 9/20/15.
 */
var gulp = require('gulp'),
    bower = require('gulp-bower'),
    clean = require('gulp-clean'),
    concat = require('gulp-concat'),
    sass = require('gulp-sass'),
    rename = require('gulp-rename'),
    minifyCss = require('gulp-minify-css'),
    sourcemaps = require('gulp-sourcemaps'),
    shrinkwrap = require('gulp-shrinkwrap'),
    uglify = require('gulp-uglify'),
    gutil = require('gulp-util');

var config = {
    libFolder: './lib',
    cssFolder: './dist/css',
    sassFolder: './src/scss',
    srcFolder: './src',
    distFolder: './dist'
};

// Bower task
gulp.task('bower', function() {
    return bower()
        .pipe(gulp.dest(config.libFolder));
});

// Clean stylesheets
gulp.task('clean:sass', function() {
    return gulp.src(config.cssFolder, {read: false})
        .pipe(clean());
});

// Compile sass to css and minify css stylesheets
gulp.task('sass', ['clean:sass'], function () {
    gulp.src(config.sassFolder + '/**/*.scss')
        .pipe(sass())
        .pipe(gulp.dest(config.cssFolder));

    // compress and copy css stylesheets
    gulp.src(config.cssFolder + '/stylesheets/css/**/*.css')
        .pipe(minifyCss({compatibility: 'ie8'}))
        .pipe(rename({suffix: '.min'}))
        .pipe(gulp.dest(config.build + '/stylesheets/css'));
});

// Clean JS
gulp.task('clean:js', function() {
    return gulp.src(config.distFolder + '/**/*.js', {read: false})
        .pipe(clean());
});

// Clean JS map files
gulp.task('clean:maps', function() {
    return gulp.src(config.distFolder + '/**/*.map', {read: false})
        .pipe(clean());
});

// Javascript, full version
gulp.task('jsFull', ['clean:js', 'clean:maps'], function () {
    gulp.src([config.srcFolder + '/*.js'])
        .pipe(concat('vidible-player-angular.js'))
        .pipe(gulp.dest(config.distFolder));
});

// Javascript, minified version
gulp.task('jsMin', ['clean:js', 'clean:maps'], function () {
    // compress and copy angular
    gulp.src([config.srcFolder + '/*.js'])
            .pipe(concat('vidible-player-angular.js'))
            .pipe(uglify().on('error', gutil.log))
            .pipe(rename({suffix: '.min'}))
        .pipe(gulp.dest(config.distFolder));
});

gulp.task('javascripts', ['jsFull', 'jsMin']);

// Shrinkwrap
gulp.task('shrinkwrap', function () {
    return gulp.src('package.json')
        .pipe(shrinkwrap())      // just like running `npm shrinkwrap`
        .pipe(gulp.dest('./'));  // writes newly created `npm-shrinkwrap.json` to the location of your choice
});

// Watch file changes and update
gulp.task('watch', function () {
    gulp.watch(config.srcFolder + '/**/*.js', ['js']);
    gulp.watch(config.srcFolder + '/**/*.scss', ['sass']);
    gulp.watch('./bower.json', ['bower']);
});

gulp.task('default', ['shrinkwrap', 'bower', 'sass', 'javascripts']);<commit_msg>Applying coding style on gulp file<commit_after>/**
 * Created by tomersela on 9/20/15.
 */
var gulp = require('gulp'),
    bower = require('gulp-bower'),
    clean = require('gulp-clean'),
    concat = require('gulp-concat'),
    sass = require('gulp-sass'),
    rename = require('gulp-rename'),
    minifyCss = require('gulp-minify-css'),
    sourcemaps = require('gulp-sourcemaps'),
    shrinkwrap = require('gulp-shrinkwrap'),
    uglify = require('gulp-uglify'),
    gutil = require('gulp-util');

var config = {
    libFolder: './lib',
    cssFolder: './dist/css',
    sassFolder: './src/scss',
    srcFolder: './src',
    distFolder: './dist'
};

// Bower task
gulp.task('bower', function() {
    return bower()
        .pipe(gulp.dest(config.libFolder));
});

// Clean stylesheets
gulp.task('clean:sass', function() {
    return gulp.src(config.cssFolder, {read: false})
        .pipe(clean());
});

// Compile sass to css and minify css stylesheets
gulp.task('sass', ['clean:sass'], function() {
    gulp.src(config.sassFolder + '/**/*.scss')
        .pipe(sass())
        .pipe(gulp.dest(config.cssFolder));

    // compress and copy css stylesheets
    gulp.src(config.cssFolder + '/stylesheets/css/**/*.css')
        .pipe(minifyCss({compatibility: 'ie8'}))
        .pipe(rename({suffix: '.min'}))
        .pipe(gulp.dest(config.build + '/stylesheets/css'));
});

// Clean JS
gulp.task('clean:js', function() {
    return gulp.src(config.distFolder + '/**/*.js', {read: false})
        .pipe(clean());
});

// Clean JS map files
gulp.task('clean:maps', function() {
    return gulp.src(config.distFolder + '/**/*.map', {read: false})
        .pipe(clean());
});

// Javascript, full version
gulp.task('jsFull', ['clean:js', 'clean:maps'], function() {
    gulp.src([config.srcFolder + '/*.js'])
        .pipe(concat('vidible-player-angular.js'))
        .pipe(gulp.dest(config.distFolder));
});

// Javascript, minified version
gulp.task('jsMin', ['clean:js', 'clean:maps'], function() {
    // compress and copy angular
    gulp.src([config.srcFolder + '/*.js'])
        .pipe(concat('vidible-player-angular.js'))
        .pipe(uglify().on('error', gutil.log))
        .pipe(rename({suffix: '.min'}))
        .pipe(gulp.dest(config.distFolder));
});

gulp.task('javascripts', ['jsFull', 'jsMin']);

// Shrinkwrap
gulp.task('shrinkwrap', function() {
    return gulp.src('package.json')
        .pipe(shrinkwrap())      // just like running `npm shrinkwrap`
        .pipe(gulp.dest('./'));  // writes newly created `npm-shrinkwrap.json` to the location of your choice
});

// Watch file changes and update
gulp.task('watch', function() {
    gulp.watch(config.srcFolder + '/**/*.js', ['js']);
    gulp.watch(config.srcFolder + '/**/*.scss', ['sass']);
    gulp.watch('./bower.json', ['bower']);
});

gulp.task('default', ['shrinkwrap', 'bower', 'sass', 'javascripts']);
<|endoftext|>


<commit_before>'use strict';

var metal = require('gulp-metal');

var options = {
	bundleCssFileName: 'ajax.css',
	bundleFileName: 'ajax.js',
	globalName: 'metal',
	mainBuildJsTasks: ['build:globals'],
	moduleName: 'metal-ajax',
	testBrowsers: ['Chrome', 'Firefox', 'Safari', 'IE10 - Win7', 'IE11 - Win7'],
	testSaucelabsBrowsers: {
		sl_chrome: {
			base: 'SauceLabs',
			browserName: 'chrome'
		},
		sl_chrome_57: {
			base: 'SauceLabs',
			browserName: 'chrome',
			version: '57'
		},
		sl_safari_8: {
			base: 'SauceLabs',
			browserName: 'safari',
			version: '8'
		},
		sl_safari_9: {
			base: 'SauceLabs',
			browserName: 'safari',
			version: '9'
		},
		sl_safari_10: {
			base: 'SauceLabs',
			browserName: 'safari',
			version: '10'
		},
		sl_firefox: {
			base: 'SauceLabs',
			browserName: 'firefox'
		},
		sl_firefox_53: {
			base: 'SauceLabs',
			browserName: 'firefox',
			version: '53'
		},
		sl_ie_10: {
			base: 'SauceLabs',
			browserName: 'internet explorer',
			platform: 'Windows 7',
			version: '10'
		},
		sl_ie_11: {
			base: 'SauceLabs',
			browserName: 'internet explorer',
			platform: 'Windows 8.1',
			version: '11'
		},
		sl_edge_20: {
			base: 'SauceLabs',
			browserName: 'microsoftedge',
			platform: 'Windows 10',
			version: '13'
		},
		sl_iphone: {
			base: 'SauceLabs',
			browserName: 'iphone',
			platform: 'OS X 10.10',
			version: '9.2'
		},
		sl_android_4: {
			base: 'SauceLabs',
			browserName: 'android',
			platform: 'Linux',
			version: '4.4'
		},
		sl_android_5: {
			base: 'SauceLabs',
			browserName: 'android',
			platform: 'Linux',
			version: '5.0'
		}
	}
};

metal.registerTasks(options);
<commit_msg>Remove Safari 8 from tests<commit_after>'use strict';

var metal = require('gulp-metal');

var options = {
	bundleCssFileName: 'ajax.css',
	bundleFileName: 'ajax.js',
	globalName: 'metal',
	mainBuildJsTasks: ['build:globals'],
	moduleName: 'metal-ajax',
	testBrowsers: ['Chrome', 'Firefox', 'Safari', 'IE10 - Win7', 'IE11 - Win7'],
	testSaucelabsBrowsers: {
		sl_chrome: {
			base: 'SauceLabs',
			browserName: 'chrome'
		},
		sl_chrome_57: {
			base: 'SauceLabs',
			browserName: 'chrome',
			version: '57'
		},
		sl_safari_9: {
			base: 'SauceLabs',
			browserName: 'safari',
			version: '9'
		},
		sl_safari_10: {
			base: 'SauceLabs',
			browserName: 'safari',
			version: '10'
		},
		sl_firefox: {
			base: 'SauceLabs',
			browserName: 'firefox'
		},
		sl_firefox_53: {
			base: 'SauceLabs',
			browserName: 'firefox',
			version: '53'
		},
		sl_ie_10: {
			base: 'SauceLabs',
			browserName: 'internet explorer',
			platform: 'Windows 7',
			version: '10'
		},
		sl_ie_11: {
			base: 'SauceLabs',
			browserName: 'internet explorer',
			platform: 'Windows 8.1',
			version: '11'
		},
		sl_edge_20: {
			base: 'SauceLabs',
			browserName: 'microsoftedge',
			platform: 'Windows 10',
			version: '13'
		},
		sl_iphone: {
			base: 'SauceLabs',
			browserName: 'iphone',
			platform: 'OS X 10.10',
			version: '9.2'
		},
		sl_android_4: {
			base: 'SauceLabs',
			browserName: 'android',
			platform: 'Linux',
			version: '4.4'
		},
		sl_android_5: {
			base: 'SauceLabs',
			browserName: 'android',
			platform: 'Linux',
			version: '5.0'
		}
	}
};

metal.registerTasks(options);
<|endoftext|>


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


<commit_before>'use strict';

/*!
 * V4Fire Client Core
 * https://github.com/V4Fire/Client
 *
 * Released under the MIT license
 * https://github.com/V4Fire/Client/blob/master/LICENSE
 */

const {env, argv} = process;
env.NODE_ENV = env.NODE_ENV || 'standalone';

require('@v4fire/core/gulpfile');
require('./build/other.gulp');
require('./build/static.gulp');

const
	gulp = require('gulp'),
	plumber = require('gulp-plumber'),
	cached = require('gulp-cached');

const
	runWebpack = 'node node_modules/parallel-webpack/bin/run.js',
	args = argv.slice(3).join(' ');

gulp.task('cleanClient', (cb) => {
	const del = require('del');
	del('./dist/packages').then(() => cb(), cb);
});

gulp.task('client', (cb) => {
	const run = require('gulp-run');
	run(`${runWebpack} -- ${args}`, {verbosity: 3})
		.exec()
		.on('finish', cb);
});

gulp.task('watchClient', () => {
	const run = require('gulp-run');
	run(`${runWebpack} --watch -- ${args}`, {verbosity: 3}).exec();
});

gulp.task('watch', ['watchClient']);
gulp.task('default', ['head', 'cleanClient', 'client']);
gulp.task('prod', ['setProd', 'default']);
<commit_msg>Import core/gulpfile<commit_after>'use strict';

/*!
 * V4Fire Client Core
 * https://github.com/V4Fire/Client
 *
 * Released under the MIT license
 * https://github.com/V4Fire/Client/blob/master/LICENSE
 */

const {env, argv} = process;
env.NODE_ENV = env.NODE_ENV || 'standalone';

const
	gulp = require('gulp'),
	plumber = require('gulp-plumber'),
	cached = require('gulp-cached');

require('@v4fire/core/gulpfile')(gulp);
require('./build/static.gulp');

const
	runWebpack = 'node node_modules/parallel-webpack/bin/run.js',
	args = argv.slice(3).join(' ');

gulp.task('cleanClient', (cb) => {
	const del = require('del');
	del('./dist/packages').then(() => cb(), cb);
});

gulp.task('client', (cb) => {
	const run = require('gulp-run');
	run(`${runWebpack} -- ${args}`, {verbosity: 3})
		.exec()
		.on('finish', cb);
});

gulp.task('watchClient', () => {
	const run = require('gulp-run');
	run(`${runWebpack} --watch -- ${args}`, {verbosity: 3}).exec();
});

gulp.task('watch', ['watchClient']);
gulp.task('default', ['head', 'cleanClient', 'client']);
gulp.task('prod', ['setProd', 'default']);
<|endoftext|>


<commit_before>const outputDir       = 'build';

//https://github.com/mafintosh/pump
const pump      = require('pump');

//https://github.com/gulpjs/gulp
const gulp      = require('gulp');

//https://github.com/terinjokes/gulp-uglify
const uglify    = require('gulp-uglify');

//https://github.com/scniro/gulp-clean-css
const cleanCSS  = require('gulp-clean-css');

//https://github.com/cynosureabu/gulp-min-ejs
const minifyejs = require('gulp-minify-ejs');

const tasks = {
    //压缩src/public/js目录下的js文件
    compressJS: callback => {
        const option = {
            mangle : {
                toplevel: true,
                keep_fnames: true,
                reserved: ['$']
            }
        };
        pump([
            gulp.src('src/public/js/**/*.js'),
            uglify(option),
            gulp.dest(outputDir + '/public/js/')
        ], callback);
    },

    //处理src/public/css目录下的css文件中的空行
    cleanCSS: callback => {
        pump([
            gulp.src('src/public/css/*.css'),
            cleanCSS({compatibility: 'ie8'}),
            gulp.dest(outputDir + '/public/css/')
        ], callback);
    },

    //复制src/public目录下的其他文件
    copyPublic: callback => {
        pump([
            gulp.src(['src/public/**', '!src/public/js/**/*.js', '!src/public/css/**/*.css']),
            gulp.dest(outputDir + '/public/')
        ], callback);
    },

    //处理src/private/views目录下的ejs模板中的空白行
    minifyejs: callback => {
        pump([
            gulp.src('src/private/views/**/*.ejs'),
            minifyejs(),
            gulp.dest(outputDir + '/private/views/')
        ], callback);
    },

    //复制src/private目录下的其他文件
    copyPrivate: callback => {
        pump([
            gulp.src(['src/private/**', '!src/private/views/**/*.ejs']),
            gulp.dest(outputDir + '/private/')
        ], callback);
    }
};

for(var key in tasks) {
    gulp.task(key, tasks[key]);
}

gulp.task('default', Object.keys(tasks));
<commit_msg>更新gulpfile.js<commit_after>const outputDir = 'build';

//https://github.com/mafintosh/pump
const pump      = require('pump');

//https://github.com/gulpjs/gulp
const gulp      = require('gulp');

//https://github.com/terinjokes/gulp-uglify
const uglify    = require('gulp-uglify');

//https://github.com/scniro/gulp-clean-css
const cleanCSS  = require('gulp-clean-css');

//https://github.com/cynosureabu/gulp-min-ejs
const minifyejs = require('gulp-minify-ejs');

const tasks = {
    //压缩src/public/js目录下的js文件
    compressJS: callback => {
        const option = {
            mangle : {
                toplevel: true,
                keep_fnames: true,
                reserved: ['$']
            }
        };
        pump([
            gulp.src('src/public/js/**/*.js'),
            uglify(option),
            gulp.dest(outputDir + '/public/js/')
        ], callback);
    },

    //处理src/public/css目录下的css文件中的空行
    cleanCSS: callback => {
        pump([
            gulp.src('src/public/css/*.css'),
            cleanCSS({compatibility: 'ie8'}),
            gulp.dest(outputDir + '/public/css/')
        ], callback);
    },

    //复制src/public目录下的其他文件
    copyPublic: callback => {
        pump([
            gulp.src(['src/public/**', '!src/public/js/**/*.js', '!src/public/css/**/*.css']),
            gulp.dest(outputDir + '/public/')
        ], callback);
    },

    //处理src/private/views目录下的ejs模板中的空白行
    minifyejs: callback => {
        pump([
            gulp.src('src/private/views/**/*.ejs'),
            minifyejs(),
            gulp.dest(outputDir + '/private/views/')
        ], callback);
    },

    //复制src/private目录下的其他文件
    copyPrivate: callback => {
        pump([
            gulp.src(['src/private/**', '!src/private/views/**/*.ejs']),
            gulp.dest(outputDir + '/private/')
        ], callback);
    }
};

for(var key in tasks) {
    gulp.task(key, tasks[key]);
}

gulp.task('default', Object.keys(tasks));
<|endoftext|>


<commit_before>var gulp = require('gulp');
var bg = require('gulp-bg');
var docs = require('./gulp/docs');

gulp.task('docs', docs({
  cwd: __dirname,
  src: './src/docs',
  dest: './dist/docs'
}));

gulp.task('watch-docs', function (cb) {
  gulp.watch('./src/docs/**', ['docs']);
});

gulp.task('default', []);
<commit_msg>Remove last bits of gulp-bg<commit_after>var gulp = require('gulp');
var docs = require('./gulp/docs');

gulp.task('docs', docs({
  cwd: __dirname,
  src: './src/docs',
  dest: './dist/docs'
}));

gulp.task('watch-docs', function (cb) {
  gulp.watch('./src/docs/**', ['docs']);
});

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


<commit_before>const babelify = require("babelify");
const browserify = require("browserify");
const buffer = require("vinyl-buffer");
const eslint = require("gulp-eslint");
const fs = require("fs");
const gulp = require("gulp");
const cucumber = require("gulp-cucumber");
const less = require("gulp-less");
const mocha = require("gulp-mocha");
const runSequence = require("run-sequence");
const source = require("vinyl-source-stream");
const ts = require("gulp-typescript");
const tslint = require("gulp-tslint");
const uglify = require("gulp-uglify");

gulp.task("browserify", () => {
    return browserify("src/site/scripts/main.js")
        .transform("babelify", { presets: ["es2015"] })
        .bundle()
        .pipe(source("main.js"))
        .pipe(buffer())
        .pipe(uglify())
        .pipe(gulp.dest("src/site/scripts/bundled"));
});

gulp.task("eslint", () => {
    return gulp
        .src("test/**/*.js")
        .pipe(eslint())
        .pipe(eslint.format())
        .pipe(eslint.failAfterError());
});

gulp.task("less", () => {
    return gulp.src("src/site/**/*.less")
        .pipe(less())
        .pipe(gulp.dest("src/site"));
});

gulp.task("lint", ["eslint", "tslint"], callback => callback());

gulp.task("test:unit", () => {
    return gulp.src("test/unit/**.js")
        .pipe(mocha({
            reporter: "spec"
        }));
});

// Feature testing
// Todo #71: Run these synchronously, and therefore as a part of the default tests
const featureTasks = (() => {
    function testFeature(feature) {
        return gulp.src(`test/integration/features/${feature}.feature`)
            .pipe(cucumber({
                "steps": `test/integration/steps/${feature}.js`,
                "support": `test/integration/support/${feature}.js`
            }));
    }

    const features = fs.readdirSync("test/integration/features")
        .map(fileName => fileName.replace(".feature", ""));

    features.forEach(feature => {
        gulp.task(
            `test:integration:${feature}`,
            () => testFeature(feature));
    });

    return features.map(feature => `test:integration:${feature}`);
})();

gulp.task("test", callback => {
    runSequence(["test:unit"], callback);
});

gulp.task("tsc", () => {
    const tsProject = ts.createProject("tsconfig.json");

    return tsProject
        .src()
        .pipe(ts(tsProject))
        .js.pipe(gulp.dest("src"));
});

gulp.task("tslint", () => {
    return gulp
        .src(["src/**/*.ts", "src/**/*.tsx", "!src/**/*.d.ts"])
        .pipe(tslint())
        .pipe(tslint.report("verbose"));
});

gulp.task("watch", () => {
    gulp.watch(["*.json", "src/**/*.ts","src/**/*.tsx"], ["tsc", "lint", "browserify"]);
    gulp.watch(["src/site/**/*.less"], ["less"]);
});

gulp.task("default", ["less", "tsc", "lint"], callback => {
    runSequence(["browserify", "test"], callback);
});

// Hack for hanging integration tests: https://github.com/gulpjs/gulp/issues/167
gulp.on("stop", () => {
    process.nextTick(() => process.exit(0));
});
<commit_msg>Added root .js scripts (gulpfile.js) to eslint<commit_after>"use strict";

const browserify = require("browserify");
const buffer = require("vinyl-buffer");
const eslint = require("gulp-eslint");
const fs = require("fs");
const gulp = require("gulp");
const cucumber = require("gulp-cucumber");
const less = require("gulp-less");
const mocha = require("gulp-mocha");
const runSequence = require("run-sequence");
const source = require("vinyl-source-stream");
const ts = require("gulp-typescript");
const tslint = require("gulp-tslint");
const uglify = require("gulp-uglify");

gulp.task("browserify", () => {
    return browserify("src/site/scripts/main.js")
        .transform("babelify", { presets: ["es2015"] })
        .bundle()
        .pipe(source("main.js"))
        .pipe(buffer())
        .pipe(uglify())
        .pipe(gulp.dest("src/site/scripts/bundled"));
});

gulp.task("eslint", () => {
    return gulp
        .src([
            "test/**/*.js",
            "./*.js"
        ])
        .pipe(eslint())
        .pipe(eslint.format())
        .pipe(eslint.failAfterError());
});

gulp.task("less", () => {
    return gulp.src("src/site/**/*.less")
        .pipe(less())
        .pipe(gulp.dest("src/site"));
});

gulp.task("lint", ["eslint", "tslint"], callback => callback());

gulp.task("test:unit", () => {
    return gulp.src("test/unit/**.js")
        .pipe(mocha({
            reporter: "spec"
        }));
});

// Feature testing
// Todo #71: Run these synchronously, and therefore as a part of the default tests
(() => {
    function testFeature(feature) {
        return gulp.src(`test/integration/features/${feature}.feature`)
            .pipe(cucumber({
                "steps": `test/integration/steps/${feature}.js`,
                "support": `test/integration/support/${feature}.js`
            }));
    }

    const features = fs.readdirSync("test/integration/features")
        .map(fileName => fileName.replace(".feature", ""));

    features.forEach(feature => {
        gulp.task(
            `test:integration:${feature}`,
            () => testFeature(feature));
    });

    return features.map(feature => `test:integration:${feature}`);
})();

gulp.task("test", callback => {
    runSequence(["test:unit"], callback);
});

gulp.task("tsc", () => {
    const tsProject = ts.createProject("tsconfig.json");

    return tsProject
        .src()
        .pipe(ts(tsProject))
        .js.pipe(gulp.dest("src"));
});

gulp.task("tslint", () => {
    return gulp
        .src(["src/**/*.ts", "src/**/*.tsx", "!src/**/*.d.ts"])
        .pipe(tslint())
        .pipe(tslint.report("verbose"));
});

gulp.task("watch", () => {
    gulp.watch(["*.json", "src/**/*.ts", "src/**/*.tsx"], ["tsc", "lint", "browserify"]);
    gulp.watch(["src/site/**/*.less"], ["less"]);
});

gulp.task("default", ["less", "tsc", "lint"], callback => {
    runSequence(["browserify", "test"], callback);
});

// Hack for hanging integration tests: https://github.com/gulpjs/gulp/issues/167
gulp.on("stop", () => {
    process.nextTick(() => process.exit(0));
});
<|endoftext|>


<commit_before>var gulp = require('gulp'),
    uglify = require('gulp-uglify'),
    eslint = require('gulp-eslint'),
    istanbul = require('gulp-istanbul'),
    rename = require('gulp-rename'),
    sourcemaps = require('gulp-sourcemaps'),
    mocha = require('gulp-mocha');

gulp.task('lint', function () {
    gulp.src('./multivents.js')
      .pipe(eslint())
      .pipe(eslint.format())
      .pipe(eslint.failAfterError());
});

gulp.task('pre-test', function () {
    gulp.src('./multivents.js')
    .pipe(istanbul())
    .pipe(istanbul.hookRequire());
});

gulp.task('test', [ 'pre-test' ], function () {
  gulp.src('./tests/*.js')
      .pipe(mocha({ reporter: 'progress' }))
      .pipe(istanbul.writeReports());
});

gulp.task('build', [], function () {
    gulp.src('./multivents.js')
      .pipe(rename('multivents.min.js'))
      .pipe(sourcemaps.init())
        .pipe(uglify())
      .pipe(sourcemaps.write('./', {includeContent:false}))
      .pipe(gulp.dest('./'));
  });

gulp.task('default', [ 'hint', 'test', 'build' ]);
<commit_msg>Added html-output of test-coverage report<commit_after>var gulp = require('gulp'),
    uglify = require('gulp-uglify'),
    eslint = require('gulp-eslint'),
    istanbul = require('gulp-istanbul'),
    rename = require('gulp-rename'),
    sourcemaps = require('gulp-sourcemaps'),
    mocha = require('gulp-mocha');

gulp.task('lint', function () {
    gulp.src('./multivents.js')
      .pipe(eslint())
      .pipe(eslint.format())
      .pipe(eslint.failAfterError());
});

gulp.task('pre-test', function () {
    gulp.src('./multivents.js')
    .pipe(istanbul())
    .pipe(istanbul.hookRequire());
});

gulp.task('test', [ 'pre-test' ], function () {
    gulp.src('./tests/*.js')
      .pipe(mocha({ reporter: 'progress' }))
      .pipe(istanbul.writeReports({ reporters: [ 'text', 'html' ] }));
});

gulp.task('build', [], function () {
    gulp.src('./multivents.js')
      .pipe(rename('multivents.min.js'))
      .pipe(sourcemaps.init())
        .pipe(uglify())
      .pipe(sourcemaps.write('./', {includeContent:false}))
      .pipe(gulp.dest('./'));
  });

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


<commit_before>var gulp = require('gulp');
var less = require('gulp-less');
var cleanCSS = require('gulp-clean-css');
var rename = require("gulp-rename");
var replace = require('gulp-replace');
var uglify = require('gulp-uglify');
var htmlmin = require('gulp-htmlmin');
var vulcanize = require('gulp-vulcanize');

// Minify HTML
gulp.task('minify-html', function() {
  return gulp.src('./index.html')
    .pipe(replace('src/components.html', 'critical.html'))
    .pipe(htmlmin({
      collapseWhitespace: true,
      removeComments: true,
      minifyCSS: true,
      minifyJS: true
    }))
    .pipe(gulp.dest('dist'));
});

// Compile LESS files from /less into /css
gulp.task('less', function() {
    return gulp.src('less/clean-blog.less')
      .pipe(less())
      .pipe(rename({ suffix: '.min' }))
      .pipe(gulp.dest('css'));
});

// Minify compiled CSS
gulp.task('minify-css', ['less'], function() {
    return gulp.src('css/clean-blog.css')
      .pipe(cleanCSS({ compatibility: 'ie8' }))
      .pipe(rename({ suffix: '.min' }))
      .pipe(gulp.dest('css'));
});

// Minify JS
gulp.task('minify-js', function() {
    return gulp.src('js/clean-blog.js')
      .pipe(uglify())
      .pipe(rename({ suffix: '.min' }))
      .pipe(gulp.dest('js'));
});

// Vulcanize Web Components
gulp.task('vulcanize', function () {
    gulp.src('src/components.html')
      .pipe(vulcanize({
        stripComments: true,
        inlineScripts: true,
        inlineCss: true
      }))
      .pipe(htmlmin({
        collapseWhitespace: true,
        removeComments: true,
        minifyCSS: true,
        minifyJS: true
      }))
      .pipe(replace('../bower_components/font-awesome/fonts/', 'fonts/'))
      .pipe(rename('critical.html'))
      .pipe(gulp.dest('dist'));
});

// Copy files
gulp.task('copy', function() {
    gulp.src(['posts/**'])
      .pipe(gulp.dest('dist/posts'))
    gulp.src(['img/**'])
      .pipe(gulp.dest('dist/img'))
    gulp.src(['node_modules/font-awesome/fonts/**'])
      .pipe(gulp.dest('dist/fonts'))
    gulp.src(['bower_components/webcomponentsjs/webcomponents-lite.min.js'])
      .pipe(gulp.dest('dist/js'));
})

// Run everything
gulp.task('default', ['less', 'minify-css', 'minify-html', 'minify-js', 'vulcanize', 'copy']);
<commit_msg>fonts under bower<commit_after>var gulp = require('gulp');
var less = require('gulp-less');
var cleanCSS = require('gulp-clean-css');
var rename = require("gulp-rename");
var replace = require('gulp-replace');
var uglify = require('gulp-uglify');
var htmlmin = require('gulp-htmlmin');
var vulcanize = require('gulp-vulcanize');

// Minify HTML
gulp.task('minify-html', function() {
  return gulp.src('./index.html')
    .pipe(replace('src/components.html', 'critical.html'))
    .pipe(htmlmin({
      collapseWhitespace: true,
      removeComments: true,
      minifyCSS: true,
      minifyJS: true
    }))
    .pipe(gulp.dest('dist'));
});

// Compile LESS files from /less into /css
gulp.task('less', function() {
    return gulp.src('less/clean-blog.less')
      .pipe(less())
      .pipe(rename({ suffix: '.min' }))
      .pipe(gulp.dest('css'));
});

// Minify compiled CSS
gulp.task('minify-css', ['less'], function() {
    return gulp.src('css/clean-blog.css')
      .pipe(cleanCSS({ compatibility: 'ie8' }))
      .pipe(rename({ suffix: '.min' }))
      .pipe(gulp.dest('css'));
});

// Minify JS
gulp.task('minify-js', function() {
    return gulp.src('js/clean-blog.js')
      .pipe(uglify())
      .pipe(rename({ suffix: '.min' }))
      .pipe(gulp.dest('js'));
});

// Vulcanize Web Components
gulp.task('vulcanize', function () {
    gulp.src('src/components.html')
      .pipe(vulcanize({
        stripComments: true,
        inlineScripts: true,
        inlineCss: true
      }))
      .pipe(htmlmin({
        collapseWhitespace: true,
        removeComments: true,
        minifyCSS: true,
        minifyJS: true
      }))
      .pipe(replace('../bower_components/font-awesome/fonts/', 'fonts/'))
      .pipe(rename('critical.html'))
      .pipe(gulp.dest('dist'));
});

// Copy files
gulp.task('copy', function() {
    gulp.src(['posts/**'])
      .pipe(gulp.dest('dist/posts'))
    gulp.src(['img/**'])
      .pipe(gulp.dest('dist/img'))
    gulp.src(['bower_components/font-awesome/fonts/**'])
      .pipe(gulp.dest('dist/fonts'))
    gulp.src(['bower_components/webcomponentsjs/webcomponents-lite.min.js'])
      .pipe(gulp.dest('dist/js'));
})

// Run everything
gulp.task('default', ['less', 'minify-css', 'minify-html', 'minify-js', 'vulcanize', 'copy']);
<|endoftext|>


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

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

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

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

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


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

const electron = require('electron-connect').server.create();
const gulp = require('gulp');
const cleancss = require('gulp-clean-css');
const htmlmin = require('gulp-htmlmin');
const plumber = require('gulp-plumber');
const stylus = require('gulp-stylus');
const prettydiff = require('gulp-prettydiff');
const typescript = require('gulp-typescript');
const del = require('del');

const project = typescript.createProject('tsconfig.json', {
    typescript: require('typescript')
});

gulp.task('html', () => {
    gulp.src('src/**/*.html')
        .pipe(plumber())
        .pipe(htmlmin({
            collapseWhitespace: true
        }))
        .pipe(gulp.dest('./build/'));
});

gulp.task('css', () => {
    gulp.src('src/**/*.styl')
        .pipe(plumber())
        .pipe(stylus())
        .pipe(cleancss())
        .pipe(gulp.dest('./build/'));
});

gulp.task('js:main', () => {

    gulp.src('src/main/**/*.ts')
        .pipe(plumber())
        .pipe(project())
        .pipe(prettydiff({
            lang: 'js',
            mode: 'minify',
        }))
        .pipe(gulp.dest('./build/main'));
});

gulp.task('js:renderer', () => {

    gulp.src('src/renderer/**/*.ts')
        .pipe(plumber())
        .pipe(project())
        .pipe(prettydiff({
            lang: 'js',
            mode: 'minify',
        }))
        .pipe(gulp.dest('./build/renderer'));
});

gulp.task('serve', () => {
    electron.start();
    gulp.watch('build/main/**/**.js', ['restart:electron']);
    gulp.watch(['build/**/**.html', 'build/**/**.css', 'build/renderer/**/**.js'], ['reload:renderer'])
})

gulp.task('watch', () => {
    gulp.watch('src/**/*.html', ['html']);
    gulp.watch('src/**/*.styl', ['css']);
    gulp.watch('src/main/**/*.ts', ['js:main']);
    gulp.watch('src/renderer/**/*.ts', ['js:renderer']);
});

gulp.task('restart:electron', (done) => {
    electron.restart();
    done();
});

gulp.task('reload:renderer', (done) => {
    electron.reload();
    done();
});

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

gulp.task('clean', del.bind(null,['build/main','build/renderer']));<commit_msg>Add build task<commit_after>//    Copyright 2016 underdolphin(masato sueda)
//
//    Licensed under the Apache License, Version 2.0 (the "License");
//    you may not use this file except in compliance with the License.
//    You may obtain a copy of the License at
//
//        http://www.apache.org/licenses/LICENSE-2.0
//
//    Unless required by applicable law or agreed to in writing, software
//    distributed under the License is distributed on an "AS IS" BASIS,
//    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//    See the License for the specific language governing permissions and
//    limitations under the License.

const electron = require('electron-connect').server.create();
const gulp = require('gulp');
const cleancss = require('gulp-clean-css');
const htmlmin = require('gulp-htmlmin');
const plumber = require('gulp-plumber');
const stylus = require('gulp-stylus');
const prettydiff = require('gulp-prettydiff');
const typescript = require('gulp-typescript');
const del = require('del');

const mainProject = typescript.createProject('tsconfig.json', {
    typescript: require('typescript')
});

const rendererProject = typescript.createProject('tsconfig.json', {
    typescript: require('typescript')
});

gulp.task('html', () => {
    gulp.src('src/**/*.html')
        .pipe(plumber())
        .pipe(htmlmin({
            collapseWhitespace: true
        }))
        .pipe(gulp.dest('./build/'));
});

gulp.task('css', () => {
    gulp.src('src/**/*.styl')
        .pipe(plumber())
        .pipe(stylus())
        .pipe(cleancss())
        .pipe(gulp.dest('./build/'));
});

gulp.task('js:main', () => {

    gulp.src('src/main/**/*.ts')
        .pipe(plumber())
        .pipe(mainProject())
        .pipe(prettydiff({
            lang: 'js',
            mode: 'minify',
        }))
        .pipe(gulp.dest('./build/main'));
});

gulp.task('js:renderer', () => {

    gulp.src('src/renderer/**/*.ts')
        .pipe(plumber())
        .pipe(rendererProject())
        .pipe(prettydiff({
            lang: 'js',
            mode: 'minify',
        }))
        .pipe(gulp.dest('./build/renderer'));
});

gulp.task('serve', () => {
    electron.start();
    gulp.watch('build/main/**/**.js', ['restart:electron']);
    gulp.watch(['build/**/**.html', 'build/**/**.css', 'build/renderer/**/**.js'], ['reload:renderer'])
})

gulp.task('watch', () => {
    gulp.watch('src/**/*.html', ['html']);
    gulp.watch('src/**/*.styl', ['css']);
    gulp.watch('src/main/**/*.ts', ['js:main']);
    gulp.watch('src/renderer/**/*.ts', ['js:renderer']);
});

gulp.task('restart:electron', (done) => {
    electron.restart();
    done();
});

gulp.task('reload:renderer', (done) => {
    electron.reload();
    done();
});

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

gulp.task('clean', del.bind(null,['build/main','build/renderer']));

gulp.task('build',['html','css','js:main','js:renderer']);<|endoftext|>