gulp.task('browserify', function() {
  return browserify(sourceFile)
    .bundle({debug: true})
    .pipe(source(destFile))
    .pipe(gulp.dest(destFolder));
});
Example #2
0
var Console = module.exports = function(config, cb) {

    config = config || {};

    // Ensure logs dir.
    var logdir = false;
    try {
        fs.readdirSync(process.cwd() + '/logs');
        logdir = true;
    }
    catch(e) {
        try {
            fs.mkdirSync(process.cwd() + '/logs/', parseInt('755', 8));
            logdir = true;
        }
        catch(e) {
        }
    }

    var logger = logdir ? new (winston.Logger)({
        transports: [
            new (winston.transports.File)({
                filename: process.cwd() + '/logs/ql.io.log',
                maxsize: 1024000 * 5
            })
        ]
    }) : new (winston.Logger)();

    logger.setLevels(config['log levels'] || winston.config.cli.levels);
    config.logger = config.logger || logger;
    var engine = new Engine(config);

    if(config.tables) {
        logger.info('Loading tables from ' + config.tables);
    }
    if(config.routes) {
        logger.info('Loading routes from ' + config.routes);
    }
    if(config.config) {
        logger.info('Loading config from ' + config.config);
    }

    var app = this.app = express.createServer();

    app.enable('case sensitive routes'); // Default routes are not case sensitive

    // Add parser for xml
    connect.bodyParser.parse['application/xml'] = function(req, options, next) {
        var buf = '';
        req.setEncoding('utf8');
        req.on('data', function (chunk) {
            buf += chunk
        });
        req.on('end', function () {
            try {
                req.body = expat.toJson(buf, {coerce: true, object: true});
                next();
            }
            catch(err) {
                next(err);
            }
        });
    };

    var bodyParser = connect.bodyParser();
    app.use(bodyParser); // parses the body for application/x-www-form-urlencoded and application/json
    var respHeaders = require(__dirname + '/lib/middleware/respheaders');
    app.use(respHeaders());
    if(config['enable console']) {
        // If you want unminified JS and CSS, jus add property debug: true to js and css vars below.
        var qlAssets = {
            'js': {
                'stale': true, // If set to false, this adds a watch file listener - which messes up shutdown via cluster.
                'route': /\/scripts\/all.js/,
                'path': __dirname + '/public/scripts/',
                'dataType': 'javascript',
                'files': [
                    'splitter.js',
                    'codemirror.js',
                    'qlio-editor.js',
                    'jquery.treeview.js',
                    'jsonview.js',
                    'mustache.js',
                    'har-viewer.js',
                    'console.js'
                ]
            },
            'css': {
                'stale': true, // If set to false, this adds a watch file listener - which messes up shutdown via cluster.
                'route': /\/css\/all.css/,
                'path': __dirname + '/public/css/',
                'dataType': 'css',
                'files': [
                    'console.css',
                    'codemirror.css',
                    'qlio-editor.css',
                    'treeview.css',
                    'har-viewer.css',
                    'jquery-ui.css',
                    'routestables.css'
                ],
                'preManipulate': {
                    // Regexp to match user-agents including MSIE.
                    'MSIE': [
                        assetHandler.yuiCssOptimize,
                        assetHandler.fixVendorPrefixes,
                        assetHandler.fixGradients,
                        assetHandler.stripDataUrlsPrefix
                    ],
                    // Matches all (regex start line)
                    '^': [
                        assetHandler.yuiCssOptimize,
                        assetHandler.fixVendorPrefixes,
                        assetHandler.fixGradients
                    ]
                }
            }
        };
        var qlAssetLoader = assetManager(qlAssets);
        app.use(qlAssetLoader);

        app.set('views', __dirname + '/public/views');
        app.use(express.static(__dirname + '/public'));
        app.set('view engine', 'html');
        app.register('.html', require('ejs'));

        // The require below has paths prepended so that they can be loaded relative to this
        // (console) module and not its dependents. If not, Node would look for those modules
        // in the app's node_modules, which introduces a dependency from app to these modules.
        app.use(browserify(
            {
                mount : '/scripts/compiler.js',
                require : [ 'ql.io-compiler',
                        'headers',
                        'mustache',
                        'events'],
                filter : require('uglify-js')
            }));
        app.get('/console', function(req, res) {
            res.render(__dirname + '/public/views/console/index.ejs', {
                title: 'ql.io',
                layout: 'console-layout',
                script: req.param('s') || '-- Type ql script here - all keywords must be in lower case'
            });
        });

        // Add the home page to the console app
        app.get('/', function(req, res) {
            res.redirect('/console');
        });
    }

    // register routes
    var routes = engine.routes.verbMap;
    _.each(routes, function(verbRoutes, uri) {
        _.each(verbRoutes, function(verbRouteVariants, verb) {
            engine.emit(Engine.Events.EVENT, {}, new Date() + ' Adding route ' + uri + ' for ' + verb);
            app[verb](uri, function(req, res) {
                var holder = {
                    params: {},
                    headers: {},
                    routeParams: {},
                    connection: {
                        remoteAddress: req.connection.remoteAddress
                    }
                };

                // get all query params
                collectHttpQueryParams(req, holder, false);

                // find a route (i.e. associated cooked script)
                var route = _(verbRouteVariants).chain()
                    .filter(function (verbRouteVariant) {
                        return _.isEqual(_.intersection(_.keys(holder.params), _.keys(verbRouteVariant.query)),
                            _.keys(verbRouteVariant.query))
                    })
                    .reduce(function (match, route) {
                        return match == null ?
                            route : _.keys(route.query).length > _.keys(match.query).length ? route : match;
                    }, null)
                    .value();

                if (!route) {
                    res.writeHead(400, 'Bad input', {
                        'content-type' : 'application/json'
                    });
                    res.write(JSON.stringify({'err' : 'No matching route'}));
                    res.end();
                    return;
                }

                // collect the path params
                var keys = _.keys(req.params);
                _.each(keys, function(key) {
                    holder.routeParams[key] = req.params[key];
                });

                _.each(route.query, function(queryParam, paramName) {
                    holder.routeParams[queryParam] = holder.params[paramName].toString();
                });

                // collect headers
                collectHttpHeaders(req, holder);
                holder.connection = {
                    remoteAddress: req.connection.remoteAddress
                }

                var execState = [];
                engine.execute(route.script,
                    {
                        request: holder,
                        route: uri,
                        context: req.body || {}
                    },
                    function(emitter) {
                        setupExecStateEmitter(emitter, execState, req.param('events'));
                        setupCounters(emitter);
                        emitter.on('end', function(err, results) {
                            return handleResponseCB(req, res, execState, err, results);
                        });
                    }
                );
            });
        });
    });

    // HTTP indirection for 'show tables' command
    app.get('/tables', function(req,res){
        var holder = {
            headers: {}
        };

        var isJson = ((req.headers || {}).accept || '').search('json') > 0 ||
            (req.param('format') || '').trim().toLowerCase() === 'json';

        function routePage(res, execState, results){
            res.header['Link'] = headers.format('Link', {
                href : 'data:application/json,' + encodeURIComponent(JSON.stringify(execState)),
                rel : ['execstate']
            });
            res.render(__dirname + '/public/views/routes-tables/tables.ejs', {
                title: 'ql.io',
                layout: __dirname + '/public/views/routes-table-layout',
                tables: results
            });
        }

        var execState = [];
        engine.execute('show tables',
            {
                request: holder
            },
            function(emitter) {
                setupExecStateEmitter(emitter, execState, req.param('events'));
                setupCounters(emitter);
                emitter.on('end', function(err, results) {
                    return isJson || err ?
                        handleResponseCB(req, res, execState, err, results) :
                        routePage(res,execState,results.body);
                });
            }
        );
    });

    // HTTP indirection for 'describe <table>' command  and it returns json (and not html)
    app.get('/table', function(req,res){
        var holder = {
            headers: {}
        };

        var isJson = ((req.headers || {}).accept || '').search('json') > 0 ||
            (req.param('format') || '').trim().toLowerCase() === 'json';

        function routePage(res, execState, result){
            res.header['Link'] = headers.format('Link', {
                href : 'data:application/json,' + encodeURIComponent(JSON.stringify(execState)),
                rel : ['execstate']
            });
            res.render(__dirname + '/public/views/routes-tables/tableInfo.ejs', {
                title: 'ql.io',
                layout: __dirname + '/public/views/routes-table-layout',
                tableInfo: result,
                routes:
                    _(result.routes).chain()
                        .map(function(route){
                            var parse = new MutableURI(route);
                            return {
                                method: parse.getParam('method'),
                                path: parse.getParam('path'),
                                about: route
                            };
                        })
                        .value()
            });
        }

        var name = req.param('name');

        if (!name) {
            res.writeHead(400, 'Bad input', {
                'content-type' : 'application/json'
            });
            res.write(
                JSON.stringify({'err' : 'Missing table name: Usage /table?name=some-tablename'}
                ));
            res.end();
            return;
        }

        var execState = [];
        engine.execute('describe' + decodeURIComponent(name),
            {
                request: holder
            },
            function(emitter) {
                setupExecStateEmitter(emitter, execState, req.param('events'));
                setupCounters(emitter);
                emitter.on('end', function(err, result) {
                    return isJson || err ?
                        handleResponseCB(req, res, execState, err, result):
                        routePage(res,execState,result.body);
                });
            }
        );
    });

    // HTTP indirection for 'show routes' command
    app.get('/routes', function(req,res){
        var holder = {
            params: {},
            headers: {}
        };

        var isJson = ((req.headers || {}).accept || '').search('json') > 0 ||
            (req.param('format') || '').trim().toLowerCase() === 'json';

        function routePage(res, execState, results){
            res.header['Link'] = headers.format('Link', {
                href : 'data:application/json,' + encodeURIComponent(JSON.stringify(execState)),
                rel : ['execstate']
            });
            res.render(__dirname + '/public/views/routes-tables/routes.ejs', {
                title: 'ql.io',
                layout: __dirname + '/public/views/routes-table-layout',
                routes: results
            });
        }

        var execState = [];
        engine.execute('show routes',
            {
                request: holder
            },
            function(emitter) {
                setupExecStateEmitter(emitter, execState, req.param('events'));
                setupCounters(emitter);
                emitter.on('end', function(err, results) {
                    return isJson || err ?
                        handleResponseCB(req, res, execState, err, results) :
                        routePage(res,execState,results.body);
                });
            }
        );
    });

    // HTTP indirection for 'describe route "<route>" using method <http-verb>' command
    app.get('/route', function(req,res){
        var holder = {
            params: {},
            headers: {}
        };
        var path = req.param('path');
        var method = req.param('method');

        if (!path || !method) {
            res.writeHead(400, 'Bad input', {
                'content-type' : 'application/json'
            });
            res.write(
                JSON.stringify({'err' : 'Missing path name or method: Usage /route?path=some-path&method=http-method'}
                ));
            res.end();
            return;
        }

        var isJson = ((req.headers || {}).accept || '').search('json') > 0 ||
            (req.param('format') || '').trim().toLowerCase() === 'json';

        function routePage(res, execState, result){
            res.header['Link'] = headers.format('Link', {
                href : 'data:application/json,' + encodeURIComponent(JSON.stringify(execState)),
                rel : ['execstate']
            });
            res.render(__dirname + '/public/views/routes-tables/routeInfo.ejs', {
                title: 'ql.io',
                layout: __dirname + '/public/views/routes-table-layout',
                routeInfo: result,
                related:
                    _(result.related).chain()
                    .map(function(route){
                        var parse = new MutableURI(route);
                        return {
                            method: parse.getParam('method'),
                            path: parse.getParam('path'),
                            about: route
                        };
                    })
                    .value(),
                tables:
                    _(result.tables).chain()
                    .map(function(table){
                        var parse = new MutableURI(table);
                        return {
                            name: parse.getParam('name'),
                            about: table
                        };
                    })
                    .value()
            });
        }

        var execState = [];
        engine.execute('describe route "' + decodeURIComponent(path) + '" using method ' + method,
            {
                request: holder
            },
            function(emitter) {
                setupExecStateEmitter(emitter, execState, req.param('events'));
                setupCounters(emitter);
                emitter.on('end', function(err, result) {
                    return isJson || err ?
                        handleResponseCB(req, res, execState, err, result) :
                        routePage(res,execState,result.body);
                });
            }
        );
    });

    /*
     * '/q' is disabled only if the console is created with config, 'enable q' : false.
     */
    var enableQ = config['enable q'] === undefined ? true : config['enable q'];

    if(enableQ) {
        app.get('/q', function(req, res) {
            var holder = {
                params: {},
                headers: {} ,
                connection: {
                    remoteAddress: req.connection.remoteAddress
                }
            };
            var query = req.param('s');
            if (!query) {
                res.writeHead(400, 'Bad input', {
                    'content-type' : 'application/json'
                });
                res.write(JSON.stringify({'err' : 'Missing query'}));
                res.end();
                return;
            }
            query = sanitize(query).str;
            collectHttpQueryParams(req, holder, true);
            collectHttpHeaders(req, holder);
            var execState = [];
            engine.execute(query,
                {
                    request: holder
                }, function(emitter) {
                    setupExecStateEmitter(emitter, execState, req.param('events'));
                    setupCounters(emitter);
                    emitter.on('end', function(err, results) {
                        return handleResponseCB(req, res, execState, err, results);
                    })
                })
            }
        );
    }

    // 404 Handling
    app.use(function(req, res, next) {
        var msg = 'Cannot GET ' + sanitize(req.url).xss();
        var accept = (req.headers || {}).accept || '';
        if (accept.search('json') > 0) {
            res.writeHead(404, {
                'content-type' : 'application/json'
            });
            res.write(JSON.stringify({ error: msg }));
            res.end();
            return;
        }
        res.writeHead(404, {
            'content-type' : 'text/plain'
        });
        res.write(msg);
        res.end();
    });

    // Error-handling middleware
    app.use(function(err, req, res, next){
        // TODO call next() if recoverable, else next(err).
        var status = err.status || 500;
        var msg =  "Server Error - " + sanitize(err.msg || err).xss();
        var accept = (req.headers || {}).accept || '';
        if (accept.search('json') > 0) {
            res.writeHead(status, {
                'content-type' : 'application/json'
            });
            res.write(JSON.stringify({ error: msg }));
            res.end();
            return;
        }
        res.writeHead(status, {
            'content-type' : 'text/plain'
        });
        res.write(msg);
        res.end();
    });

    // Also listen to WebSocket requests
    var server = new WebSocketServer({
        httpServer: app,
        autoAcceptConnections: false
    });
    server.on('request', function(request) {
        var connection = request.accept('ql.io-console', request.origin);
        var events = [];
        connection.on('message', function(message) {
            var event = JSON.parse(message.utf8Data);
            if(event.type === 'events') {
                var arr = event.data;
                try {
                    events = JSON.parse(arr);
                }
                catch(e) {
                    events = [];
                    _.each(Engine.Events, function(event) {
                        events.push(event);
                    })
                }
                connection.sendUTF(JSON.stringify({
                    type: 'events',
                    data: '{}'
                }));
            }
            else if (event.type === 'script') {
                var _collect = function(packet) {
                    // Writes events to the client
                    connection.sendUTF(JSON.stringify({
                        type: packet.type,
                        data: packet
                    }))
                }
                var script = event.data;
                engine.execute(script, {
                    request: {
                        headers: {},
                        params: {},
                        connection: {
                            remoteAddress: connection.remoteAddress
                        }
                    }
                }, function(emitter) {
                    _.each(events, function(event) {
                        emitter.on(event, _collect);
                    });
                    setupCounters(emitter);
                    emitter.on('end', function(err, results) {
                        if(err) {
                            var packet = {
                                headers: {
                                    'content-type': 'application/json'
                                },
                                body: err.stack || err
                            };
                            connection.sendUTF(JSON.stringify({
                                type: Engine.Events.SCRIPT_RESULT,
                                data: packet
                            }));
                        }
                        else {
                            connection.sendUTF(JSON.stringify({
                                type: Engine.Events.SCRIPT_RESULT,
                                data: results
                            }));
                        }
                    })
                })
            }
        });
        connection.on('close', function() {
            connection.close();
        });
    });

    function collectHttpQueryParams(req, holder, ignoreS) {
        // Collect req params (with sanitization)
        _.each(req.query, function(v, k) {
            if (ignoreS && k == 's') {
                return;
            }
            if (_.isArray(v)) {
                holder.params[k] = [];
                _.each(v, function(val) {
                    holder.params[k].push(sanitize(val).str);
                });
            }
            else {
                holder.params[k] = sanitize(v).str;
            }
        });
    }

    function collectHttpHeaders(req, holder) {
        // Collect req headers (with sanitization)
        _.each(req.headers, function(v, k) {
            if (skipHeaders.indexOf(k) === -1) {
                if (_.isArray(v)) {
                    holder.headers[k] = [];
                    _.each(v, function(val) {
                        holder.headers[k].push(sanitize(val).str);
                    });
                }
                else {
                    holder.headers[k] = sanitize(v).str;
                }
            }
        });
    }

    function setupExecStateEmitter(emitter, execState, eventParam) {
        var obj, events;
        try {
            obj = JSON.parse(eventParam);
            obj = obj.data;
            events = JSON.parse(obj);
        }
        catch(e) {
            events = [];
        }

        _.each(events, function(event) {
            emitter.on(event, function(packet) {
                execState.push(packet);
            });
        });
    }

    // Send to master
    function setupCounters(emitter) {
        if(process.send) {
            emitter.on(Engine.Events.SCRIPT_ACK, function(packet) {
                process.send({event:  Engine.Events.SCRIPT_ACK, pid: process.pid});
            })
            emitter.on(Engine.Events.STATEMENT_REQUEST, function(packet) {
                process.send({event:  Engine.Events.STATEMENT_REQUEST, pid: process.pid});
            })
            emitter.on(Engine.Events.STATEMENT_RESPONSE, function(packet) {
                process.send({event:  Engine.Events.STATEMENT_RESPONSE, pid: process.pid});
            })
            emitter.on(Engine.Events.SCRIPT_DONE, function(packet) {
                process.send({event:  Engine.Events.SCRIPT_DONE, pid: process.pid});
            })
        }
    }

    function handleResponseCB(req, res, execState, err, results) {
        var cb = req.param('callback');
        if (err) {
            var status = err.status || 400;
            res.writeHead(status, {
                'content-type' : 'application/json'
            });
            if (cb) {
                res.write(cb + '(');
            }
            res.write(JSON.stringify(err));
            if (cb) {
                res.write(cb + ')');
            }
            res.end();
        }
        else {
            //
            // Hack: This is a hack to fix expressjs. The way expressjs is written forbids calling
            // writeHead. We need to look more closely into this.
            //
            res._header = undefined;
            var contentType = results.headers['content-type'];
            var h = {
                'Connection': 'keep-alive',
                'Transfer-Encoding' : 'chunked',
                'content-type' : cb ? 'application/javascript' : contentType,
                'Request-Id' : results.headers['request-id']
            };
            if(execState.length > 0) {
                h['Link'] = headers.format('Link', {
                    href : 'data:application/json,' + encodeURIComponent(JSON.stringify(execState)),
                    rel : ['execstate']
                });
            }
            res.writeHead(200, h);
            if (cb) {
                res.write(cb + '(');
            }
            if (contentType === 'application/json') {
                res.write(JSON.stringify(results.body));
            }
            else {
                res.write(results.body);
            }
            if (cb) {
                res.write(')');
            }
            res.end();
        }
    }

    // The caller gets the app and the engine/event emitter
    if(cb) {
        cb(app, engine);
    }
};
Example #3
0
var derequire = require('derequire');
var browserify = require('browserify');
var shim = require('browserify-shim');

