<commit_before>#!/usr/bin/env node
const Crawler = require("crawler")
const fs = require("fs")
const vm = require('vm')
const request = require('request')
const unpack = require('unpacker').unpack
const progress = require('request-progress')
const ProgressBar = require('node-progress-bars')
const stringWidth = require('string-width')

function right_pad(str, len, padding_chr) {
    padding_chr = padding_chr || ' '
    var curr_size = stringWidth(str)
    var padding_len = len - curr_size
    if (padding_len <= 0) {
        return str
    }
    return str + new Array(padding_len + 1).join(padding_chr)
}

var video_callback = function(dir, anime_name, episode_number){
    return function(error, result, $){
        //console.log(result)
        //console.log(dir)
        //console.log(name)

        //console.log(result)
        //console.log($("script").last().text())
        // parse js code
        //var code = /eval\((.*)\);/.exec($("script").last().text())[1]
        var code = $("script").last().text()
        //console.log(code)
        code = unpack(code)
        code = code.replace(/player\.on(.|[\n\r])*/, '')
        code = code.replace(/var player=jwplayer\('videoContainer'\);/, '')
        code = code.replace(/player.setup\(playerSetup\)/, '')
        //console.log(code)
        const sandbox = {}
        vm.runInNewContext(code, sandbox)
        var url = sandbox.playerSetup.playlist[0].sources.pop()
        var type = /.*\/(.*)/.exec(url.type)[1]
        var label = url.label
        var filename = dir + "/[" + anime_name + "]" + "[" + episode_number + "][" + label + "]." + type
        var file = fs.createWriteStream(filename)
        var display_name = dir + ' - ' + episode_number
        var bar_format = right_pad(display_name, 40) + ".white[:bar].green :percent.yellow :ets sec :speed kB/s"
        var progress_bar, last_tick = 0

        progress(request(url.file))
            .on('progress', function (state) {
                if (!progress_bar) {
                    progress_bar = new ProgressBar({
                        schema: bar_format,
                        width: 50,
                        filled: '#',
                        blank: ' ',
                        total: state.size.total
                    })
                }
                var delta_tick = state.size.transferred - last_tick
                progress_bar.tick(delta_tick, {
                    speed: (state.speed / 1000).toFixed(2),
                    ets: state.time.remaining
                })
                last_tick = state.size.transferred
            })
            .on('end', function () {
                console.log(filename + " done!")
            })
            .pipe(file)
    }
}

var video = new Crawler({
    forceUTF8: true
})