var fs = require('fs');
var UglifyJS = require('uglify-js');
var pack = require('./package.json');

var inputFile = './index.js';
var outputFile = './dist/immstruct.js';
var outputMinifiedFile = './dist/immstruct.min.js';

var header = generateHeader();

var b = browserify({
  standalone: 'immstruct'
});
b.add(inputFile);
b.exclude('immutable');
b.transform(shim);
b.bundle(function(err, buf){
  var code = buf.toString();
  code = code.replace(/require\(('|")immutable('|")\)/ig, '(typeof window !== "undefined" ? window.Immutable : typeof global !== "undefined" ? global.Immutable : null)');
  code = header + derequire(code);
  fs.writeFileSync(outputFile, code);

  var minfied = UglifyJS.minify(outputFile);
  fs.writeFileSync(outputMinifiedFile, header + minfied.code);
});

function generateHeader() {
Example #4
0
gulp.task("build", function() {
  return browserify("./src")
    .bundle()
    .pipe(source("web-audio-test-api.js"))
    .pipe(gulp.dest("build"));
});
Example #5
0
var gulp = require('gulp');
var source = require('vinyl-source-stream');
var buffer = require('vinyl-buffer');
var gutil = require('gulp-util');
var sourcemaps = require('gulp-sourcemaps');
var assign = require('lodash.assign');
var sass = require('gulp-sass');


// add custom browserify options here
var customOpts = {
  entries: ['./javascripts/main.js'],
  debug: true
};
var opts = assign({}, watchify.args, customOpts);
var b = watchify(browserify(opts));

gulp.task('bundle', bundle); // changed from the sample gulpfile. Was 'default'

gulp.task('default', ['bundle', 'lint', 'sassify', 'watch']); //add test?

gulp.task('lint', function() {
  return gulp.src('./javascripts/**/*.js')
    .pipe(jshint())
    .pipe(jshint.reporter('jshint-stylish'));
});

// stretch goal: Make Jasmine and Browserify work together
// gulp.task('test', function() {
//   gulp.src('spec/RobotSpec.js')
//   // gulp-jasmine works on filepaths so you can't have any plugins before it
Example #6
0
if (process.env.ADAPTERS) {
  queryParams.adapters = process.env.ADAPTERS;
}
if (process.env.AUTO_COMPACTION) {
  queryParams.autoCompaction = true;
}

var indexfile = "./lib/index.js";
var outfile = "./dist/pouchdb.js";
var perfRoot = './tests/performance/';
var performanceBundle = './tests/performance-bundle.js';

var w = watchify(browserify(indexfile, {
  standalone: "PouchDB",
  cache: {},
  packageCache: {},
  fullPaths: true,
  debug: true
})).on('update', bundle);
var b = watchify(browserify({
    entries: perfRoot,
    cache: {},
    packageCache: {},
    fullPaths: true,
    debug: true
  })).on('update', bundlePerfTests);

function bundle(callback) {
  mkdirp.sync('./dist');
  w.bundle().pipe(derequire()).pipe(fs.createWriteStream(outfile))
  .on('finish', function () {
Example #7
0
gulp.task('browserify', ['clean-dist'], () => {
  const bundle = browserify({entries: './src/av-browser.js'});
  return bundle.bundle()
    .pipe(source('av-es6.js'))
    .pipe(gulp.dest('dist'));
});
Example #8
0
    })
    .on('restart', function onRestart() {
      // reload connected browsers after a slight delay
      setTimeout(function reload() {
        browserSync.reload({
          stream: false
        });
      }, BROWSER_SYNC_RELOAD_DELAY);
    });
  });

// Browserify bundler
var bundler = browserify({
  entries: ['./public/main.jsx'], // bundle the main.jsx file
  paths: ['./node_modules','./public'], // paths to files bundle may require
  transform: [reactify],
  debug: true,
  // Required properties for watchify
  cache: {}, packageCache: {}, fullPaths: true
}).plugin(resolutions, '*')
  .on('time', function (time) {
    console.log('Bundle updated in ' + (time / 1000) + 's.');
  });

// Watcher on the bundle

gulp.task('bundle', ['sass'], function () {
  bundler.bundle()
  .on('error', function (err) {
    console.log(err.toString());
  })
  .pipe(source('main.js'))
function compile(path, options, cb, cacheUpdated) {
  cb = guard(cb);
  var cache;
  if (options.cache === 'dynamic') {
    var cacheName = path + ':' + options.external + ':' + options.debug;
    cache = dynamicCache[cacheName];
    if (cache && !cacheUpdated) {
      return cache.update(function () { compile(path, options, cb, true) });
    } else if (!cache) {
      cache = (dynamicCache[cacheName] = new DynamicCache());
    }
  }

  var bundle = browserify({
    noParse: options.noParse,
    extensions: options.extensions,
    resolve: options.resolve,
    insertGlobals: options.insertGlobals,
    detectGlobals: options.detectGlobals,
    ignoreMissing: options.ignoreMissing,
    debug: options.debug,
    standalone: options.standalone || false,
    cache: cache ? cache.getCache() : undefined
  });
  if (options.plugins) {
    var plugins = options.plugins; // in the format options.plugins = [{plugin: plugin, options: options}, {plugin: plugin, options: options}, ... ]
    for(var i = 0; i < plugins.length; i++) {
      var obj = plugins[i];
      bundle.plugin(obj.plugin, obj.options);
    }
  }
  if (Array.isArray(path)) {
    for (var i = 0; i < path.length; i++) {
      if (typeof path[i] === 'object') { // obj spec support; i.e. {"jquery": {options...}}
        var spec = path[i];
        var keys = Object.keys(spec);
        keys.forEach(function (key) {
          console.dir(key);
          console.dir(spec[key]);
          bundle.require(key, spec[key]);
        })
      } else {
        bundle.require(path[i]);
      }
    }
  } else {
    bundle.add(path);
  }
  if (cache) {
    cache.populate(bundle);
  }
  for (var i = 0; i < (options.external || []).length; i++) {
    bundle.external(options.external[i]);
  }
  for (var i = 0; i < (options.ignore || []).length; i++) {
    bundle.ignore(options.ignore[i]);
  }
  for (var i = 0; i < (options.transform || []).length; i++) {
    var transform = options.transform[i];

    if (Array.isArray(transform)) {
      bundle.transform(transform[1], transform[0]);
    } else {
      bundle.transform(transform);
    }
  }
  bundle.bundle(function (err, src) {
    if (err) return cb(err);
    src = src.toString();
    if (options.postcompile) src = options.postcompile(src);
    /*
    if (options.debug) {
      if (options.basedir) {
        src = transformSourcesRelativeTo(src, options.basedir);
      }
      src = unixifySourceMap(src);
    }
    */
    if (options.minify) {
      if (options.preminify) src = options.preminify(src);
      try {
        src = minify(src, options.minify).code;
      } catch (ex) { } //better to just let the client fail to parse
      if (options.postminify) src = options.postminify(src);
    }
    cb(null, src);
  });
}
Example #10
0
function embedBundler(args) {
  return browserify('./lib/embed.js', args)
}
Example #11
0
gulp.task('javascript', [ 'clean:js', 'lint:js' ], function() {
  return browserify(config.dir.src +'app.js').bundle()
    .pipe(source('app.js', config.dir.src).on('error', gutil.log))
    .pipe(gulp.dest(config.dir.build))
  ;
});
Example #12
0
function heimBundler(args) {
  return browserify('./lib/client.js', args)
}
Example #13
0
var gulp = require("gulp");
var browserify = require("browserify");
var source = require('vinyl-source-stream');
var watchify = require("watchify");
var tsify = require("tsify");
var gutil = require("gulp-util");
var sass = require("gulp-sass");
var pug = require('gulp-pug');
var paths = {
    pages: ['src/*.html']
};

var watchedBrowserify = watchify(browserify({
    basedir: '.',
    debug: true,
    entries: ['src/main.ts'],
    cache: {},
    packageCache: {}
}).plugin(tsify));

gulp.task("copy-html", function () {
    return gulp.src(paths.pages)
        .pipe(gulp.dest("dist"));
});

gulp.task('sass', function () {
  return gulp.src('./scss/portfolio.scss')
    .pipe(sass().on('error', sass.logError))
    .pipe(gulp.dest('./dist'));
});
Example #14
0
'use strict';
var browserify =  require('browserify')
  , fs         =  require('fs');

browserify()
  .require(require.resolve('./javascript-editor'), { entry: true })
  .require(require.resolve('./coffee-editor'), { entry: true })
  .require(require.resolve('./json-editor'), { entry: true })
  .require(require.resolve('./lua-editor'), { entry: true })
  .bundle({ debug: true })
  .pipe(fs.createWriteStream(__dirname + '/bundle.js'));
Example #15
0
    notify.onError({
      message: task + ' failed, check the logs..',
      sound: false
    })(err);

    gutil.log(gutil.colors.bgRed(task + ' error:'), gutil.colors.red(err));
  };
};

var customOpts = {
  entries: ['./js/main.js'],
  debug: true //creates readable 'source maps' of code
};
var opts = assign({}, watchify.args, customOpts);
var bundler = watchify(browserify(opts));
bundler.on('update', bundle); // on any dep update, runs the bundler
bundler.on('log', gutil.log); // output build logs to terminal

function bundle() {
  return bundler.bundle()
    // log errors if they happen
    .on('error', gutil.log.bind(gutil, 'Browserify Error'))
    .pipe(source('bundle.js'))
    // optional, remove if you don't need to buffer file contents
    .pipe(buffer())
    // optional, remove if you dont want sourcemaps
    .pipe(sourcemaps.init({loadMaps: true})) // loads map from browserify file
       // Add transformation tasks to the pipeline here.
    .pipe(sourcemaps.write('./')) // writes .map file
    .pipe(gulp.dest('./dist'));
Example #16
0
        message += file[file.length-1];
    }

    if (error.lineNumber) {
        message += '\nOn Line: ' + error.lineNumber;
    }

    notifier.notify({title: title, message: message});
};

// Bundle settings, Step 9 starts
var bundler = watchify(browserify({
    entries: ['./src/app.jsx'],
    transform: [reactify],
    extensions: ['.jsx'],
    debug: true,
    cache: {},
    packageCache: {},
    fullPaths: true
}));

// Bundle tasks
function bundle() {
    return bundler
        .bundle()
        .on('error', notify)
        .pipe(source('main.js'))
        .pipe(gulp.dest('./'))
}
bundler.on('update', bundle);
Example #17
0
var createBundle = function(opts) {
  opts.dir = opts.dir || 'js/';

  var bopts = {
    pack: pack,
    debug: true,
    standalone: 'copay',
    insertGlobals: true
  };
  var b = browserify(bopts);

  b.require('bitcore/node_modules/browserify-buffertools/buffertools.js', {
    expose: 'buffertools'
  });

  b.require('./copay', {
    expose: 'copay'
  });
  b.require('./version');
//  b.external('bitcore');
  b.require('./js/models/core/WalletFactory', {
    expose: '../js/models/core/WalletFactory'
  });
  b.require('./js/models/core/Wallet');
  b.require('./js/models/core/Wallet', {
    expose: '../js/models/core/Wallet'
  });
  b.require('./test/mocks/FakeStorage', {
    expose: './mocks/FakeStorage'
  });
  b.require('./test/mocks/FakeBlockchain', {
    expose: './mocks/FakeBlockchain'
  });
  b.require('./js/models/core/Wallet', {
    expose: '../js/models/core/Wallet'
  });
  b.require('./test/mocks/FakeNetwork', {
    expose: './mocks/FakeNetwork'
  });
  b.require('./js/models/network/WebRTC', {
    expose: '../js/models/network/WebRTC' 
  });
  b.require('./js/models/blockchain/Insight', {
    expose: '../js/models/blockchain/Insight'
  });
  b.require('./js/models/core/PrivateKey', {
    expose: '../js/models/core/PrivateKey'
  });
  b.require('./js/models/core/PublicKeyRing', {
    expose: '../js/models/core/PublicKeyRing'
  });
  b.require('./js/models/core/Passphrase', {
    expose: '../js/models/core/Passphrase'
  });

  if (opts.dontminify) {
    //include dev dependencies
    b.require('sinon');
    b.require('blanket');
    b.require('soop');
  }

  if (!opts.dontminify) {
    b.transform({
      global: true
    }, 'uglifyify');
  }
  var bundle = b.bundle();
  return bundle;
};
  gulp.task(`${output}-browserify`, () =>
    browserify(src)
			.transform("brfs").bundle()
			.pipe(source(`${output}.js`))
			.pipe(gulp.dest(dest))
    topic: function() {
      var b = browserify(path.join(__dirname, 'nonexisting.js'));

        b.transform(configify);
        b.bundle(this.callback);
    },
Example #20
0
gulp.task('client-scripts', ['jsx'], function() {
    return browserify('./bin/assets/js/index.js').bundle()
               .pipe(source('index.js'))
               .pipe(gulp.dest('bin/assets/js'));
});
Example #21
0
gulp.task('build', function() {
  browserify('src/main.js')
    .transform('babelify', {presets: ['es2015', 'react']})
    .bundle()
    .pipe(fs.createWriteStream('public/js/bundle.js'));
});
Example #22
0
gulp.task('browserify', function () {
    return browserify(paths.js.src)
        .bundle()
        .pipe(source(paths.js.destFile))
        .pipe(gulp.dest(paths.js.dest))
});
Example #23
0
gulp.task('browserify', function() {
  return browserify('./app/scripts/app.js')
    .bundle()
    .pipe(source('main.js'))
    .pipe(gulp.dest('./public/js/'));
});
Example #24
0
gulp.task('browserify', function() {
    return browserify('src/js/app.js')
        .bundle()
        .pipe(vinylSourceStream('bundle.js'))
        .pipe(gulp.dest('dist/js'));
});
Example #25
0
( function() {

  'use strict';

  let gulp = require( 'gulp' );

  let browserify = require( 'browserify' );
  let watchify = require( 'watchify' );
  let babelify = require( 'babelify' );
  let sass = require( 'gulp-sass' );
  let source = require( 'vinyl-source-stream' );

  let browserSync = require( 'browser-sync' );

  // ---

  gulp.task( 'static-build',function() {
    gulp.src( [ './src/static/**/*' ] )
    .pipe( gulp.dest( './dist' ) );
  } );

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

  // ---

  gulp.task( 'style-build', function() {
    return gulp.src( './src/style/main.scss' )
    .pipe( sass().on( 'error', sass.logError ) )
    .pipe( gulp.dest( './dist' ) )
    .pipe( browserSync.stream() )
  } );

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

  // ---

  let brwsrfy = browserify( {
    cache: {},
    packageCache: {},
    fullPaths: true,
    entries: [ './src/script/main.js' ],
    transform: [
      [ babelify, {
        presets: 'es2015'
      } ],
      'glslify'
    ]
  } );

  gulp.task( 'script-build', function() {
    brwsrfy.bundle()
    .on( 'error', function( _error ) {
      console.error( _error );
      this.emit( 'end' );
    } )
    .pipe( source( 'main.js' ) )
    .pipe( gulp.dest( './dist' ) );
  } );

  gulp.task( 'script-watch', function() {
    let wtcfy = watchify( brwsrfy );

    wtcfy.on( 'update', function() {
      console.log( '🔮 Browserify!' );
      wtcfy.bundle()
      .on( 'error', function( _error ) {
        console.error( _error );
        this.emit( 'end' );
      } )
      .pipe( source( 'main.js' ) )
      .pipe( gulp.dest( './dist' ) );
    } );

    wtcfy.on( 'log', function( _log ) {
      console.log( '🍕 ' + _log );
    } );
  } );

  // ---

  gulp.task( 'browser-init', function() {
    browserSync.init( {
      server: './dist'
    } );
  } );

  gulp.task( 'browser-reload', function() {
    browserSync.reload();
  } );

  gulp.task( 'browser-watch', function() {
    gulp.watch( [ './dist/**', '!./dist/**/*.css' ], [ 'browser-reload' ] );
  } );

  // ---

  gulp.task( 'watch', [
    'static-watch',
    'style-watch',
    'script-watch'
  ] );

  gulp.task( 'build', [
    'static-build',
    'style-build',
    'script-build'
  ] );

  gulp.task( 'browser', [
    'browser-init',
    'browser-watch'
  ] );

  gulp.task( 'dev', [
    'build',
    'watch',
    'browser'
  ] );

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

} )();
Example #26
0
var browserify = require('browserify'),
    b = browserify(),
    fs = require('fs');

var filename = 'time-counter.bundled.js';

b.add('./time-counter.js');
b.bundle({standalone: 'TimeCounter'}, function (err, code) {
    fs.writeFile(filename, code, function (err) {
        if (!err) console.log(filename + ' built!');
    });
})
Example #27
0
 .pipe(tap(function(file){ // tap nos permite ejecutar un código por cada fichero seleccionado en el paso anterior
     file.contents = browserify(file.path).bundle(); // pasamos el archivo por browserify para importar los require
 }))
Example #28
0
var watchify = require('watchify');
var browserify = require('browserify');
var ecstatic = require('ecstatic');
var reactify = require('reactify');

var paths = {
  js: 'src/**/*.js'
};

var bundleCache = {};
var pkgCache = {};

var bundler = watchify(browserify('./src/index.js', {
  cache: bundleCache,
  packageCache: pkgCache,
  fullPaths: true,
  standalone: 'react-responsive',
  debug: true
}));

var sampleBundler = watchify(browserify('./samples/sandbox/src/index.jsx', {
  cache: bundleCache,
  packageCache: pkgCache,
  fullPaths: true,
  standalone: 'sample',
  debug: true
}));
sampleBundler.transform(reactify);

var staticSampleBundler = watchify(browserify('./samples/static/src/index.jsx', {
  cache: bundleCache,
Example #29
0
gulp.task('jsBrowserify', ['concatInterface'], function() {
  return browserify({ entries: ['./tmp/allConcat.js'] })
    .bundle()
    .pipe(source('app.js'))
    .pipe(gulp.dest('./build/js'));
});
Example #30
0
function browser() {
    return browserify('./performance/browser.js').
        bundle().
        pipe(vinyl('browser.js')).
        pipe(gulp.dest('performance/bin'));
}