var page = new Crawler({
    forceUTF8: true,
    callback: function(error, result, $){
        name = /^([^\[]*)\[.*\[.*\]\]\W+\](\[.*\])?$/.exec($('a#thread_subject').text())
        anime_name = (name[1] == undefined ? '' : name[1].trim())
        anime_status = (name[2] == undefined ? '' : name[2].trim())
        dir = "[" + anime_name + "]" + anime_status
        fs.existsSync(dir) || fs.mkdirSync(dir)

        $('a[href|="/thread"]').each(function(index, a){
            //console.log($(a).attr('href'))
            //console.log($(a).text())
            var episode_number = $(a).text()
            var href = $(a).attr('href')
            //console.log(/#.*/.exec(href))
            //console.log($('div' + /#.*/.exec(href)).children('span').attr('href'))
            var uri = $('div' + /#.*/.exec(href)).children('span').attr('href')
            uri && video.queue({
                uri: uri,
                callback: video_callback(dir, anime_name, episode_number)
            })
        })
    }
})

var page_list = process.argv.slice(2)
//console.log(page_list)
if(page_list.length > 0)
    page.queue(page_list)
else
    console.log("node index.js <2dg-url> [<2dg-url> ...]")
<commit_msg>Add debug_mode into cli option.<commit_after>#!/usr/bin/env node
const Crawler = require("crawler")
const fs = require("fs")
const vm = require('vm')
const request = require('request')
const unpack = require('unpacker').unpack
const progress = require('request-progress')
const ProgressBar = require('node-progress-bars')
const stringWidth = require('string-width')

function right_pad(str, len, padding_chr) {
    padding_chr = padding_chr || ' '
    var curr_size = stringWidth(str)
    var padding_len = len - curr_size
    if (padding_len <= 0) {
        return str
    }
    return str + new Array(padding_len + 1).join(padding_chr)
}

var video_callback = function(dir, anime_name, episode_number){
    return function(error, result, $){
        //console.log(result)
        //console.log(dir)
        //console.log(name)

        //console.log(result)
        //console.log($("script").last().text())
        // parse js code
        //var code = /eval\((.*)\);/.exec($("script").last().text())[1]
        var code = $("script").last().text()
        //console.log(code)
        code = unpack(code)
        code = code.replace(/player\.on(.|[\n\r])*/, '')
        code = code.replace(/var player=jwplayer\('videoContainer'\);/, '')
        code = code.replace(/player.setup\(playerSetup\)/, '')
        //console.log(code)
        const sandbox = {}
        vm.runInNewContext(code, sandbox)
        var url = sandbox.playerSetup.playlist[0].sources.pop()
        var type = /.*\/(.*)/.exec(url.type)[1]
        var label = url.label
        var filename = dir + "/[" + anime_name + "]" + "[" + episode_number + "][" + label + "]." + type
        var file = fs.createWriteStream(filename)
        var display_name = dir + ' - ' + episode_number
        var bar_format = right_pad(display_name, 40) + ".white[:bar].green :percent.yellow :ets sec :speed kB/s"
        var progress_bar, last_tick = 0

        progress(request(url.file))
            .on('progress', function (state) {
                if (!progress_bar) {
                    progress_bar = new ProgressBar({
                        schema: bar_format,
                        width: 50,
                        filled: '#',
                        blank: ' ',
                        total: state.size.total
                    })
                }
                var delta_tick = state.size.transferred - last_tick
                progress_bar.tick(delta_tick, {
                    speed: (state.speed / 1000).toFixed(2),
                    ets: state.time.remaining
                })
                last_tick = state.size.transferred
            })
            .on('end', function () {
                console.log(filename + " done!")
            })
            .pipe(file)
    }
}

var video = new Crawler({
    forceUTF8: true
})

var page = new Crawler({
    forceUTF8: true,
    callback: function(error, result, $){
        name = /^([^\[]*)\[.*\[.*\]\]\W+\](\[.*\])?$/.exec($('a#thread_subject').text())
        anime_name = (name[1] == undefined ? '' : name[1].trim())
        anime_status = (name[2] == undefined ? '' : name[2].trim())
        dir = "[" + anime_name + "]" + anime_status
        fs.existsSync(dir) || fs.mkdirSync(dir)

        $('a[href|="/thread"]').each(function(index, a){
            //console.log($(a).attr('href'))
            //console.log($(a).text())
            var episode_number = $(a).text()
            var href = $(a).attr('href')
            //console.log(/#.*/.exec(href))
            //console.log($('div' + /#.*/.exec(href)).children('span').attr('href'))
            var uri = $('div' + /#.*/.exec(href)).children('span').attr('href')
            uri && video.queue({
                uri: uri,
                callback: video_callback(dir, anime_name, episode_number)
            })
        })
    }
})

var debug_mode = false
if (process.argv[2] == '-d' || process.argv[2] == '--debug') {
    console.log("Debug mode turned on.")
    debug_mode = true
    var page_list = process.argv.slice(3)
}
else {
    var page_list = process.argv.slice(2)
}

if(page_list.length > 0) {
    if (debug_mode) {
        console.log("page_list:", page_list)
    }

    page.queue(page_list)
}
else {
    console.log("node index.js [-d | --debug] <2dg-url> [<2dg-url> ...]")
}
<|endoftext|>


<commit_before>"use strict";

var CoffeeScript  = require('coffee-script');
// -- Register CoffeeScript if exits -------------------------------------------
if(CoffeeScript.register) CoffeeScript.register();

var Zen           = require('./lib/zen');

module.exports = {
    // Crawler     : require("./lib/helpers/crawler"),
    // Cron        : require("./lib/helpers/cron"),
    // Deploy      : require("./lib/helpers/deploy"),
    // Model       : require("./lib/helpers/model"),
    // Services
    // Mongo       : require("./lib/services/mongo"),
    // Redis       : require("./lib/services/redis"),
    // Appnima     : require("./lib/services/appnima"),
    // Facade
    // Mongoose    : require("mongoose"),
    // Hope        : require("hope"),
    // Instance
    start         : function() {
        return new Zen()
    }
};
<commit_msg>Export services & modules<commit_after>"use strict";

var CoffeeScript  = require('coffee-script');
// -- Register CoffeeScript if exits -------------------------------------------
if(CoffeeScript.register) CoffeeScript.register();

var Zen           = require('./lib/zen');

module.exports = {
    // Crawler     : require("./lib/helpers/crawler"),
    // Cron        : require("./lib/helpers/cron"),
    // Deploy      : require("./lib/helpers/deploy"),
    // Model       : require("./lib/helpers/model"),
    // Services
    Mongo       : require("./lib/services/mongo"),
    Redis       : require("./lib/services/redis"),
    Appnima     : require("./lib/services/appnima"),
    // Facade
    Mongoose    : require("mongoose"),
    Hope        : require("hope"),
    // Instance
    start         : function() {
        return new Zen()
    }
};
<|endoftext|>


<commit_before>require('dotenv').load();

const express = require('express');
const passport = require('passport');
const next = require('next');
const cookieSession = require('cookie-session');
const session = require('express-session');
const ControlTowerStrategy = require('passport-control-tower');
const cookieParser = require('cookie-parser');
const bodyParser = require('body-parser');
const basicAuth = require('basic-auth');
const sass = require('node-sass');
const { parse } = require('url');
const routes = require('./routes');

const port = process.env.PORT || 3000;
const dev = process.env.NODE_ENV !== 'production';

// Next app creation
const app = next({ dev });
const handle = routes.getRequestHandler(app);

// Express app creation
const server = express();

function auth(username, password) {
  return function authMiddleware(req, res, nextAction) {
    const user = basicAuth(req);
    if (!user || user.name !== username || user.pass !== password) {
      res.set('WWW-Authenticate', 'Basic realm=Authorization Required');
      return res.sendStatus(401);
    }
    return nextAction();
  };
}

function isAuthenticated(req, res, nextAction) {
  if (req.isAuthenticated()) return nextAction();
  // if they aren't redirect them to the home page
  return res.redirect('/login');
}

function isAdmin(req, res, nextAction) {
  if (req.user.role === 'ADMIN') return nextAction();
  // if they aren't redirect them to the home page
  return res.redirect('/myrw');
}

// Use the Control Tower Strategy within Passport.
const controlTowerStrategy = new ControlTowerStrategy({
  controlTowerUrl: process.env.CONTROL_TOWER_URL,
  callbackUrl: process.env.CALLBACK_URL
});
passport.use(controlTowerStrategy);

// Passport session setup.
// To support persistent login sessions, Passport needs to be able to
// serialize users into and deserialize users out of the session.
passport.serializeUser((user, done) => done(null, user));
passport.deserializeUser((obj, done) => done(null, obj));

// configure Express
server.use(cookieParser());
server.use(bodyParser.urlencoded({ extended: false }));
server.use(bodyParser.json());
server.use(cookieSession({
  name: 'session',
  keys: [process.env.SECRET || 'keyboard cat']
}));
server.use(session({
  secret: process.env.SECRET || 'keyboard cat',
  resave: false,
  saveUninitialized: true
}));
server.use('/static', express.static('static'));

if (process.env.NODE_ENV === 'production') {
  server.use(auth(process.env.USERNAME, process.env.PASSWORD));
}

// Initialize Passport!
server.use(passport.initialize());
server.use(passport.session());

// Initializing next app before express server
app.prepare()
  .then(() => {
    // Add route to serve compiled SCSS from /assets/{build id}/main.css
    // Note: This is is only used in production, in development it is inlined
    if (!dev) {
      const sassResult = sass.renderSync({ file: './css/index.scss', outputStyle: 'compressed' });
      server.get('/styles/:id/index.css', (req, res) => {
        res.setHeader('Content-Type', 'text/css');
        res.setHeader('Cache-Control', 'public, max-age=2592000');
        res.setHeader('Expires', new Date(Date.now() + 2592000000).toUTCString());
        res.send(sassResult.css);
      });
    }

    server.get('/data', (req, res) => res.redirect('/data/explore'));

    // On success, redirecting to My RW
    server.get('/auth', passport.authenticate('control-tower', { failureRedirect: '/' }),
      (req, res) => res.redirect('/myrw'));

    server.get('/auth/user', (req, res) => res.json(req.user || {}));

    server.get('/login', (req, res) => controlTowerStrategy.login(req, res));

    server.get('/logout', (req, res) => {
      req.logout();
      return res.redirect('/');
    });

    const handleUrl = (req, res) => {
      const parsedUrl = parse(req.url, true);
      return handle(req, res, parsedUrl);
    };

    server.get('/myrw*?', isAuthenticated, handleUrl);
    server.get('/admin*?', isAuthenticated, isAdmin, handleUrl);

    server.use(handle);

    server.listen(port, (err) => {
      if (err) throw err;
      console.info(`> Ready on http://localhost:${port}`);
    });
  });
<commit_msg>removed sass in express server<commit_after>require('dotenv').load();

const express = require('express');
const passport = require('passport');
const next = require('next');
const cookieSession = require('cookie-session');
const session = require('express-session');
const ControlTowerStrategy = require('passport-control-tower');
const cookieParser = require('cookie-parser');
const bodyParser = require('body-parser');
const basicAuth = require('basic-auth');
const sass = require('node-sass');
const { parse } = require('url');
const routes = require('./routes');

const port = process.env.PORT || 3000;
const dev = process.env.NODE_ENV !== 'production';

// Next app creation
const app = next({ dev });
const handle = routes.getRequestHandler(app);

// Express app creation
const server = express();

function auth(username, password) {
  return function authMiddleware(req, res, nextAction) {
    const user = basicAuth(req);
    if (!user || user.name !== username || user.pass !== password) {
      res.set('WWW-Authenticate', 'Basic realm=Authorization Required');
      return res.sendStatus(401);
    }
    return nextAction();
  };
}

function isAuthenticated(req, res, nextAction) {
  if (req.isAuthenticated()) return nextAction();
  // if they aren't redirect them to the home page
  return res.redirect('/login');
}

function isAdmin(req, res, nextAction) {
  if (req.user.role === 'ADMIN') return nextAction();
  // if they aren't redirect them to the home page
  return res.redirect('/myrw');
}

// Use the Control Tower Strategy within Passport.
const controlTowerStrategy = new ControlTowerStrategy({
  controlTowerUrl: process.env.CONTROL_TOWER_URL,
  callbackUrl: process.env.CALLBACK_URL
});
passport.use(controlTowerStrategy);

// Passport session setup.
// To support persistent login sessions, Passport needs to be able to
// serialize users into and deserialize users out of the session.
passport.serializeUser((user, done) => done(null, user));
passport.deserializeUser((obj, done) => done(null, obj));

// configure Express
server.use(cookieParser());
server.use(bodyParser.urlencoded({ extended: false }));
server.use(bodyParser.json());
server.use(cookieSession({
  name: 'session',
  keys: [process.env.SECRET || 'keyboard cat']
}));
server.use(session({
  secret: process.env.SECRET || 'keyboard cat',
  resave: false,
  saveUninitialized: true
}));
server.use('/static', express.static('static'));

if (process.env.NODE_ENV === 'production') {
  server.use(auth(process.env.USERNAME, process.env.PASSWORD));
}

// Initialize Passport!
server.use(passport.initialize());
server.use(passport.session());

// Initializing next app before express server
app.prepare()
  .then(() => {
    // Add route to serve compiled SCSS from /assets/{build id}/main.css
    // Note: This is is only used in production, in development it is inlined
    // if (!dev) {
    //   const sassResult = sass.renderSync({ file: './css/index.scss', outputStyle: 'compressed' });
    //   server.get('/styles/:id/index.css', (req, res) => {
    //     res.setHeader('Content-Type', 'text/css');
    //     res.setHeader('Cache-Control', 'public, max-age=2592000');
    //     res.setHeader('Expires', new Date(Date.now() + 2592000000).toUTCString());
    //     res.send(sassResult.css);
    //   });
    // }

    server.get('/data', (req, res) => res.redirect('/data/explore'));

    // On success, redirecting to My RW
    server.get('/auth', passport.authenticate('control-tower', { failureRedirect: '/' }),
      (req, res) => res.redirect('/myrw'));

    server.get('/auth/user', (req, res) => res.json(req.user || {}));

    server.get('/login', (req, res) => controlTowerStrategy.login(req, res));

    server.get('/logout', (req, res) => {
      req.logout();
      return res.redirect('/');
    });

    const handleUrl = (req, res) => {
      const parsedUrl = parse(req.url, true);
      return handle(req, res, parsedUrl);
    };

    server.get('/myrw*?', isAuthenticated, handleUrl);
    server.get('/admin*?', isAuthenticated, isAdmin, handleUrl);

    server.use(handle);

    server.listen(port, (err) => {
      if (err) throw err;
      console.info(`> Ready on http://localhost:${port}`);
    });
  });
<|endoftext|>


<commit_before>Error.stackTraceLimit = Infinity

require('babel/register')({
  // necessary so that the local app/node_modules/* will be transpiled
  only: /scegratoo/,
  sourceMaps: 'inline',
  // sourceFileName: '(filenameRelative).es6',
  sourceRoot: 'babel'
})

global.Promise = require('bluebird')

require('./scegratoo/app.js')
<commit_msg>enable long stack traces for promise rejections<commit_after>Error.stackTraceLimit = Infinity

require('babel/register')({
  // necessary so that the local app/node_modules/* will be transpiled
  only: /scegratoo/,
  sourceMaps: 'inline',
  // sourceFileName: '(filenameRelative).es6',
  sourceRoot: 'babel'
})

global.Promise = require('bluebird')
Promise.longStackTraces()

require('./scegratoo/app.js')
<|endoftext|>


<commit_before>function clone(obj) {
  return JSON.parse(JSON.stringify(obj));
}

module.exports = function(obj) {
  var cloned = clone(obj);

  return cloned;
};
<commit_msg>Implement basic library functionality<commit_after>'use strict';

function createTree(list, rootNodes) {
  var tree = [];

  for (var prop in rootNodes) {
    if (!rootNodes.hasOwnProperty(prop)) {
      continue;
    }

    var node = rootNodes[prop];

    if (list[node.id]) {
      node.children = createTree(list, list[node.id]);
    }

    tree.push(node);
  }

  return tree;
}

function orderByParents(list) {
  var parents = {};

  list.forEach(function(item) {
    var parentID = item.parent_id || 0;
    parents[parentID] = parents[parentID] || [];
    parents[parentID].push(item);
  });

  return parents;
}

function clone(obj) {
  return JSON.parse(JSON.stringify(obj));
}

module.exports = function(obj) {
  var cloned = clone(obj);
  var ordered = orderByParents(cloned);
  return createTree(ordered, ordered[0]);
};
<|endoftext|>


<commit_before>const yaml = require('js-yaml');
const Stale = require('./lib/radar');

// Check for stale issues every hour
const INTERVAL = 60 * 60 * 1000;

module.exports = (robot) => {
  // Your plugin code here
  console.log('Yay, the plugin was loaded!');

  check()

  async function check() {
    robot.log.info('Checking for open issues');

    const github = await robot.integration.asIntegration();
    // TODO: Pagination
    const installations = await github.integrations.getInstallations({});
    return installations.map(i => checkInstallation(i));
  }

  async function checkInstallation(installation) {
     const github = await robot.auth(installation.id);
     // TODO: Pagination
     const data = await github.integrations.getInstallationRepositories({});
     return data.repositories.map(async repo => {
       const radar = await forRepository(github, repo);
       return radar.getIssues();
     });
   }

  async function forRepository(github, repository) {
    const owner = repository.owner.login;
    const repo = repository.name;
    const path = '.github/radar.yml';
    let config;

    try {
      const data = await github.repos.getContent({owner, repo, path});
      config = yaml.load(new Buffer(data.content, 'base64').toString());
    } catch (err) {
      config = {};
    }
    config = Object.assign(config, {owner, repo, logger: robot.log});
    robot.log("config:", config)
    return new Radar(github, config);
  }
};
<commit_msg>copy paste error<commit_after>const yaml = require('js-yaml');
const Radar = require('./lib/radar');

// Check for stale issues every hour
const INTERVAL = 60 * 60 * 1000;

module.exports = (robot) => {
  // Your plugin code here
  console.log('Yay, the plugin was loaded!');

  check()

  async function check() {
    robot.log.info('Checking for open issues');

    const github = await robot.integration.asIntegration();
    // TODO: Pagination
    const installations = await github.integrations.getInstallations({});
    return installations.map(i => checkInstallation(i));
  }

  async function checkInstallation(installation) {
     const github = await robot.auth(installation.id);
     // TODO: Pagination
     const data = await github.integrations.getInstallationRepositories({});
     return data.repositories.map(async repo => {
       const radar = await forRepository(github, repo);
       return radar.getIssues();
     });
   }

  async function forRepository(github, repository) {
    const owner = repository.owner.login;
    const repo = repository.name;
    const path = '.github/radar.yml';
    let config;

    try {
      const data = await github.repos.getContent({owner, repo, path});
      config = yaml.load(new Buffer(data.content, 'base64').toString());
    } catch (err) {
      config = {};
    }
    config = Object.assign(config, {owner, repo, logger: robot.log});
    robot.log("config:", config)
    return new Radar(github, config);
  }
};
<|endoftext|>


<commit_before>'use strict';

var path = require('path');
var fs = require('graceful-fs');
var _ = require('lodash');
var through = require('through2');
var convert = require('convert-source-map');

class Wallabify {

  constructor(opts, initializer) {
    this._patchModuleDependenciesModule();

    this._opts = opts || {};
    this._initializer = initializer;

    this._b = null;
    this._browserifyCache = {};
    this._affectedFilesCache = {};
    this._initRequired = false;
    this._allTrackedFiles = {};
  }

  createPostprocessor() {
    var self = this;
    try {
      this._browserify = require('browserify');
    }
    catch (e) {
      console.error('Browserify node module is not found, missing `npm install browserify --save-dev`?');
      return;
    }

    // wallaby.js postprocessor for browserify
    // The postprocessor creates and reuses browserify instance.
    // It splices browserify pipeline so that file concatenation doesn't happen.
    // Instead, the postprocessor creates new files and lets wallaby.js to serve them to browser as requested.
    // This allows to leverage file-based browser caching as opposed to always reload a full bundle.
    // When separate files load, they only add a function with the file body to the cache object.
    // Actual loading happens when window.__moduleBundler.loadTests is called (from bootstrap function).

    return wallaby => {
      var logger = wallaby.logger;
      var affectedFiles = wallaby.affectedFiles;
      if (!self._b || wallaby.anyFilesAdded || wallaby.anyFilesDeleted) {

        if (!self._b) {
          logger.debug('New browserify instance created');
        }
        else {
          logger.debug('Browserify instance re-created because some tracked files were added or deleted');
        }

        self._initRequired = true;
        self._affectedFilesCache = {};
        self._allTrackedFiles = _.reduce(wallaby.allFiles, function (memo, file) {
          memo[file.fullPath] = file;
          return memo;
        }, {});
        affectedFiles = wallaby.allFiles;

        self._b = self._createBrowserify({
          entries: _.map(wallaby.allTestFiles, testFile => testFile.fullPath),
          paths: wallaby.nodeModulesDir ? [wallaby.nodeModulesDir] : [],
          cache: {}, packageCache: {}, fullPaths: true
        });

        self._browserifyCache = self._b._options.cache;

        self._b.on('dep', function (dep) {
          if (typeof dep.id === 'string') {
            var key = dep.id;
            if (!self._browserifyCache[key]) {
              self._browserifyCache[key] = dep;
              // external files are cached by file name as well to avoid re-processing them every time
              if (dep.expose) {
                self._browserifyCache[dep.file] = dep;
              }
              // new file that has not been cached before (node module or a source file)
              self._affectedFilesCache[key] = dep;
            }
          }
        });

        // no need to pack the bundle, wallaby.js serves files one by one to leverage browser caching
        self._b.pipeline.splice('pack');
      }

      // todo: handle node modules external update
      // todo: bundle node_modules into a single file

      // removing changed files tracked by wallaby.js from browserify cache
      if (!self._initRequired) {
        _.each(affectedFiles, file => {
          delete self._browserifyCache[file.fullPath];
        });
      }

      return new Promise(
        function (resolve, reject) {
          try {
            // incremental bundling
            self._b.bundle()
              .on('data', () => {
              })
              .on('error', err => reject(err))
              .on('end', () => resolve());
          } catch (err) {
            reject(err);
          }
        })
        .then(function () {
          var createFilePromises = [];

          // test loader for wallaby.js
          // works exactly as browserify bundle loading, but with separate files as opposed to a single bundle file
          if (self._initRequired) {
            self._initRequired = false;

            createFilePromises.push(wallaby.createFile({
              order: -1,  // need to be the first file to load
              path: 'wallabify.js',
              content: Wallabify._getLoaderContent()
            }));
          }

          // handling changed files tracked by wallaby.js
          _.each(affectedFiles, function (file) {
            var cached = self._browserifyCache[file.fullPath];
            if (cached) {
              var code = cached.source;
              var sourceMap;
              var sourceMapConverter = convert.fromSource(code);
              if (sourceMapConverter) {
                sourceMap = sourceMapConverter.toJSON();
                code = convert.removeComments(code);
              }

              // cloning an original file and browserify-ing it
              createFilePromises.push(wallaby.createFile({
                // adding the suffix to store browserified file along with the original copies
                path: file.path + '.bro' + path.extname(file.path),
                original: file,
                content: Wallabify._wallabifyFile(file.fullPath, code, cached.deps),
                sourceMap: sourceMap
              }));
              delete self._affectedFilesCache[file.fullPath];
            }
          });

          // handling externally added and not tracked files (such as node modules and external files)
          try {
            _.each(self._affectedFilesCache, function (file) {
              if (!file.expose && !~file.id.indexOf(wallaby.nodeModulesDir)) {
                throw new Error('File ' + file.id + ' is neither a node module nor an external dependency.');
              }
              createFilePromises.push(wallaby.createFile({
                path: file.expose
                  ? path.join('browserify_external', file.id, 'external' +  + path.extname(file.id))
                  : path.join('browserify_node_modules', path.relative(wallaby.nodeModulesDir, file.id)),
                content: Wallabify._wallabifyFile(file.id, file.source, file.deps)
              }));
            });
          }
          catch (e) {
            return Promise.reject(e);
          }

          // resetting till next incremental bundle run
          self._affectedFilesCache = {};

          logger.debug('Emitting %s files', createFilePromises.length);

          return Promise.all(createFilePromises);
        });
    }
  }

  _createBrowserify(mandatoryOpts) {
    var paths = mandatoryOpts.paths.concat(this._opts.paths || []);
    var mergedOpts = _.extend(this._opts, mandatoryOpts);
    mergedOpts.paths = paths;

    var instance = this._browserify(mergedOpts);
    if (this._initializer && _.isFunction(this._initializer)) {
      return this._initializer(instance) || instance;
    }

    return instance;
  }

  static _wallabifyFile(id, content, deps) {
    return 'window.__moduleBundler.cache["' + id + '"] = [function(require, module, exports) {'
      + content + '\n}, ' + JSON.stringify(deps) + '];';
  }

  static _getLoaderContent() {
    return 'window.__moduleBundler = {};'
      + 'window.__moduleBundler.cache = {};'
      + 'window.__moduleBundler.loadTests = function () {'
        // browser pack prelude
      + '(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module \'"+o+"\'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})'
        // passing accumulated files and entry points (browserified tests for the current sandbox)
      + '(window.__moduleBundler.cache, {}, (function(){ var testIds = []; for(var i = 0, len = wallaby.loadedTests.length; i < len; i++) { var test = wallaby.loadedTests[i]; if (test.substr(-7) === ".bro.js") testIds.push(wallaby.baseDir + test.substr(0, test.length - 7)); } return testIds; })()); };'
  }

  _patchModuleDependenciesModule() {
    var wallabify = this;
    // patching module dependencies to use wallaby cache
    try {
      require('browserify/node_modules/module-deps').prototype.readFile = function (file, id) {
        var self = this;
        var tr = through();
        if (this.cache && this.cache[file]) {
          tr.push(this.cache[file].source);
          tr.push(null);
          return tr;
        }

        // wallaby.js may already have the file cached (if not, it will just read it from disk)
        if (wallabify._allTrackedFiles && wallabify._allTrackedFiles[file]) {
          wallabify._allTrackedFiles[file].getContent().then(function (source) {
            tr.push(source);
            tr.push(null);
          });
          return tr;
        }

        var rs = fs.createReadStream(file);
        rs.on('error', function (err) {
          self.emit('error', err)
        });
        this.emit('file', file, id);
        return rs;
      };
    }
    catch (e) {
      // not critical
      console.warn('Failed to patch `module-deps` module, wallaby.js file cache will not be used.'
      + '\nIt\'s not a critical issue, however tests will run faster when wallaby.js file cache is used.');
    }
  }
}

module.exports = function (opts, initializer) {
  return new Wallabify(opts, initializer).createPostprocessor();
};<commit_msg>Browser caching for node modules<commit_after>'use strict';

var path = require('path');
var fs = require('graceful-fs');
var _ = require('lodash');
var through = require('through2');
var convert = require('convert-source-map');

class Wallabify {

  constructor(opts, initializer) {
    this._patchModuleDependenciesModule();

    this._opts = opts || {};
    this._initializer = initializer;

    this._b = null;
    this._browserifyCache = {};
    this._affectedFilesCache = {};
    this._initRequired = false;
    this._allTrackedFiles = {};
  }

  createPostprocessor() {
    var self = this;
    try {
      this._browserify = require('browserify');
    }
    catch (e) {
      console.error('Browserify node module is not found, missing `npm install browserify --save-dev`?');
      return;
    }

    // wallaby.js postprocessor for browserify
    // The postprocessor creates and reuses browserify instance.
    // It splices browserify pipeline so that file concatenation doesn't happen.
    // Instead, the postprocessor creates new files and lets wallaby.js to serve them to browser as requested.
    // This allows to leverage file-based browser caching as opposed to always reload a full bundle.
    // When separate files load, they only add a function with the file body to the cache object.
    // Actual loading happens when window.__moduleBundler.loadTests is called (from bootstrap function).

    return wallaby => {
      var logger = wallaby.logger;
      var affectedFiles = wallaby.affectedFiles;
      if (!self._b || wallaby.anyFilesAdded || wallaby.anyFilesDeleted) {

        if (!self._b) {
          logger.debug('New browserify instance created');
        }
        else {
          logger.debug('Browserify instance re-created because some tracked files were added or deleted');
        }

        self._initRequired = true;
        self._affectedFilesCache = {};
        self._allTrackedFiles = _.reduce(wallaby.allFiles, function (memo, file) {
          memo[file.fullPath] = file;
          return memo;
        }, {});
        affectedFiles = wallaby.allFiles;

        self._b = self._createBrowserify({
          entries: _.map(wallaby.allTestFiles, testFile => testFile.fullPath),
          paths: wallaby.nodeModulesDir ? [wallaby.nodeModulesDir] : [],
          cache: {}, packageCache: {}, fullPaths: true
        });

        self._browserifyCache = self._b._options.cache;

        self._b.on('dep', function (dep) {
          if (typeof dep.id === 'string') {
            var key = dep.id;
            if (!self._browserifyCache[key]) {
              self._browserifyCache[key] = dep;
              // external files are cached by file name as well to avoid re-processing them every time
              if (dep.expose) {
                self._browserifyCache[dep.file] = dep;
              }
              // new file that has not been cached before (node module or a source file)
              self._affectedFilesCache[key] = dep;
            }
          }
        });

        // no need to pack the bundle, wallaby.js serves files one by one to leverage browser caching
        self._b.pipeline.splice('pack');
      }

      // todo: handle node modules external update
      // todo: bundle node_modules into a single file

      // removing changed files tracked by wallaby.js from browserify cache
      if (!self._initRequired) {
        _.each(affectedFiles, file => {
          delete self._browserifyCache[file.fullPath];
        });
      }

      return new Promise(
        function (resolve, reject) {
          try {
            // incremental bundling
            self._b.bundle()
              .on('data', () => {
              })
              .on('error', err => reject(err))
              .on('end', () => resolve());
          } catch (err) {
            reject(err);
          }
        })
        .then(function () {
          var createFilePromises = [];

          // test loader for wallaby.js
          // works exactly as browserify bundle loading, but with separate files as opposed to a single bundle file
          if (self._initRequired) {
            self._initRequired = false;

            createFilePromises.push(wallaby.createFile({
              order: -1,  // need to be the first file to load
              path: 'wallabify.js',
              content: Wallabify._getLoaderContent()
            }));
          }

          // handling changed files tracked by wallaby.js
          _.each(affectedFiles, function (file) {
            var cached = self._browserifyCache[file.fullPath];
            if (cached) {
              var code = cached.source;
              var sourceMap;
              var sourceMapConverter = convert.fromSource(code);
              if (sourceMapConverter) {
                sourceMap = sourceMapConverter.toJSON();
                code = convert.removeComments(code);
              }

              // cloning an original file and browserify-ing it
              createFilePromises.push(wallaby.createFile({
                // adding the suffix to store browserified file along with the original copies
                path: file.path + '.bro' + path.extname(file.path),
                original: file,
                content: Wallabify._wallabifyFile(file.fullPath, code, cached.deps),
                sourceMap: sourceMap
              }));
              delete self._affectedFilesCache[file.fullPath];
            }
          });

          // handling externally added and not tracked files (such as node modules and external files)
          try {
            _.each(self._affectedFilesCache, function (file) {
              if (!file.expose && !~file.id.indexOf(wallaby.nodeModulesDir)) {
                throw new Error('File ' + file.id + ' is neither a node module nor an external dependency.');
              }
              createFilePromises.push(wallaby.createFile({
                path: file.expose
                  ? path.join('browserify_external', file.id, 'external' +  + path.extname(file.id))
                  : path.join('browserify_node_modules', path.relative(wallaby.nodeModulesDir, file.id)),
                content: Wallabify._wallabifyFile(file.id, file.source, file.deps),
                ts: 1   // constant timestamp to cache forever (until wallaby restarts)
              }));
            });
          }
          catch (e) {
            return Promise.reject(e);
          }

          // resetting till next incremental bundle run
          self._affectedFilesCache = {};

          logger.debug('Emitting %s files', createFilePromises.length);

          return Promise.all(createFilePromises);
        });
    }
  }

  _createBrowserify(mandatoryOpts) {
    var paths = mandatoryOpts.paths.concat(this._opts.paths || []);
    var mergedOpts = _.extend(this._opts, mandatoryOpts);
    mergedOpts.paths = paths;

    var instance = this._browserify(mergedOpts);
    if (this._initializer && _.isFunction(this._initializer)) {
      return this._initializer(instance) || instance;
    }

    return instance;
  }

  static _wallabifyFile(id, content, deps) {
    return 'window.__moduleBundler.cache["' + id + '"] = [function(require, module, exports) {'
      + content + '\n}, ' + JSON.stringify(deps) + '];';
  }

  static _getLoaderContent() {
    return 'window.__moduleBundler = {};'
      + 'window.__moduleBundler.cache = {};'
      + 'window.__moduleBundler.loadTests = function () {'
        // browser pack prelude
      + '(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module \'"+o+"\'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})'
        // passing accumulated files and entry points (browserified tests for the current sandbox)
      + '(window.__moduleBundler.cache, {}, (function(){ var testIds = []; for(var i = 0, len = wallaby.loadedTests.length; i < len; i++) { var test = wallaby.loadedTests[i]; if (test.substr(-7) === ".bro.js") testIds.push(wallaby.baseDir + test.substr(0, test.length - 7)); } return testIds; })()); };'
  }

  _patchModuleDependenciesModule() {
    var wallabify = this;
    // patching module dependencies to use wallaby cache
    try {
      require('browserify/node_modules/module-deps').prototype.readFile = function (file, id) {
        var self = this;
        var tr = through();
        if (this.cache && this.cache[file]) {
          tr.push(this.cache[file].source);
          tr.push(null);
          return tr;
        }

        // wallaby.js may already have the file cached (if not, it will just read it from disk)
        if (wallabify._allTrackedFiles && wallabify._allTrackedFiles[file]) {
          wallabify._allTrackedFiles[file].getContent().then(function (source) {
            tr.push(source);
            tr.push(null);
          });
          return tr;
        }

        var rs = fs.createReadStream(file);
        rs.on('error', function (err) {
          self.emit('error', err)
        });
        this.emit('file', file, id);
        return rs;
      };
    }
    catch (e) {
      // not critical
      console.warn('Failed to patch `module-deps` module, wallaby.js file cache will not be used.'
      + '\nIt\'s not a critical issue, however tests will run faster when wallaby.js file cache is used.');
    }
  }
}

module.exports = function (opts, initializer) {
  return new Wallabify(opts, initializer).createPostprocessor();
};<|endoftext|>


<commit_before>
var app = require('express')();
var http = require('http').Server(app);
var socketio = require('socket.io')(http);

var twitter = require('twitter');
var mongodb = require('mongodb');
var shortid = require('shortid');

var config = require('./config');

var t = new twitter({
  consumer_key: config.twitter_consumer_key,
  consumer_secret: config.twitter_consumer_secret,
  access_token_key: config.twitter_access_token_key,
  access_token_secret: config.twitter_access_token_secret
});

mongodb.MongoClient.connect('mongodb://' + config.dbhost + ':' + config.dbport + '/' + config.dbname, function(err, database) {
  var coll = database.collection('tweet');
  coll.ensureIndex('timestamp_ms', function(err, i) {

    app.get('/', function(req, res) {
      res.sendfile('index.html');
    });

    app.get('/api/tweet', function(req, res) {
      var timestamp_ms = req.query.timestamp_ms || new Date().getTime();
      var limit = req.query.limit || 10;
      var skip = req.query.skip || 0;
      coll.find({timestamp_ms: {'$lt': ''+timestamp_ms}}, {limit:limit,skip:skip,sort:{'timestamp_ms':-1}}).toArray(function(err, data)
      {
        if (err != null)
        {
          return res.status(400).send(e);
        }
        return res.json(data);
      });
    });

    app.get('/api/geotweet', function(req, res) {
      var timestamp_ms = req.query.timestamp_ms || new Date().getTime();
      var limit = req.query.limit || 10;
      var skip = req.query.skip || 0;
      coll.find({'$and': [{timestamp_ms: {'$lt': ''+timestamp_ms}}, {'$or': [{place: {'$ne': null}}, {coordinages: {'$ne': null}}]}]}, {limit:limit,skip:skip,sort:{'timestamp_ms':-1}}).toArray(function(err, data)
      {
        if (err != null)
        {
          return res.status(400).send(err);
        }
        return res.json(data);
      });
    });

    socketio.on('connection', function(socket) {
      console.log('a user connected');
    });

    http.listen(config.webui_port, function() {
      console.log('listening on *:' + config.webui_port);
    });
    t.stream('statuses/filter', {'track': config.track_word}, function(stream) {
      stream.on('data', function (data) {
        data['_id'] = shortid.generate();
        coll.save(data);
        socketio.emit('tweet', data);
      });
    });
  });
});
<commit_msg>fix type<commit_after>
var app = require('express')();
var http = require('http').Server(app);
var socketio = require('socket.io')(http);

var twitter = require('twitter');
var mongodb = require('mongodb');
var shortid = require('shortid');

var config = require('./config');

var t = new twitter({
  consumer_key: config.twitter_consumer_key,
  consumer_secret: config.twitter_consumer_secret,
  access_token_key: config.twitter_access_token_key,
  access_token_secret: config.twitter_access_token_secret
});

mongodb.MongoClient.connect('mongodb://' + config.dbhost + ':' + config.dbport + '/' + config.dbname, function(err, database) {
  var coll = database.collection('tweet');
  coll.ensureIndex('timestamp_ms', function(err, i) {

    app.get('/', function(req, res) {
      res.sendfile('index.html');
    });

    app.get('/api/tweet', function(req, res) {
      var timestamp_ms = req.query.timestamp_ms || new Date().getTime();
      var limit = req.query.limit || 10;
      var skip = req.query.skip || 0;
      coll.find({timestamp_ms: {'$lt': ''+timestamp_ms}}, {limit:limit,skip:skip,sort:{'timestamp_ms':-1}}).toArray(function(err, data)
      {
        if (err != null)
        {
          return res.status(400).send(e);
        }
        return res.json(data);
      });
    });

    app.get('/api/geotweet', function(req, res) {
      var timestamp_ms = req.query.timestamp_ms || new Date().getTime();
      var limit = req.query.limit || 10;
      var skip = req.query.skip || 0;
      coll.find({'$and': [{timestamp_ms: {'$lt': ''+timestamp_ms}}, {'$or': [{place: {'$ne': null}}, {coordinates: {'$ne': null}}]}]}, {limit:limit,skip:skip,sort:{'timestamp_ms':-1}}).toArray(function(err, data)
      {
        if (err != null)
        {
          return res.status(400).send(err);
        }
        return res.json(data);
      });
    });

    socketio.on('connection', function(socket) {
      console.log('a user connected');
    });

    http.listen(config.webui_port, function() {
      console.log('listening on *:' + config.webui_port);
    });
    t.stream('statuses/filter', {'track': config.track_word}, function(stream) {
      stream.on('data', function (data) {
        data['_id'] = shortid.generate();
        coll.save(data);
        socketio.emit('tweet', data);
      });
    });
  });
});
<|endoftext|>


<commit_before>/*!The MIT License (MIT)
 *
 * Copyright (c) 2014 Petka Antonov
 *
 * With parts by 2009-2014 Kris Kowal under the terms of the MIT
 * license found at http://github.com/kriskowal/q/raw/master/LICENSE
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:

 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

 /* jshint node:true,browser:true,newcap:false */
 'use strict';

var Promise = require("bluebird/js/release/promise")();
var scheduler = require("bluebird/js/release/schedule");
var THIS = {};
var INSTANCE = {};

var aliasMap = {
    thenReturn: "thenResolve",
    thenThrow: "thenReject",
    caught: "fail",
    lastly: "fin",
    call: "send mcall invoke".split(" ")
};

var staticAliasMap = {
    reject: "reject rejected".split(" "),
    resolve: "resolve resolved fulfill fulfilled".split(" "),
    is: "isPromise",
    race: "race",
    async: "coroutine",
    spawn: "spawn",
    delay: "delay",

    timeout: INSTANCE,
    join: INSTANCE,
    spread: INSTANCE,
    tap: INSTANCE,
    thenReject: INSTANCE,
    thenResolve: INSTANCE,
    isPending: INSTANCE,
    isFulfilled: INSTANCE,
    isRejected: INSTANCE,
    get: INSTANCE,
    set: INSTANCE,
    del: INSTANCE,
    'delete': INSTANCE,
    'try': INSTANCE,
    keys: INSTANCE,
    allResolved: INSTANCE,
    allSettled: INSTANCE,
    fail: INSTANCE,
    "catch": INSTANCE,
    fin: INSTANCE,
    "finally": INSTANCE,
    done: INSTANCE,
    nodeify: INSTANCE,
    nfapply: INSTANCE,
    nfcall: INSTANCE,
    nfbind: INSTANCE,
    npost: INSTANCE,
    nsend: INSTANCE,
    ninvoke: INSTANCE,
    nbind: INSTANCE,
    nmcall: INSTANCE,
    fapply: INSTANCE,
    fcall: INSTANCE,
    fbind: INSTANCE,
    denodeify: INSTANCE,
    nmapply: INSTANCE,
    mapply: INSTANCE,
    post: INSTANCE,
    send: INSTANCE,
    mcall: INSTANCE,
    invoke: INSTANCE
};

function Q(value) {
    return Promise.resolve(value);
}

Q.all = Promise.all;

Q.Promise = function(resolver) {
    var ret = Q.defer();
    try {
        resolver(ret.resolve, ret.reject, ret.notify);
    } catch (e) {
        ret.reject(e);
    }
    return ret.promise;
};
Q.promise = Q.Promise;
Q.isPromiseAlike = function(value) {
    if (value instanceof Promise) return true;
    // If it was a thenable it will always pending
    // If it was a value it will always be fulfilled synchronously
    return Promise.resolve(value).isPending();
};
var map = Promise.map;
var resolve = Promise.resolve;
Q.promised = function(func) {
    return function() {
        var args = [].slice.call(arguments);
        args.unshift(this);
        return map(args, resolve).then(function(args) {
            return func.apply(args.shift(), args);
        });
    };
};

Q.when = function(a, b, c, d) {
    return Q(a).then(b, c, d);
};

Q.nearer = function(value) {
    if (value instanceof Promise) {
        var inspected = value.inspect();
        if (inspected.state === "fulfilled") {
            return inspected.value;
        }
    }
    return value;
};
Q.passByCopy = function(arg) {return arg;};

Q.defer = function() {
    var ret = {};
    var promise = new Promise(function(resolve, reject) {
        ret.resolve = ret.fulfill = resolve;
        ret.reject = reject;
    });
    ret.promise = promise;
    ret.notify = bind(promise._progress, promise);
    ret.makeNodeResolver = function() {
        return function(err, result) {
            if (err) return ret.reject(err);
            if (arguments.length > 2) return ret.resolve([].slice.call(arguments, 1));
            return ret.resolve(result);
        };
    };
    return ret;
};
Q.deferred = Q.pending = Q.defer;

Q.getBluebirdPromise = function() {
	return Promise;
};

var settle = Promise.settle;
var map = Promise.map;

Promise.prototype.valueOf = Promise.prototype.value;

Promise.prototype.allSettled = function() {
    return map(settle(this), bluebirdInspectionToQInspection);
};

Promise.prototype.allResolved = function() {
    return map(settle(this), function(i) {
        if (i.isFulfilled()) return Q(i.value());
        if (i.isRejected()) return Q.reject(i.reason());
    });
};

Promise.prototype.join = function (that) {
    return Q([this, that]).spread(function (x, y) {
        if (x === y) {
            // TODO: "===" should be Object.is or equiv
            return x;
        } else {
            throw new Error("Can't join: not the same: " + x + " " + y);
        }
    });
};

Promise.prototype.fbind = function() {
    var args = [].slice.call(arguments);
    var promise = this;
    return function() {
        var cargs = args.concat([].slice.call(arguments));
        var self = this;
        return promise.then(function(fn) {
            return fn.apply(self, cargs);
        });
    };
};

Promise.prototype.fapply = function(args) {
    return this.then(function(f) {
        return f.apply(undefined, args);
    });
};

Promise.prototype["try"] = Promise.prototype.fcall = function() {
    return this.fapply.call(this, [].slice.call(arguments));
};

Promise.prototype.nfapply = function(args) {
    return this.then(function(nodeFn) {
        return doNode(nodeFn, undefined, args);
    });
};

Promise.prototype.nfcall = function() {
    return this.nfapply.call(this, [].slice.call(arguments));
};

Promise.prototype.nfbind = Promise.prototype.denodeify = function() {
    var nodeFn = this;
    var args = [].slice.call(arguments);
    return function() {
        var self = this;
        var cargs = args.concat([].slice.call(arguments));
        return nodeFn.then(function(nodeFn) {
            return doNode(nodeFn, self, cargs);
        });
    };
};

Promise.prototype.nbind = function(ctx) {
    var nodeFn = this;
    var args = [].slice.call(arguments, 1);
    return function() {
        var cargs = args.concat([].slice.call(arguments));
        return nodeFn.then(function(nodeFn) {
            return doNode(nodeFn, ctx, cargs);
        });
    };
};

Promise.prototype.npost = Promise.prototype.nmapply = function(name, args) {
    return this.then(function(object) {
        return doNode(object[name], object, args);
    });
};

Promise.prototype.ninvoke = Promise.prototype.nsend =
Promise.prototype.nmcall = function(name) {
    var args = [].slice.call(arguments, 1);
    return this.then(function(object) {
        return doNode(object[name], object, args);
    });
};

Promise.prototype.mapply = Promise.prototype.post = function(methodName, args) {
    if (!methodName) return this.fapply(args);
    args.unshift(methodName);
    return this.invoke.apply(this, args);
};

var nodeify = Promise.prototype.nodeify;
Promise.prototype.nodeify = function(callback) {
    if (typeof callback === "function") {
        nodeify.call(this, callback);
        return;
    }
    return this;
};

Promise.prototype.inspect = function() {
    if (this.isPending()) return {state: "pending"};
    else if(this.isFulfilled()) return {state: "fulfilled", value: this.value()};
    else return {state: "rejected", reason: this.reason()};
};

Promise.prototype.passByCopy = function() {
    return this;
};

Promise.prototype.set = function(key, val) {
    return this.then(function(object) {
        object[key] = val;
    });
};

Promise.prototype["delete"] = Promise.prototype.del = function(key) {
    return this.then(function(object) {
        delete object[key];
    });
};

Promise.prototype.keys = function() {
    return this.then(function(o) {
        return Object.keys(o);
    });
};

Promise.prototype.race = function () {
    return this.then(Q.race);
};

var caught = Promise.prototype.caught;
var timeout = Promise.prototype.timeout;
Promise.prototype.timeout = function(time, customErr) {
    var result = timeout.apply(this, arguments);
    return caught.call(result, Promise.TimeoutError, function(e) {
        e.code = "ETIMEDOUT";
        if (customErr instanceof Error) {
            throw customErr;
        }
        throw e;
    });
};

Promise.prototype.done = function (fulfilled, rejected, progress) {
    var onUnhandledError = function (error) {
        // forward to a future turn so that ``when``
        // does not catch it and turn it into a rejection.
        var onerror = Q.onerror;
        var sheduled = scheduler(function () {
            promise._attachExtraTrace(error);
            if (onerror) {
                onerror(error);
            } else {
                throw error;
            }
        });
        if (scheduler.isStatic === true && typeof sheduled === "function") {
            sheduled();
    	}
    };

    // Avoid unnecessary `nextTick`ing via an unnecessary `when`.
    var promise = fulfilled || rejected || progress ?
        this.then(fulfilled, rejected, progress) :
        this;

    if (typeof process === "object" && process && process.domain) {
        onUnhandledError = process.domain.bind(onUnhandledError);
    }

    promise.then(void 0, onUnhandledError);
};

var defaultScheduler = scheduler;
Object.defineProperty(Q, "nextTick", {
    get: function() {
        return scheduler;
    },

    set: function(val) {
        if (typeof val === "function") {
            scheduler = val;
            Promise.setScheduler(val);
        } else {
            scheduler = defaultScheduler;
            Promise.setScheduler(defaultScheduler);
        }
    }
});

Object.defineProperty(Q, "longStackSupport", {
    set: function(val) {
        if (val) {
            Promise.longStackTraces();
        }
    },
    get: function() {
        return Promise.haveLongStackTraces();
    }
});

var unhandledReasons = [];
var unhandledRejections = [];
var unhandledReasonsDisplayed = false;
var trackUnhandledRejections = true;
function displayUnhandledReasons() {
    if (
        !unhandledReasonsDisplayed &&
        typeof window !== "undefined" &&
        window.console
    ) {
        console.warn("[bluebird-Q] Unhandled rejection reasons (should be empty):");
        unhandledReasons.forEach(function(reason) {
            console.warn(reason);
        });
        console.warn("[/bluebird-Q]");

    }

    unhandledReasonsDisplayed = true;
}

function logUnhandledReasons() {
    for (var i = 0; i < unhandledReasons.length; i++) {
        var reason = unhandledReasons[i];
        console.warn("Unhandled rejection reason:", reason);
    }
}

function resetUnhandledRejections() {
    unhandledReasons.length = 0;
    unhandledRejections.length = 0;
    unhandledReasonsDisplayed = false;

    if (!trackUnhandledRejections) {
        trackUnhandledRejections = true;

        // Show unhandled rejection reasons if Node exits without handling an
        // outstanding rejection.  (Note that Browserify presently produces a
        // `process` global without the `EventEmitter` `on` method.)
        if (typeof process !== "undefined" && process.on) {
            process.on("exit", logUnhandledReasons);
        }
    }
}

function trackRejection(promise, reason) {
    if (!trackUnhandledRejections) {
        return;
    }

    unhandledRejections.push(promise);
    if (reason && typeof reason.stack !== "undefined") {
        unhandledReasons.push(reason.stack);
    } else {
        unhandledReasons.push("(no stack) " + reason);
    }
    displayUnhandledReasons();
}

function untrackRejection(promise) {
    if (!trackUnhandledRejections) {
        return;
    }

    var at = unhandledRejections.indexOf(promise);
    if (at !== -1) {
        unhandledRejections.splice(at, 1);
        unhandledReasons.splice(at, 1);
    }
}

Q.resetUnhandledRejections = resetUnhandledRejections;

Q.getUnhandledReasons = function () {
    // Make a copy so that consumers can't interfere with our internal state.
    return unhandledReasons.slice();
};

Q.stopUnhandledRejectionTracking = function () {
    resetUnhandledRejections();
    if (typeof process !== "undefined" && process.on) {
        process.removeListener("exit", logUnhandledReasons);
    }
    trackUnhandledRejections = false;
};

resetUnhandledRejections();

Promise.onPossiblyUnhandledRejection(function(reason, promise) {
    trackRejection(promise, reason);
});
Promise.onUnhandledRejectionHandled(untrackRejection);

Object.keys(aliasMap).forEach(function(key) {
    var Qmethods = aliasMap[key];
    if (!Array.isArray(Qmethods)) Qmethods = [Qmethods];
    Qmethods.forEach(function(Qmethod) {
        Promise.prototype[Qmethod] = Promise.prototype[key];
    });
});

Object.keys(staticAliasMap).forEach(function(key) {
    var Qmethods = staticAliasMap[key];
    if (Qmethods === INSTANCE) {
        if (typeof Promise.prototype[key] !== "function")
            throw new Error("unimplemented Promise.prototype." + key);
        Q[key] = function(promise) {
            var instance = Q(promise);
            return instance[key].apply(instance, [].slice.call(arguments, 1));
        };
    } else {
        if (!Array.isArray(Qmethods)) Qmethods = [Qmethods];
        Qmethods.forEach(function(Qmethod) {
            Q[Qmethod] = Promise[key];
        });
    }
});

if (typeof process === "object" && process && process.env && process.env.Q_DEBUG) {
    Q.longStackSupport = true;
}

function f() {}
f.prototype = Q;
f.prototype = Promise.prototype;

function doNode(fn, ctx, args) {
     /* jshint validthis:true */
    ctx = ctx === THIS ? this : ctx;
    var d = Q.defer();
    args.push(d.makeNodeResolver());
    try {
        fn.apply(ctx, args);
    } catch (e) {
        d.reject(e);
    }
    return d.promise;
}

function bind(fn, ctx) {
    return function() {
        return fn.apply(ctx, arguments);
    };
}

function bluebirdInspectionToQInspection(i) {
    if (i.isFulfilled()) {
        return {state: "fulfilled", value: i.value()};
    } else if (i.isRejected()) {
        return {state: "rejected", reason: i.reason()};
    } else {
        return {state: "pending"};
    }
}

module.exports = Q;
<commit_msg>Remove usage of deprecated methods<commit_after>/*!The MIT License (MIT)
 *
 * Copyright (c) 2014 Petka Antonov
 *
 * With parts by 2009-2014 Kris Kowal under the terms of the MIT
 * license found at http://github.com/kriskowal/q/raw/master/LICENSE
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:

 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

 /* jshint node:true,browser:true,newcap:false */
 'use strict';

var Promise = require("bluebird/js/release/promise")();
var scheduler = require("bluebird/js/release/schedule");
var THIS = {};
var INSTANCE = {};

var aliasMap = {
    thenReturn: "thenResolve",
    thenThrow: "thenReject",
    caught: "fail",
    lastly: "fin",
    call: "send mcall invoke".split(" ")
};

var staticAliasMap = {
    reject: "reject rejected".split(" "),
    resolve: "resolve resolved fulfill fulfilled".split(" "),
    is: "isPromise",
    race: "race",
    async: "coroutine",
    spawn: "spawn",
    delay: "delay",

    timeout: INSTANCE,
    join: INSTANCE,
    spread: INSTANCE,
    tap: INSTANCE,
    thenReject: INSTANCE,
    thenResolve: INSTANCE,
    isPending: INSTANCE,
    isFulfilled: INSTANCE,
    isRejected: INSTANCE,
    get: INSTANCE,
    set: INSTANCE,
    del: INSTANCE,
    'delete': INSTANCE,
    'try': INSTANCE,
    keys: INSTANCE,
    allResolved: INSTANCE,
    allSettled: INSTANCE,
    fail: INSTANCE,
    "catch": INSTANCE,
    fin: INSTANCE,
    "finally": INSTANCE,
    done: INSTANCE,
    nodeify: INSTANCE,
    nfapply: INSTANCE,
    nfcall: INSTANCE,
    nfbind: INSTANCE,
    npost: INSTANCE,
    nsend: INSTANCE,
    ninvoke: INSTANCE,
    nbind: INSTANCE,
    nmcall: INSTANCE,
    fapply: INSTANCE,
    fcall: INSTANCE,
    fbind: INSTANCE,
    denodeify: INSTANCE,
    nmapply: INSTANCE,
    mapply: INSTANCE,
    post: INSTANCE,
    send: INSTANCE,
    mcall: INSTANCE,
    invoke: INSTANCE
};

function Q(value) {
    return Promise.resolve(value);
}

Q.all = Promise.all;

Q.Promise = function(resolver) {
    var ret = Q.defer();
    try {
        resolver(ret.resolve, ret.reject, ret.notify);
    } catch (e) {
        ret.reject(e);
    }
    return ret.promise;
};
Q.promise = Q.Promise;
Q.isPromiseAlike = function(value) {
    if (value instanceof Promise) return true;
    // If it was a thenable it will always pending
    // If it was a value it will always be fulfilled synchronously
    return Promise.resolve(value).isPending();
};
var map = Promise.map;
var resolve = Promise.resolve;
Q.promised = function(func) {
    return function() {
        var args = [].slice.call(arguments);
        args.unshift(this);
        return map(args, resolve).then(function(args) {
            return func.apply(args.shift(), args);
        });
    };
};

Q.when = function(a, b, c, d) {
    return Q(a).then(b, c, d);
};

Q.nearer = function(value) {
    if (value instanceof Promise) {
        var inspected = value.inspect();
        if (inspected.state === "fulfilled") {
            return inspected.value;
        }
    }
    return value;
};
Q.passByCopy = function(arg) {return arg;};

Q.defer = function() {
    var ret = {};
    var promise = new Promise(function(resolve, reject) {
        ret.resolve = ret.fulfill = resolve;
        ret.reject = reject;
    });
    ret.promise = promise;
    ret.notify = bind(promise._progress, promise);
    ret.makeNodeResolver = function() {
        return function(err, result) {
            if (err) return ret.reject(err);
            if (arguments.length > 2) return ret.resolve([].slice.call(arguments, 1));
            return ret.resolve(result);
        };
    };
    return ret;
};
Q.deferred = Q.pending = Q.defer;

Q.getBluebirdPromise = function() {
	return Promise;
};

Promise.prototype.valueOf = Promise.prototype.value;

Promise.prototype.allSettled = function() {
    return Promise.all(this.value().map(function(promise) {
        return promise.reflect();
    })).then(function(oResult) {
        var aPromState = [];
        for (var i = 0; i < oResult.length; i++) {
            var inspection = oResult[i];
            if (inspection.isFulfilled()) {
                aPromState.push({state: "fulfilled", value: inspection.value()});
            } else if (inspection.isRejected()) {
                aPromState.push({state: "rejected", reason: inspection.reason()});
            } else {
                aPromState.push({state: "pending"});
            }
        }

        return aPromState;
    });
};

Promise.prototype.allResolved = function() {
    return Promise.all(this.value().map(function(promise) {
        return promise.reflect();
    })).then(function(oResult) {
        var aPromState = [];
        for (var i = 0; i < oResult.length; i++) {
            var inspection = oResult[i];
            if (inspection.isFulfilled()) {
                aPromState.push(Q(inspection.value()));
            } else {
                aPromState.push(Q.reject(inspection.value()));
            }
        }

        return aPromState;
    });
};

Promise.prototype.join = function (that) {
    return Q([this, that]).spread(function (x, y) {
        if (x === y) {
            // TODO: "===" should be Object.is or equiv
            return x;
        } else {
            throw new Error("Can't join: not the same: " + x + " " + y);
        }
    });
};

Promise.prototype.fbind = function() {
    var args = [].slice.call(arguments);
    var promise = this;
    return function() {
        var cargs = args.concat([].slice.call(arguments));
        var self = this;
        return promise.then(function(fn) {
            return fn.apply(self, cargs);
        });
    };
};

Promise.prototype.fapply = function(args) {
    return this.then(function(f) {
        return f.apply(undefined, args);
    });
};

Promise.prototype["try"] = Promise.prototype.fcall = function() {
    return this.fapply.call(this, [].slice.call(arguments));
};

Promise.prototype.nfapply = function(args) {
    return this.then(function(nodeFn) {
        return doNode(nodeFn, undefined, args);
    });
};

Promise.prototype.nfcall = function() {
    return this.nfapply.call(this, [].slice.call(arguments));
};

Promise.prototype.nfbind = Promise.prototype.denodeify = function() {
    var nodeFn = this;
    var args = [].slice.call(arguments);
    return function() {
        var self = this;
        var cargs = args.concat([].slice.call(arguments));
        return nodeFn.then(function(nodeFn) {
            return doNode(nodeFn, self, cargs);
        });
    };
};

Promise.prototype.nbind = function(ctx) {
    var nodeFn = this;
    var args = [].slice.call(arguments, 1);
    return function() {
        var cargs = args.concat([].slice.call(arguments));
        return nodeFn.then(function(nodeFn) {
            return doNode(nodeFn, ctx, cargs);
        });
    };
};

Promise.prototype.npost = Promise.prototype.nmapply = function(name, args) {
    return this.then(function(object) {
        return doNode(object[name], object, args);
    });
};

Promise.prototype.ninvoke = Promise.prototype.nsend =
Promise.prototype.nmcall = function(name) {
    var args = [].slice.call(arguments, 1);
    return this.then(function(object) {
        return doNode(object[name], object, args);
    });
};

Promise.prototype.mapply = Promise.prototype.post = function(methodName, args) {
    if (!methodName) return this.fapply(args);
    args.unshift(methodName);
    return this.invoke.apply(this, args);
};

var nodeify = Promise.prototype.nodeify;
Promise.prototype.nodeify = function(callback) {
    if (typeof callback === "function") {
        nodeify.call(this, callback);
        return;
    }
    return this;
};

Promise.prototype.inspect = function() {
    if (this.isPending()) return {state: "pending"};
    else if(this.isFulfilled()) return {state: "fulfilled", value: this.value()};
    else return {state: "rejected", reason: this.reason()};
};

Promise.prototype.passByCopy = function() {
    return this;
};

Promise.prototype.set = function(key, val) {
    return this.then(function(object) {
        object[key] = val;
    });
};

Promise.prototype["delete"] = Promise.prototype.del = function(key) {
    return this.then(function(object) {
        delete object[key];
    });
};

Promise.prototype.keys = function() {
    return this.then(function(o) {
        return Object.keys(o);
    });
};

Promise.prototype.race = function () {
    return this.then(Q.race);
};

var caught = Promise.prototype.caught;
var timeout = Promise.prototype.timeout;
Promise.prototype.timeout = function(time, customErr) {
    var result = timeout.apply(this, arguments);
    return caught.call(result, Promise.TimeoutError, function(e) {
        e.code = "ETIMEDOUT";
        if (customErr instanceof Error) {
            throw customErr;
        }
        throw e;
    });
};

Promise.prototype.done = function (fulfilled, rejected, progress) {
    var onUnhandledError = function (error) {
        // forward to a future turn so that ``when``
        // does not catch it and turn it into a rejection.
        var onerror = Q.onerror;
        var sheduled = scheduler(function () {
            promise._attachExtraTrace(error);
            if (onerror) {
                onerror(error);
            } else {
                throw error;
            }
        });
        if (scheduler.isStatic === true && typeof sheduled === "function") {
            sheduled();
    	}
    };

    // Avoid unnecessary `nextTick`ing via an unnecessary `when`.
    var promise = fulfilled || rejected || progress ?
        this.then(fulfilled, rejected, progress) :
        this;

    if (typeof process === "object" && process && process.domain) {
        onUnhandledError = process.domain.bind(onUnhandledError);
    }

    promise.then(void 0, onUnhandledError);
};

var defaultScheduler = scheduler;
Object.defineProperty(Q, "nextTick", {
    get: function() {
        return scheduler;
    },

    set: function(val) {
        if (typeof val === "function") {
            scheduler = val;
            Promise.setScheduler(val);
        } else {
            scheduler = defaultScheduler;
            Promise.setScheduler(defaultScheduler);
        }
    }
});

Object.defineProperty(Q, "longStackSupport", {
    set: function(val) {
        if (val) {
            Promise.longStackTraces();
        }
    },
    get: function() {
        return Promise.haveLongStackTraces();
    }
});

var unhandledReasons = [];
var unhandledRejections = [];
var unhandledReasonsDisplayed = false;
var trackUnhandledRejections = true;
function displayUnhandledReasons() {
    if (
        !unhandledReasonsDisplayed &&
        typeof window !== "undefined" &&
        window.console
    ) {
        console.warn("[bluebird-Q] Unhandled rejection reasons (should be empty):");
        unhandledReasons.forEach(function(reason) {
            console.warn(reason);
        });
        console.warn("[/bluebird-Q]");

    }

    unhandledReasonsDisplayed = true;
}

function logUnhandledReasons() {
    for (var i = 0; i < unhandledReasons.length; i++) {
        var reason = unhandledReasons[i];
        console.warn("Unhandled rejection reason:", reason);
    }
}

function resetUnhandledRejections() {
    unhandledReasons.length = 0;
    unhandledRejections.length = 0;
    unhandledReasonsDisplayed = false;

    if (!trackUnhandledRejections) {
        trackUnhandledRejections = true;

        // Show unhandled rejection reasons if Node exits without handling an
        // outstanding rejection.  (Note that Browserify presently produces a
        // `process` global without the `EventEmitter` `on` method.)
        if (typeof process !== "undefined" && process.on) {
            process.on("exit", logUnhandledReasons);
        }
    }
}

function trackRejection(promise, reason) {
    if (!trackUnhandledRejections) {
        return;
    }

    unhandledRejections.push(promise);
    if (reason && typeof reason.stack !== "undefined") {
        unhandledReasons.push(reason.stack);
    } else {
        unhandledReasons.push("(no stack) " + reason);
    }
    displayUnhandledReasons();
}

function untrackRejection(promise) {
    if (!trackUnhandledRejections) {
        return;
    }

    var at = unhandledRejections.indexOf(promise);
    if (at !== -1) {
        unhandledRejections.splice(at, 1);
        unhandledReasons.splice(at, 1);
    }
}

Q.resetUnhandledRejections = resetUnhandledRejections;

Q.getUnhandledReasons = function () {
    // Make a copy so that consumers can't interfere with our internal state.
    return unhandledReasons.slice();
};

Q.stopUnhandledRejectionTracking = function () {
    resetUnhandledRejections();
    if (typeof process !== "undefined" && process.on) {
        process.removeListener("exit", logUnhandledReasons);
    }
    trackUnhandledRejections = false;
};

resetUnhandledRejections();

Promise.onPossiblyUnhandledRejection(function(reason, promise) {
    trackRejection(promise, reason);
});
Promise.onUnhandledRejectionHandled(untrackRejection);

Object.keys(aliasMap).forEach(function(key) {
    var Qmethods = aliasMap[key];
    if (!Array.isArray(Qmethods)) Qmethods = [Qmethods];
    Qmethods.forEach(function(Qmethod) {
        Promise.prototype[Qmethod] = Promise.prototype[key];
    });
});

Object.keys(staticAliasMap).forEach(function(key) {
    var Qmethods = staticAliasMap[key];
    if (Qmethods === INSTANCE) {
        if (typeof Promise.prototype[key] !== "function")
            throw new Error("unimplemented Promise.prototype." + key);
        Q[key] = function(promise) {
            var instance = Q(promise);
            return instance[key].apply(instance, [].slice.call(arguments, 1));
        };
    } else {
        if (!Array.isArray(Qmethods)) Qmethods = [Qmethods];
        Qmethods.forEach(function(Qmethod) {
            Q[Qmethod] = Promise[key];
        });
    }
});

if (typeof process === "object" && process && process.env && process.env.Q_DEBUG) {
    Q.longStackSupport = true;
}

function f() {}
f.prototype = Q;
f.prototype = Promise.prototype;

function doNode(fn, ctx, args) {
     /* jshint validthis:true */
    ctx = ctx === THIS ? this : ctx;
    var d = Q.defer();
    args.push(d.makeNodeResolver());
    try {
        fn.apply(ctx, args);
    } catch (e) {
        d.reject(e);
    }
    return d.promise;
}

function bind(fn, ctx) {
    return function() {
        return fn.apply(ctx, arguments);
    };
}

function bluebirdInspectionToQInspection(i) {
    if (i.isFulfilled()) {
        return {state: "fulfilled", value: i.value()};
    } else if (i.isRejected()) {
        return {state: "rejected", reason: i.reason()};
    } else {
        return {state: "pending"};
    }
}

module.exports = Q;
<|endoftext|>


<commit_before>var path = require('path');
var _ = require('lodash');
var fs = require('fs');
var compileActionscript = require('compile-actionscript');
var chalk = require('chalk');
var livereload = require('livereload');
var connect = require('connect');

function fleecyServer(params) {
	params = _.merge({
		port: 3000,
		livereload: true,
		inputPath: 'test/Main.as',
		compilerOptions: {
			'swf-version' : 13,
			'use-gpu' : true,
			'output' : 'test.swf'
		}
	}, params || {});
	var statusSwfParams = _.cloneDeep(params);
	statusSwfParams.inputPath = 'test/Status.as';
	statusSwfParams.compilerOptions.output = 'Status.swf';

	if(!params.compilerOptions.output) params.compilerOptions.output = params.inputPath.replace('.as', '.swf');
	console.log('compiling', params.inputPath);
	console.log('serving on port:', params.port );

	var serveStatic = require('serve-static');
	var app = connect();
	app.use(serveStatic(__dirname + "/tmp"));

	if(params.livereload) {
		var folder_path = path.resolve(__dirname, path.dirname(params.inputPath));

		livereload_server = livereload.createServer({exts:["as"]});
		console.log('watching', folder_path);
		livereload_server.watch(folder_path);
	}

	function respond(msg) {
		msg = msg || 'hello world';
		return function(req, res) {
			console.log('requesting', req.url);
			if(req.url.indexOf('.swf') != -1) {
				console.log('compiling', req.url);
				function serveThatSwf(swfPath) {
					console.log('compile complete', swfPath);
					var stats;
					try {
						stats = fs.lstatSync(swfPath); // throws if path doesn't exist
					} catch (e) {
						res.writeHead(404, {'Content-Type': 'text/plain'});
						res.write('404 Not Found\n');
						res.end();
						return;
					}

					if (stats.isFile()) {
						res.writeHead(200, { 'Content-Type': 'application/x-shockwave-flash' });
					    var fileStream = fs.createReadStream(swfPath);
					    fileStream.pipe(res);
					}
				}

				compileActionscript(params.inputPath, params.compilerOptions, function(err) {
					if(err) {
						console.log(chalk.red('COMPILE FAILED!'));
						console.log(chalk.red(err.err));
						console.log(chalk.red(err.stderr));
						var stringContainingNewLines = err.err + '\n' + err.stdout + '\n' + err.stderr;
						// var htmlString = stringContainingNewLines.replace(/(\r\n|\n|\r)/gm, "
")
						var htmlString = encodeURI(stringContainingNewLines);
						statusSwfParams.compilerOptions.defines = {
							'STATUS::log' : htmlString.replace(',', '%%COMMA%%')
						}
						compileActionscript(statusSwfParams.inputPath, statusSwfParams.compilerOptions, function() {
							serveThatSwf(statusSwfParams.compilerOptions.output);
						});
					} else {
						serveThatSwf(params.compilerOptions.output)
					}
				});
			} else {
				res.writeHead(200, { 'Content-Type': 'text/html' });
				res.end(msg);
			}
		}
	}

	var html = '' +
	'		' +
	'			<title>Fleecy</title>' +
	'			<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />' +
	'			' +
	'			' +
	'		' +
	'	' +
	'
' +
	'			TEST' +
	'
' +
	'		' +
	'	' +
	'';
	app.use(respond(html));
	app.listen(params.port);
}

module.exports = fleecyServer;
<commit_msg>bugfix relative paths<commit_after>var path = require('path');
var _ = require('lodash');
var fs = require('fs');
var compileActionscript = require('compile-actionscript');
var chalk = require('chalk');
var livereload = require('livereload');
var connect = require('connect');

function fleecyServer(params) {
	params = _.merge({
		port: 3000,
		livereload: true,
		inputPath: 'test/Main.as',
		compilerOptions: {
			'swf-version' : 13,
			'use-gpu' : true,
			'output' : 'test.swf'
		}
	}, params || {});
	var statusSwfParams = _.cloneDeep(params);
	statusSwfParams.inputPath = 'test/Status.as';
	statusSwfParams.compilerOptions.output = 'Status.swf';

	if(!params.compilerOptions.output) params.compilerOptions.output = params.inputPath.replace('.as', '.swf');
	console.log('compiling', params.inputPath);
	console.log('serving on port:', params.port );

	var serveStatic = require('serve-static');
	var app = connect();
	app.use(serveStatic(__dirname + "/tmp"));

	if(params.livereload) {
		var folder_path = path.resolve(path.dirname(path.resolve(params.inputPath)));

		livereload_server = livereload.createServer({exts:["as"]});
		console.log('watching', folder_path);
		livereload_server.watch(folder_path);
	}

	function respond(msg) {
		msg = msg || 'hello world';
		return function(req, res) {
			console.log('requesting', req.url);
			if(req.url.indexOf('.swf') != -1) {
				console.log('compiling', req.url);
				function serveThatSwf(swfPath) {
					console.log('compile complete', swfPath);
					var stats;
					try {
						stats = fs.lstatSync(swfPath); // throws if path doesn't exist
					} catch (e) {
						res.writeHead(404, {'Content-Type': 'text/plain'});
						res.write('404 Not Found\n');
						res.end();
						return;
					}

					if (stats.isFile()) {
						res.writeHead(200, { 'Content-Type': 'application/x-shockwave-flash' });
					    var fileStream = fs.createReadStream(swfPath);
					    fileStream.pipe(res);
					}
				}

				compileActionscript(params.inputPath, params.compilerOptions, function(err) {
					if(err) {
						console.log(chalk.red('COMPILE FAILED!'));
						console.log(chalk.red(err.err));
						console.log(chalk.red(err.stderr));
						var stringContainingNewLines = err.err + '\n' + err.stdout + '\n' + err.stderr;
						// var htmlString = stringContainingNewLines.replace(/(\r\n|\n|\r)/gm, "
")
						var htmlString = encodeURI(stringContainingNewLines);
						statusSwfParams.compilerOptions.defines = {
							'STATUS::log' : htmlString.replace(',', '%%COMMA%%')
						}
						compileActionscript(statusSwfParams.inputPath, statusSwfParams.compilerOptions, function() {
							serveThatSwf(statusSwfParams.compilerOptions.output);
						});
					} else {
						serveThatSwf(params.compilerOptions.output)
					}
				});
			} else {
				res.writeHead(200, { 'Content-Type': 'text/html' });
				res.end(msg);
			}
		}
	}

	var html = '' +
	'		' +
	'			<title>Fleecy</title>' +
	'			<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />' +
	'			' +
	'			' +
	'		' +
	'	' +
	'
' +
	'			TEST' +
	'
' +
	'		' +
	'	' +
	'';
	app.use(respond(html));
	app.listen(params.port);
}

module.exports = fleecyServer;
<|endoftext|>


<commit_before>exports.Schema = require('./lib/schema').Schema;
exports.AbstractClass = require('./lib/abstract-class').AbstractClass;
exports.Validatable = require('./lib/validatable').Validatable;

exports.version = JSON.parse(require('fs').readFileSync('./package.json')).version;
<commit_msg>Safe require package.json<commit_after>exports.Schema = require('./lib/schema').Schema;
exports.AbstractClass = require('./lib/abstract-class').AbstractClass;
exports.Validatable = require('./lib/validatable').Validatable;

try {
    exports.version = require('./package.json').version;
} catch(e) {}
<|endoftext|>


<commit_before>/*!
 * strip-comments <https://github.com/jonschlinkert/strip-comments>
 *
 * Copyright (c) 2014-2016, 2018, Jon Schlinkert.
 * Released under the MIT License.
 */

'use strict';

const assign = Object.assign;
const extract = require('babel-extract-comments');

/**
 * Strip all code comments from the given `input`, including protected
 * comments that start with `!`, unless disabled by setting `options.keepProtected`
 * to true.
 *
 * ```js
 * const str = strip('const foo = "bar";// this is a comment\n /* me too *\/');
 * console.log(str);
 * // => 'const foo = "bar";'
 * ```
 * @name  strip
 * @param  {String} `input` string from which to strip comments
 * @param  {Object} `options` optional options, passed to [extract-comments][extract-comments]
 * @option {Boolean} [options] `line` if `false` strip only block comments, default `true`
 * @option {Boolean} [options] `block` if `false` strip only line comments, default `true`
 * @option {Boolean} [options] `keepProtected` Keep ignored comments (e.g. `/*!` and `//!`)
 * @option {Boolean} [options] `preserveNewlines` Preserve newlines after comments are stripped
 * @return {String} modified input
 * @api public
 */

function strip(input, options) {
  return stripComments(input, assign({ block: true, line: true }, options));
}

/**
 * Strip only block comments.
 *
 * ```js
 * const strip = require('..');
 * const str = strip.block('const foo = "bar";// this is a comment\n /* me too *\/');
 * console.log(str);
 * // => 'const foo = "bar";// this is a comment'
 * ```
 * @name  .block
 * @param  {String} `input` string from which to strip comments
 * @param  {Object} `options` pass `opts.keepProtected: true` to keep ignored comments (e.g. `/*!`)
 * @return {String} modified string
 * @api public
 */

strip.block = function(input, options) {
  return stripComments(input, assign({ block: true }, options));
};

/**
 * Strip only line comments.
 *
 * ```js
 * const str = strip.line('const foo = "bar";// this is a comment\n /* me too *\/');
 * console.log(str);
 * // => 'const foo = "bar";\n/* me too *\/'
 * ```
 * @name  .line
 * @param  {String} `input` string from which to strip comments
 * @param  {Object} `options` pass `opts.keepProtected: true` to keep ignored comments (e.g. `//!`)
 * @return {String} modified string
 * @api public
 */

strip.line = function(input, options) {
  return stripComments(input, assign({ line: true }, options));
};

/**
 * Strip the first comment from the given `input`. Or, if `opts.keepProtected` is true,
 * the first non-protected comment will be stripped.
 *
 * ```js
 * const output = strip.first(input, { keepProtected: true });
 * console.log(output);
 * // => '//! first comment\nfoo; '
 * ```
 * @name .first
 * @param {String} `input`
 * @param {Object} `options` pass `opts.keepProtected: true` to keep comments with `!`
 * @return {String}
 * @api public
 */

strip.first = function(input, options) {
  const opts = assign({ block: true, line: true, first: true }, options);
  return stripComments(input, opts);
};

/**
 * Strip comments
 */

function stripComments(input, options, tried) {
  if (typeof input !== 'string') {
    throw new TypeError('expected a string');
  }

  // strip all by default, including `ingored` comments.
  const defaults = { block: false, line: false, safe: false, first: false };
  const opts = assign({}, defaults, options);
  tried = tried || 0;

  if (typeof opts.keepProtected !== 'boolean') {
    opts.keepProtected = opts.safe;
  }

  try {
    const comments = extract(input, opts);
    let pos = { start: 0, end: 0, removed: 0 };

    for (const comment of comments) {
      if (typeof opts.filter === 'function' && opts.filter(comment, opts) === false) {
        continue;
      }

      input = remove(input, comment, opts, pos);

      if (opts.first === true && !isProtected(comment, opts)) {
        break;
      }
    }
  } catch (err) {
    if (options.verbose) {
      throw err;
    }
  }
  return input;
}

/**
 * Remove a single comment from the given string.
 */

function remove(str, comment, options, pos) {
  let nl = '';

  if (isProtected(comment, options)) {
    return str;
  }

  if (options && options.preserveNewlines) {
    nl = comment.value.replace(/[^\r\n]/g, '');
  }

  if (comment.type === 'CommentLine' && options.line === true) {
    const before = str.slice(0, comment.start - pos.removed);
    const after = str.slice(comment.end - pos.removed);
    pos.removed += comment.end - comment.start - nl.length;
    return before + nl + after;
  }

  if (comment.type === 'CommentBlock' && options.block === true) {
    const before = str.slice(0, comment.start - pos.removed);
    const after = str.slice(comment.end - pos.removed);
    pos.removed += comment.end - comment.start - nl.length;
    return before + nl + after;
  }

  return str;
}

function isProtected(comment, options) {
  return options && options.keepProtected === true && /^\*?!/.test(comment.value);
}

module.exports = strip;
<commit_msg>adds object-rest-spread plugin<commit_after>/*!
 * strip-comments <https://github.com/jonschlinkert/strip-comments>
 *
 * Copyright (c) 2014-2016, 2018, Jon Schlinkert.
 * Released under the MIT License.
 */

'use strict';

const assign = Object.assign;
const extract = require('babel-extract-comments');

/**
 * Strip all code comments from the given `input`, including protected
 * comments that start with `!`, unless disabled by setting `options.keepProtected`
 * to true.
 *
 * ```js
 * const str = strip('const foo = "bar";// this is a comment\n /* me too *\/');
 * console.log(str);
 * // => 'const foo = "bar";'
 * ```
 * @name  strip
 * @param  {String} `input` string from which to strip comments
 * @param  {Object} `options` optional options, passed to [extract-comments][extract-comments]
 * @option {Boolean} [options] `line` if `false` strip only block comments, default `true`
 * @option {Boolean} [options] `block` if `false` strip only line comments, default `true`
 * @option {Boolean} [options] `keepProtected` Keep ignored comments (e.g. `/*!` and `//!`)
 * @option {Boolean} [options] `preserveNewlines` Preserve newlines after comments are stripped
 * @return {String} modified input
 * @api public
 */

function strip(input, options) {
  return stripComments(input, assign({ block: true, line: true }, options));
}

/**
 * Strip only block comments.
 *
 * ```js
 * const strip = require('..');
 * const str = strip.block('const foo = "bar";// this is a comment\n /* me too *\/');
 * console.log(str);
 * // => 'const foo = "bar";// this is a comment'
 * ```
 * @name  .block
 * @param  {String} `input` string from which to strip comments
 * @param  {Object} `options` pass `opts.keepProtected: true` to keep ignored comments (e.g. `/*!`)
 * @return {String} modified string
 * @api public
 */

strip.block = function(input, options) {
  return stripComments(input, assign({ block: true }, options));
};

/**
 * Strip only line comments.
 *
 * ```js
 * const str = strip.line('const foo = "bar";// this is a comment\n /* me too *\/');
 * console.log(str);
 * // => 'const foo = "bar";\n/* me too *\/'
 * ```
 * @name  .line
 * @param  {String} `input` string from which to strip comments
 * @param  {Object} `options` pass `opts.keepProtected: true` to keep ignored comments (e.g. `//!`)
 * @return {String} modified string
 * @api public
 */

strip.line = function(input, options) {
  return stripComments(input, assign({ line: true }, options));
};

/**
 * Strip the first comment from the given `input`. Or, if `opts.keepProtected` is true,
 * the first non-protected comment will be stripped.
 *
 * ```js
 * const output = strip.first(input, { keepProtected: true });
 * console.log(output);
 * // => '//! first comment\nfoo; '
 * ```
 * @name .first
 * @param {String} `input`
 * @param {Object} `options` pass `opts.keepProtected: true` to keep comments with `!`
 * @return {String}
 * @api public
 */

strip.first = function(input, options) {
  const opts = assign({ block: true, line: true, first: true }, options);
  return stripComments(input, opts);
};

/**
 * Strip comments
 */

function stripComments(input, options) {
  if (typeof input !== 'string') {
    throw new TypeError('expected a string');
  }

  // strip all by default, including `ingored` comments.
  const defaults = { block: false, line: false, safe: false, first: false };
  const opts = assign({}, defaults, options);
  opts.plugins = ['objectRestSpread'];

  if (typeof opts.keepProtected !== 'boolean') {
    opts.keepProtected = opts.safe;
  }

  try {
    const comments = extract(input, opts);
    let pos = { start: 0, end: 0, removed: 0 };
    if (!comments) return input;

    for (const comment of comments) {
      if (typeof opts.filter === 'function' && opts.filter(comment, opts) === false) {
        continue;
      }

      input = remove(input, comment, opts, pos);

      if (opts.first === true && !isProtected(comment, opts)) {
        break;
      }
    }
  } catch (err) {
    if (options.silent !== true) {
      throw err;
    }
  }
  return input;
}

/**
 * Remove a single comment from the given string.
 */

function remove(str, comment, options, pos) {
  let nl = '';

  if (isProtected(comment, options)) {
    return str;
  }

  if (options && options.preserveNewlines) {
    nl = comment.value.replace(/[^\r\n]/g, '');
  }

  if (comment.type === 'CommentLine' && options.line === true) {
    const before = str.slice(0, comment.start - pos.removed);
    const after = str.slice(comment.end - pos.removed);
    pos.removed += comment.end - comment.start - nl.length;
    return before + nl + after;
  }

  if (comment.type === 'CommentBlock' && options.block === true) {
    const before = str.slice(0, comment.start - pos.removed);
    const after = str.slice(comment.end - pos.removed);
    pos.removed += comment.end - comment.start - nl.length;
    return before + nl + after;
  }

  return str;
}

function isProtected(comment, options) {
  return options && options.keepProtected === true && /^\*?!/.test(comment.value);
}

module.exports = strip;
<|endoftext|>


<commit_before>/* eslint-env node */
'use strict';
var BasePlugin = require('ember-cli-deploy-plugin');
var fbTools = require('firebase-tools');

module.exports = {
  name: 'ember-cli-deploy-firebase',

  createDeployPlugin: function(options) {
    var DeployPlugin = BasePlugin.extend({
      name: options.name,

      upload: function(context) {
        var outer = this;
        var project = context.config.firebase.appName || context.config.fireBaseAppName;
        var options = {
          project: project,
          public: context.config.build.outputPath,
          message: (context.revisionData || {}).revisionKey,
          verbose: context.ui.verbose
        };
        if (context.config.firebase.deployToken || process.env.FIREBASE_TOKEN) {
          options.token = context.config.firebase.deployToken || process.env.FIREBASE_TOKEN;
        }
        return fbTools.deploy(options).then(() => {
          outer.log('successful deploy!', {verbose: true});
        }).catch((err) => {
          // handle error
          outer.log('something bad happened oh no', { color: 'red' });
          outer.log(err, { color: 'red' });
          outer.log(err.stack, { color: 'red' });
        });
      }
    });

    return new DeployPlugin();
  }
};
<commit_msg>actually change the arrows back to functions<commit_after>/* eslint-env node */
'use strict';
var BasePlugin = require('ember-cli-deploy-plugin');
var fbTools = require('firebase-tools');

module.exports = {
  name: 'ember-cli-deploy-firebase',

  createDeployPlugin: function(options) {
    var DeployPlugin = BasePlugin.extend({
      name: options.name,

      upload: function(context) {
        var outer = this;
        var project = context.config.firebase.appName || context.config.fireBaseAppName;
        var options = {
          project: project,
          public: context.config.build.outputPath,
          message: (context.revisionData || {}).revisionKey,
          verbose: context.ui.verbose
        };
        if (context.config.firebase.deployToken || process.env.FIREBASE_TOKEN) {
          options.token = context.config.firebase.deployToken || process.env.FIREBASE_TOKEN;
        }
        return fbTools.deploy(options).then(function() {
          outer.log('successful deploy!', {verbose: true});
        }).catch(function(err) {
          // handle error
          outer.log('something bad happened oh no', { color: 'red' });
          outer.log(err, { color: 'red' });
          outer.log(err.stack, { color: 'red' });
        });
      }
    });

    return new DeployPlugin();
  }
};
<|endoftext|>