<commit_before>/*
 * grunt-component
 * https://github.com/anthonyshort/grunt-component-build
 *
 * Copyright (c) 2012 Anthony Short
 * Licensed under the MIT license.
 */

'use strict';

var Builder = require('component-builder');
var fs = require('fs');
var path = require('path');
var template = fs.readFileSync( __dirname + '/../lib/require.tmpl').toString();

module.exports = function(grunt) {

  // Please see the grunt documentation for more information regarding task and
  // helper creation: https://github.com/cowboy/grunt/blob/master/docs/toc.md

  // ==========================================================================
  // TASKS
  // ==========================================================================

  grunt.registerMultiTask('component', 'component-build for grunt.', function() {
    var opts = this.data;
    var name = opts.name || this.target;
    var output = path.resolve(this.data.output);
    var done = this.async();
    var self = this;

    // The component builder
    var builder = new Builder( path.resolve(path.dirname(this.data.config)) );

    if( opts.sourceUrls === true ) {
      builder.addSourceURLs();
    }

    // Where to output the final file
    builder.copyAssetsTo(output);

    // Ignore component parts
    if( opts.ignore ) {
      Object.keys(opts.ignore).forEach(function(n){
        var type = opts.ignore[n];
        builder.ignore(n, type);
      });
    }

    // The component config
    var config = require( path.resolve(this.data.base, 'component.json') );

    // Add in extra scripts during the build since Component makes
    // us define each and every file in our component to build it.
    config.scripts = grunt.file.expand( config.scripts || [] );
    config.templates = grunt.file.expand( config.templates || [] );

    if( config.paths ) {
      builder.addLookup(config.paths);
    }

    // Prefix urls
    if( this.data.prefix ) {
      builder.prefixUrls(this.data.prefix);
    }

    // Development mode
    if( this.data.dev ) {
      builder.development();
    }

    // Set the config on the builder. We've modified
    // the original config from the file and this will
    // override settings during the build
    builder.conf = config;

    if( opts.plugins ) {
      opts.plugins.forEach(function(name){
        var plugin = require('../plugins/' + name);
        builder.use(plugin);
      });
    }

    // Configure hook
    if( opts.configure ) {
      opts.configure.call(this, builder);
    }

    // Build the component
    builder.build(function(err, obj){

      if (err) {
        grunt.log.error( err.message );
        grunt.fatal( err.message );
      }

      // Write CSS file
      if( opts.styles !== false ) {
        var cssFile = path.join(output, name + '.css');
        grunt.file.write(cssFile, obj.css);
      }

      // Write JS file
      if( opts.scripts !== false ) {
        var jsFile = path.join(output, name + '.js');
        if( opts.standalone ) {
          obj.name = name;
          obj.config = config;
          var string = grunt.template.process(template, obj);
          grunt.file.write(jsFile, string);
        }
        else {
          grunt.file.write(jsFile, obj.require + obj.js);
        }
      }

      done();

    });
  });

};
<commit_msg>Fix the "standalone" output to pass the tests<commit_after>/*
 * grunt-component
 * https://github.com/anthonyshort/grunt-component-build
 *
 * Copyright (c) 2012 Anthony Short
 * Licensed under the MIT license.
 */

'use strict';

var Builder = require('component-builder');
var fs = require('fs');
var path = require('path');
var template = fs.readFileSync( __dirname + '/../lib/require.tmpl').toString();

module.exports = function(grunt) {

  // Please see the grunt documentation for more information regarding task and
  // helper creation: https://github.com/cowboy/grunt/blob/master/docs/toc.md

  // ==========================================================================
  // TASKS
  // ==========================================================================

  grunt.registerMultiTask('component', 'component-build for grunt.', function() {
    var opts = this.data;
    var name = opts.name || this.target;
    var output = path.resolve(this.data.output);
    var done = this.async();
    var self = this;

    // The component builder
    var builder = new Builder( path.resolve(path.dirname(this.data.config)) );

    if( opts.sourceUrls === true ) {
      builder.addSourceURLs();
    }

    // Where to output the final file
    builder.copyAssetsTo(output);

    // Ignore component parts
    if( opts.ignore ) {
      Object.keys(opts.ignore).forEach(function(n){
        var type = opts.ignore[n];
        builder.ignore(n, type);
      });
    }

    // The component config
    var config = require( path.resolve(this.data.base, 'component.json') );

    // Add in extra scripts during the build since Component makes
    // us define each and every file in our component to build it.
    config.scripts = grunt.file.expand( config.scripts || [] );
    config.templates = grunt.file.expand( config.templates || [] );

    if( config.paths ) {
      builder.addLookup(config.paths);
    }

    // Prefix urls
    if( this.data.prefix ) {
      builder.prefixUrls(this.data.prefix);
    }

    // Development mode
    if( this.data.dev ) {
      builder.development();
    }

    // Set the config on the builder. We've modified
    // the original config from the file and this will
    // override settings during the build
    builder.conf = config;

    if( opts.plugins ) {
      opts.plugins.forEach(function(name){
        var plugin = require('../plugins/' + name);
        builder.use(plugin);
      });
    }

    // Configure hook
    if( opts.configure ) {
      opts.configure.call(this, builder);
    }

    // Build the component
    builder.build(function(err, obj){

      if (err) {
        grunt.log.error( err.message );
        grunt.fatal( err.message );
      }

      // Write CSS file
      if( opts.styles !== false ) {
        var cssFile = path.join(output, name + '.css');
        grunt.file.write(cssFile, obj.css);
      }

      // Write JS file
      if( opts.scripts !== false ) {
        var jsFile = path.join(output, name + '.js');
        if( opts.standalone ) {
          // Defines the name of the global variable (window[opts.name]).
          // By default we use the name defined in the component.json,
          // else we use the `standalone` option defined in the Gruntfile.
          obj.name = (typeof opts.standalone === 'string') ? opts.standalone : config.name;
          obj.config = config;
          var string = grunt.template.process(template, { data: obj });
          grunt.file.write(jsFile, string);
        }
        else {
          grunt.file.write(jsFile, obj.require + obj.js);
        }
      }

      done();

    });
  });

};
<|endoftext|>


<commit_before>'use strict';
// to allow mongodb host and port injection thanks
// to the EZMASTER_MONGODB_HOST_PORT environment parameter
// (docker uses it)
var mongoHostPort = process.env.EZMASTER_MONGODB_HOST_PORT ?
                    process.env.EZMASTER_MONGODB_HOST_PORT :
                    'localhost:27017';

var publicDomain = process.env.EZMASTER_PUBLIC_DOMAIN ?
                  process.env.EZMASTER_PUBLIC_DOMAIN :
                  null;

var publicIP = process.env.EZMASTER_PUBLIC_IP ?
                    process.env.EZMASTER_PUBLIC_IP :
                    '127.0.0.1';

module.exports = {
  connectionURI: 'mongodb://' + mongoHostPort + '/ezmaster',
  collectionName: 'data',
  publicDomain: publicDomain,
  publicIP: publicIP,
  browserifyModules : [
    'vue'
    , 'vue-resource'
    , 'components/addInstance'
    , 'components/table'
    , 'vue-validator'
    , 'heartbeats'
  ],
  rootURL : '/',
  routes: [
    'route.js',
    'status.js'
  ],
  middlewares: {
    '/*': 'reverseproxy.js'
  },

  filters: ['jbj-parse']
};

module.exports.package = require('./package.json');
<commit_msg>Add 127.0.0.1 default if Public IP not specified.<commit_after>'use strict';
// to allow mongodb host and port injection thanks
// to the EZMASTER_MONGODB_HOST_PORT environment parameter
// (docker uses it)
var mongoHostPort = process.env.EZMASTER_MONGODB_HOST_PORT ?
                    process.env.EZMASTER_MONGODB_HOST_PORT :
                    'localhost:27017';

var publicDomain = process.env.EZMASTER_PUBLIC_DOMAIN ?
                  process.env.EZMASTER_PUBLIC_DOMAIN :
                  null;
/*
var publicIP = process.env.EZMASTER_PUBLIC_IP ?
                    process.env.EZMASTER_PUBLIC_IP :
                    '127.0.0.1';
*/
var publicIP = process.env.EZMASTER_PUBLIC_IP || '127.0.0.1';

module.exports = {
  connectionURI: 'mongodb://' + mongoHostPort + '/ezmaster',
  collectionName: 'data',
  publicDomain: publicDomain,
  publicIP: publicIP,
  browserifyModules : [
    'vue'
    , 'vue-resource'
    , 'components/addInstance'
    , 'components/table'
    , 'vue-validator'
    , 'heartbeats'
  ],
  rootURL : '/',
  routes: [
    'route.js',
    'status.js'
  ],
  middlewares: {
    '/*': 'reverseproxy.js'
  },

  filters: ['jbj-parse']
};

module.exports.package = require('./package.json');
<|endoftext|>


<commit_before>var gulp = require('gulp');
var runSequence = require('run-sequence');
var changed = require('gulp-changed');
var plumber = require('gulp-plumber');
var to5 = require('gulp-6to5');
var shell = require('gulp-shell');
var sourcemaps = require('gulp-sourcemaps');
var paths = require('../paths');
var compilerOptions = require('../6to5-options');
var assign = Object.assign || require('object.assign');

gulp.task('build-system', function () {
  return gulp.src(paths.source)
    .pipe(plumber())
    .pipe(changed(paths.output, {extension: '.js'}))
    .pipe(sourcemaps.init())
    .pipe(to5(assign({}, compilerOptions, {modules:'system'})))
    .pipe(sourcemaps.write({includeContent: false, sourceRoot: '/src'}))
    .pipe(gulp.dest(paths.output));
});

gulp.task('build-html', function () {
  return gulp.src(paths.html)
    .pipe(changed(paths.output, {extension: '.html'}))
    .pipe(gulp.dest(paths.output));
});

gulp.task('build-bundle', ['build-system'], shell.task('jspm bundle ' +
  paths.output + 'main ' +
  paths.output + 'bundled.js ' +
  ' --inject --skip-source-maps')
);

gulp.task('build-export', function() {
  var sources = [
    'README.md',
    'index.html',
    'config.js',
    'css/*',
    'jspm_packages/*',
    'jspm_packages/npm/todomvc-app-css@*/index.css',
    paths.output + '*.html',
    paths.output + 'bundled.js'
  ];

  return gulp.src(sources, {base: "."})
    .pipe(gulp.dest(paths.export));
});

gulp.task('build', function(callback) {
  return runSequence(
    'clean',
    ['build-system', 'build-html'],
    'build-bundle',
    'build-export',
    callback
  );
});
<commit_msg>added todomvc-common assets to be included in 'build-export' gulp task (fixed #7)<commit_after>var gulp = require('gulp');
var runSequence = require('run-sequence');
var changed = require('gulp-changed');
var plumber = require('gulp-plumber');
var to5 = require('gulp-6to5');
var shell = require('gulp-shell');
var sourcemaps = require('gulp-sourcemaps');
var paths = require('../paths');
var compilerOptions = require('../6to5-options');
var assign = Object.assign || require('object.assign');

gulp.task('build-system', function () {
  return gulp.src(paths.source)
    .pipe(plumber())
    .pipe(changed(paths.output, {extension: '.js'}))
    .pipe(sourcemaps.init())
    .pipe(to5(assign({}, compilerOptions, {modules:'system'})))
    .pipe(sourcemaps.write({includeContent: false, sourceRoot: '/src'}))
    .pipe(gulp.dest(paths.output));
});

gulp.task('build-html', function () {
  return gulp.src(paths.html)
    .pipe(changed(paths.output, {extension: '.html'}))
    .pipe(gulp.dest(paths.output));
});

gulp.task('build-bundle', ['build-system'], shell.task('jspm bundle ' +
  paths.output + 'main ' +
  paths.output + 'bundled.js ' +
  ' --inject --skip-source-maps')
);

gulp.task('build-export', function() {
  var sources = [
    'README.md',
    'index.html',
    'config.js',
    'css/*',
    'jspm_packages/*',
    'jspm_packages/npm/todomvc-app-css@*/index.css',
    'jspm_packages/npm/todomvc-common@*/base.*',
    paths.output + '*.html',
    paths.output + 'bundled.js'
  ];

  return gulp.src(sources, {base: "."})
    .pipe(gulp.dest(paths.export));
});

gulp.task('build', function(callback) {
  return runSequence(
    'clean',
    ['build-system', 'build-html'],
    'build-bundle',
    'build-export',
    callback
  );
});
<|endoftext|>


<commit_before>/* global cloak */

var form = document.querySelector('#input-form');
var input = document.querySelector('#input');
var messages = document.querySelector('#messages');
var counter = document.querySelector('#counter');

cloak.configure({
  messages: {
    chat: function(msg) {
      var message = document.createElement('div');
      message.innerText = msg;
      message.className = 'msg';
      messages.appendChild(message);
      messages.scrollTop = messages.scrollHeight;
    },
    userCount: function(count) {
      counter.innerText = count;
    }
  },
});

cloak.run('http://localhost:8090');

form.addEventListener('submit', function(e) {
  e.preventDefault();
  var msg = input.value;
  if (msg.length < 1) {
    return;
  }
  cloak.message('chat', msg);
  input.value = '';
});
<commit_msg>Switch .innerText DOM output to .textContent<commit_after>/* global cloak */

var form = document.querySelector('#input-form');
var input = document.querySelector('#input');
var messages = document.querySelector('#messages');
var counter = document.querySelector('#counter');

cloak.configure({
  messages: {
    chat: function(msg) {
      var message = document.createElement('div');
      message.textContent = msg;
      message.className = 'msg';
      messages.appendChild(message);
      messages.scrollTop = messages.scrollHeight;
    },
    userCount: function(count) {
      counter.textContent = count;
    }
  },
});

cloak.run('http://localhost:8090');

form.addEventListener('submit', function(e) {
  e.preventDefault();
  var msg = input.value;
  if (msg.length < 1) {
    return;
  }
  cloak.message('chat', msg);
  input.value = '';
});
<|endoftext|>


<commit_before>const Renderer = require('./Renderer.js');
const { defaults } = require('./defaults.js');
const { inline } = require('./rules.js');
const {
  findClosingBracket,
  escape
} = require('./helpers.js');

/**
 * Inline Lexer & Compiler
 */
module.exports = class InlineLexer {
  constructor(links, options) {
    this.options = options || defaults;
    this.links = links;
    this.rules = inline.normal;
    this.options.renderer = this.options.renderer || new Renderer();
    this.renderer = this.options.renderer;
    this.renderer.options = this.options;

    if (!this.links) {
      throw new Error('Tokens array requires a `links` property.');
    }

    if (this.options.pedantic) {
      this.rules = inline.pedantic;
    } else if (this.options.gfm) {
      if (this.options.breaks) {
        this.rules = inline.breaks;
      } else {
        this.rules = inline.gfm;
      }
    }
  }

  /**
   * Expose Inline Rules
   */
  static get rules() {
    return inline;
  }

  /**
   * Static Lexing/Compiling Method
   */
  static output(src, links, options) {
    const inline = new InlineLexer(links, options);
    return inline.output(src);
  }

  /**
   * Lexing/Compiling
   */
  output(src) {
    let out = '',
      link,
      text,
      href,
      title,
      cap,
      prevCapZero;

    while (src) {
      // escape
      if (cap = this.rules.escape.exec(src)) {
        src = src.substring(cap[0].length);
        out += escape(cap[1]);
        continue;
      }

      // tag
      if (cap = this.rules.tag.exec(src)) {
        if (!this.inLink && /^<a /i.test(cap[0])) {
          this.inLink = true;
        } else if (this.inLink && /^<\/a>/i.test(cap[0])) {
          this.inLink = false;
        }
        if (!this.inRawBlock && /^<(pre|code|kbd|script)(\s|>)/i.test(cap[0])) {
          this.inRawBlock = true;
        } else if (this.inRawBlock && /^<\/(pre|code|kbd|script)(\s|>)/i.test(cap[0])) {
          this.inRawBlock = false;
        }

        src = src.substring(cap[0].length);
        out += this.options.sanitize
          ? this.options.sanitizer
            ? this.options.sanitizer(cap[0])
            : escape(cap[0])
          : cap[0];
        continue;
      }

      // link
      if (cap = this.rules.link.exec(src)) {
        const lastParenIndex = findClosingBracket(cap[2], '()');
        if (lastParenIndex > -1) {
          const start = cap[0].indexOf('!') === 0 ? 5 : 4;
          const linkLen = start + cap[1].length + lastParenIndex;
          cap[2] = cap[2].substring(0, lastParenIndex);
          cap[0] = cap[0].substring(0, linkLen).trim();
          cap[3] = '';
        }
        src = src.substring(cap[0].length);
        this.inLink = true;
        href = cap[2];
        if (this.options.pedantic) {
          link = /^([^'"]*[^\s])\s+(['"])(.*)\2/.exec(href);

          if (link) {
            href = link[1];
            title = link[3];
          } else {
            title = '';
          }
        } else {
          title = cap[3] ? cap[3].slice(1, -1) : '';
        }
        href = href.trim().replace(/^<([\s\S]*)>$/, '$1');
        out += this.outputLink(cap, {
          href: InlineLexer.escapes(href),
          title: InlineLexer.escapes(title)
        });
        this.inLink = false;
        continue;
      }

      // reflink, nolink
      if ((cap = this.rules.reflink.exec(src))
          || (cap = this.rules.nolink.exec(src))) {
        src = src.substring(cap[0].length);
        link = (cap[2] || cap[1]).replace(/\s+/g, ' ');
        link = this.links[link.toLowerCase()];
        if (!link || !link.href) {
          out += cap[0].charAt(0);
          src = cap[0].substring(1) + src;
          continue;
        }
        this.inLink = true;
        out += this.outputLink(cap, link);
        this.inLink = false;
        continue;
      }

      // strong
      if (cap = this.rules.strong.exec(src)) {
        src = src.substring(cap[0].length);
        out += this.renderer.strong(this.output(cap[4] || cap[3] || cap[2] || cap[1]));
        continue;
      }

      // em
      if (cap = this.rules.em.exec(src)) {
        src = src.substring(cap[0].length);
        out += this.renderer.em(this.output(cap[6] || cap[5] || cap[4] || cap[3] || cap[2] || cap[1]));
        continue;
      }

      // code
      if (cap = this.rules.code.exec(src)) {
        src = src.substring(cap[0].length);
        out += this.renderer.codespan(escape(cap[2].trim(), true));
        continue;
      }

      // br
      if (cap = this.rules.br.exec(src)) {
        src = src.substring(cap[0].length);
        out += this.renderer.br();
        continue;
      }

      // del (gfm)
      if (cap = this.rules.del.exec(src)) {
        src = src.substring(cap[0].length);
        out += this.renderer.del(this.output(cap[1]));
        continue;
      }

      // autolink
      if (cap = this.rules.autolink.exec(src)) {
        src = src.substring(cap[0].length);
        if (cap[2] === '@') {
          text = escape(this.mangle(cap[1]));
          href = 'mailto:' + text;
        } else {
          text = escape(cap[1]);
          href = text;
        }
        out += this.renderer.link(href, null, text);
        continue;
      }

      // url (gfm)
      if (!this.inLink && (cap = this.rules.url.exec(src))) {
        if (cap[2] === '@') {
          text = escape(cap[0]);
          href = 'mailto:' + text;
        } else {
          // do extended autolink path validation
          do {
            prevCapZero = cap[0];
            cap[0] = this.rules._backpedal.exec(cap[0])[0];
          } while (prevCapZero !== cap[0]);
          text = escape(cap[0]);
          if (cap[1] === 'www.') {
            href = 'http://' + text;
          } else {
            href = text;
          }
        }
        src = src.substring(cap[0].length);
        out += this.renderer.link(href, null, text);
        continue;
      }

      // text
      if (cap = this.rules.text.exec(src)) {
        src = src.substring(cap[0].length);
        if (this.inRawBlock) {
          out += this.renderer.text(this.options.sanitize ? (this.options.sanitizer ? this.options.sanitizer(cap[0]) : escape(cap[0])) : cap[0]);
        } else {
          out += this.renderer.text(escape(this.smartypants(cap[0])));
        }
        continue;
      }

      if (src) {
        throw new Error('Infinite loop on byte: ' + src.charCodeAt(0));
      }
    }

    return out;
  }

  static escapes(text) {
    return text ? text.replace(InlineLexer.rules._escapes, '$1') : text;
  }

  /**
   * Compile Link
   */
  outputLink(cap, link) {
    const href = link.href,
      title = link.title ? escape(link.title) : null;

    return cap[0].charAt(0) !== '!'
      ? this.renderer.link(href, title, this.output(cap[1]))
      : this.renderer.image(href, title, escape(cap[1]));
  }

  /**
   * Smartypants Transformations
   */
  smartypants(text) {
    if (!this.options.smartypants) return text;
    return text
      // em-dashes
      .replace(/---/g, '\u2014')
      // en-dashes
      .replace(/--/g, '\u2013')
      // opening singles
      .replace(/(^|[-\u2014/(\[{"\s])'/g, '$1\u2018')
      // closing singles & apostrophes
      .replace(/'/g, '\u2019')
      // opening doubles
      .replace(/(^|[-\u2014/(\[{\u2018\s])"/g, '$1\u201c')
      // closing doubles
      .replace(/"/g, '\u201d')
      // ellipses
      .replace(/\.{3}/g, '\u2026');
  }

  /**
   * Mangle Links
   */
  mangle(text) {
    if (!this.options.mangle) return text;
    const l = text.length;
    let out = '',
      i = 0,
      ch;

    for (; i < l; i++) {
      ch = text.charCodeAt(i);
      if (Math.random() > 0.5) {
        ch = 'x' + ch.toString(16);
      }
      out += '&#' + ch + ';';
    }

    return out;
  }
};
<commit_msg>send inline html to renderer<commit_after>const Renderer = require('./Renderer.js');
const { defaults } = require('./defaults.js');
const { inline } = require('./rules.js');
const {
  findClosingBracket,
  escape
} = require('./helpers.js');

/**
 * Inline Lexer & Compiler
 */
module.exports = class InlineLexer {
  constructor(links, options) {
    this.options = options || defaults;
    this.links = links;
    this.rules = inline.normal;
    this.options.renderer = this.options.renderer || new Renderer();
    this.renderer = this.options.renderer;
    this.renderer.options = this.options;

    if (!this.links) {
      throw new Error('Tokens array requires a `links` property.');
    }

    if (this.options.pedantic) {
      this.rules = inline.pedantic;
    } else if (this.options.gfm) {
      if (this.options.breaks) {
        this.rules = inline.breaks;
      } else {
        this.rules = inline.gfm;
      }
    }
  }

  /**
   * Expose Inline Rules
   */
  static get rules() {
    return inline;
  }

  /**
   * Static Lexing/Compiling Method
   */
  static output(src, links, options) {
    const inline = new InlineLexer(links, options);
    return inline.output(src);
  }

  /**
   * Lexing/Compiling
   */
  output(src) {
    let out = '',
      link,
      text,
      href,
      title,
      cap,
      prevCapZero;

    while (src) {
      // escape
      if (cap = this.rules.escape.exec(src)) {
        src = src.substring(cap[0].length);
        out += escape(cap[1]);
        continue;
      }

      // tag
      if (cap = this.rules.tag.exec(src)) {
        if (!this.inLink && /^<a /i.test(cap[0])) {
          this.inLink = true;
        } else if (this.inLink && /^<\/a>/i.test(cap[0])) {
          this.inLink = false;
        }
        if (!this.inRawBlock && /^<(pre|code|kbd|script)(\s|>)/i.test(cap[0])) {
          this.inRawBlock = true;
        } else if (this.inRawBlock && /^<\/(pre|code|kbd|script)(\s|>)/i.test(cap[0])) {
          this.inRawBlock = false;
        }

        src = src.substring(cap[0].length);
        out += this.renderer.html(this.options.sanitize
          ? (this.options.sanitizer
            ? this.options.sanitizer(cap[0])
            : escape(cap[0]))
          : cap[0]);
        continue;
      }

      // link
      if (cap = this.rules.link.exec(src)) {
        const lastParenIndex = findClosingBracket(cap[2], '()');
        if (lastParenIndex > -1) {
          const start = cap[0].indexOf('!') === 0 ? 5 : 4;
          const linkLen = start + cap[1].length + lastParenIndex;
          cap[2] = cap[2].substring(0, lastParenIndex);
          cap[0] = cap[0].substring(0, linkLen).trim();
          cap[3] = '';
        }
        src = src.substring(cap[0].length);
        this.inLink = true;
        href = cap[2];
        if (this.options.pedantic) {
          link = /^([^'"]*[^\s])\s+(['"])(.*)\2/.exec(href);

          if (link) {
            href = link[1];
            title = link[3];
          } else {
            title = '';
          }
        } else {
          title = cap[3] ? cap[3].slice(1, -1) : '';
        }
        href = href.trim().replace(/^<([\s\S]*)>$/, '$1');
        out += this.outputLink(cap, {
          href: InlineLexer.escapes(href),
          title: InlineLexer.escapes(title)
        });
        this.inLink = false;
        continue;
      }

      // reflink, nolink
      if ((cap = this.rules.reflink.exec(src))
          || (cap = this.rules.nolink.exec(src))) {
        src = src.substring(cap[0].length);
        link = (cap[2] || cap[1]).replace(/\s+/g, ' ');
        link = this.links[link.toLowerCase()];
        if (!link || !link.href) {
          out += cap[0].charAt(0);
          src = cap[0].substring(1) + src;
          continue;
        }
        this.inLink = true;
        out += this.outputLink(cap, link);
        this.inLink = false;
        continue;
      }

      // strong
      if (cap = this.rules.strong.exec(src)) {
        src = src.substring(cap[0].length);
        out += this.renderer.strong(this.output(cap[4] || cap[3] || cap[2] || cap[1]));
        continue;
      }

      // em
      if (cap = this.rules.em.exec(src)) {
        src = src.substring(cap[0].length);
        out += this.renderer.em(this.output(cap[6] || cap[5] || cap[4] || cap[3] || cap[2] || cap[1]));
        continue;
      }

      // code
      if (cap = this.rules.code.exec(src)) {
        src = src.substring(cap[0].length);
        out += this.renderer.codespan(escape(cap[2].trim(), true));
        continue;
      }

      // br
      if (cap = this.rules.br.exec(src)) {
        src = src.substring(cap[0].length);
        out += this.renderer.br();
        continue;
      }

      // del (gfm)
      if (cap = this.rules.del.exec(src)) {
        src = src.substring(cap[0].length);
        out += this.renderer.del(this.output(cap[1]));
        continue;
      }

      // autolink
      if (cap = this.rules.autolink.exec(src)) {
        src = src.substring(cap[0].length);
        if (cap[2] === '@') {
          text = escape(this.mangle(cap[1]));
          href = 'mailto:' + text;
        } else {
          text = escape(cap[1]);
          href = text;
        }
        out += this.renderer.link(href, null, text);
        continue;
      }

      // url (gfm)
      if (!this.inLink && (cap = this.rules.url.exec(src))) {
        if (cap[2] === '@') {
          text = escape(cap[0]);
          href = 'mailto:' + text;
        } else {
          // do extended autolink path validation
          do {
            prevCapZero = cap[0];
            cap[0] = this.rules._backpedal.exec(cap[0])[0];
          } while (prevCapZero !== cap[0]);
          text = escape(cap[0]);
          if (cap[1] === 'www.') {
            href = 'http://' + text;
          } else {
            href = text;
          }
        }
        src = src.substring(cap[0].length);
        out += this.renderer.link(href, null, text);
        continue;
      }

      // text
      if (cap = this.rules.text.exec(src)) {
        src = src.substring(cap[0].length);
        if (this.inRawBlock) {
          out += this.renderer.text(this.options.sanitize ? (this.options.sanitizer ? this.options.sanitizer(cap[0]) : escape(cap[0])) : cap[0]);
        } else {
          out += this.renderer.text(escape(this.smartypants(cap[0])));
        }
        continue;
      }

      if (src) {
        throw new Error('Infinite loop on byte: ' + src.charCodeAt(0));
      }
    }

    return out;
  }

  static escapes(text) {
    return text ? text.replace(InlineLexer.rules._escapes, '$1') : text;
  }

  /**
   * Compile Link
   */
  outputLink(cap, link) {
    const href = link.href,
      title = link.title ? escape(link.title) : null;

    return cap[0].charAt(0) !== '!'
      ? this.renderer.link(href, title, this.output(cap[1]))
      : this.renderer.image(href, title, escape(cap[1]));
  }

  /**
   * Smartypants Transformations
   */
  smartypants(text) {
    if (!this.options.smartypants) return text;
    return text
      // em-dashes
      .replace(/---/g, '\u2014')
      // en-dashes
      .replace(/--/g, '\u2013')
      // opening singles
      .replace(/(^|[-\u2014/(\[{"\s])'/g, '$1\u2018')
      // closing singles & apostrophes
      .replace(/'/g, '\u2019')
      // opening doubles
      .replace(/(^|[-\u2014/(\[{\u2018\s])"/g, '$1\u201c')
      // closing doubles
      .replace(/"/g, '\u201d')
      // ellipses
      .replace(/\.{3}/g, '\u2026');
  }

  /**
   * Mangle Links
   */
  mangle(text) {
    if (!this.options.mangle) return text;
    const l = text.length;
    let out = '',
      i = 0,
      ch;

    for (; i < l; i++) {
      ch = text.charCodeAt(i);
      if (Math.random() > 0.5) {
        ch = 'x' + ch.toString(16);
      }
      out += '&#' + ch + ';';
    }

    return out;
  }
};
<|endoftext|>


<commit_before>import _ from 'lodash'

import {authExpired} from 'shared/actions/auth'
import {publishNotification as notify} from 'shared/actions/notifications'

import {HTTP_FORBIDDEN} from 'shared/constants'

const actionsAllowedDuringBlackout = [
  '@@',
  'AUTH_',
  'ME_',
  'NOTIFICATION_',
  'ERROR_',
]
const notificationsBlackoutDuration = 5000
let allowNotifications = true // eslint-disable-line

const errorsMiddleware = store => next => action => {
  const {auth: {me}} = store.getState()

  if (action.type === 'ERROR_THROWN') {
    const {error, error: {status, auth}, altText, alertType = 'error'} = action

    if (status === HTTP_FORBIDDEN) {
      const message = _.get(error, 'data.message', '')

      const organizationWasRemoved =
        message === `user's current organization was not found` // eslint-disable-line quotes
      const wasSessionTimeout = me !== null

      store.dispatch(authExpired(auth))

      if (
        message ===
        `This organization is private. To gain access, you must be explicitly added by an administrator.` // eslint-disable-line quotes
      ) {
        store.dispatch(notify(alertType, message))
      }

      if (organizationWasRemoved) {
        store.dispatch(
          notify(alertType, 'Your current organization was deleted.')
        )

        allowNotifications = false
        setTimeout(() => {
          allowNotifications = true
        }, notificationsBlackoutDuration)
      } else if (wasSessionTimeout) {
        store.dispatch(
          notify(
            alertType,
            'Your session has timed out. Log in again to continue.'
          )
        )

        allowNotifications = false
        setTimeout(() => {
          allowNotifications = true
        }, notificationsBlackoutDuration)
      }
    } else if (altText) {
      store.dispatch(notify(alertType, altText))
    } else {
      // TODO: actually do proper error handling
      // store.dispatch(notify(alertType, 'Cannot communicate with server.'))
    }
  }

  // If auth has expired, do not execute any further actions or redux state
  // changes not related to routing and auth. This allows the error notification
  // telling the user why they've been logged out to persist in the UI. It also
  // prevents further changes to redux state by actions that may have triggered
  // AJAX requests pre-auth expiration and whose response returns post-logout
  if (
    me === null &&
    !actionsAllowedDuringBlackout.some(allowedAction =>
      action.type.includes(allowedAction)
    )
  ) {
    return
  }
  next(action)
}

export default errorsMiddleware
<commit_msg>Un-blackout LINKS_ actions from errors middleware so dispatch registers with Redux<commit_after>import _ from 'lodash'

import {authExpired} from 'shared/actions/auth'
import {publishNotification as notify} from 'shared/actions/notifications'

import {HTTP_FORBIDDEN} from 'shared/constants'

const actionsAllowedDuringBlackout = [
  '@@',
  'AUTH_',
  'ME_',
  'NOTIFICATION_',
  'ERROR_',
  'LINKS_',
]
const notificationsBlackoutDuration = 5000
let allowNotifications = true // eslint-disable-line

const errorsMiddleware = store => next => action => {
  const {auth: {me}} = store.getState()

  if (action.type === 'ERROR_THROWN') {
    const {error, error: {status, auth}, altText, alertType = 'error'} = action

    if (status === HTTP_FORBIDDEN) {
      const message = _.get(error, 'data.message', '')

      const organizationWasRemoved =
        message === `user's current organization was not found` // eslint-disable-line quotes
      const wasSessionTimeout = me !== null

      store.dispatch(authExpired(auth))

      if (
        message ===
        `This organization is private. To gain access, you must be explicitly added by an administrator.` // eslint-disable-line quotes
      ) {
        store.dispatch(notify(alertType, message))
      }

      if (organizationWasRemoved) {
        store.dispatch(
          notify(alertType, 'Your current organization was deleted.')
        )

        allowNotifications = false
        setTimeout(() => {
          allowNotifications = true
        }, notificationsBlackoutDuration)
      } else if (wasSessionTimeout) {
        store.dispatch(
          notify(
            alertType,
            'Your session has timed out. Log in again to continue.'
          )
        )

        allowNotifications = false
        setTimeout(() => {
          allowNotifications = true
        }, notificationsBlackoutDuration)
      }
    } else if (altText) {
      store.dispatch(notify(alertType, altText))
    } else {
      // TODO: actually do proper error handling
      // store.dispatch(notify(alertType, 'Cannot communicate with server.'))
    }
  }

  // If auth has expired, do not execute any further actions or redux state
  // changes not related to routing and auth. This allows the error notification
  // telling the user why they've been logged out to persist in the UI. It also
  // prevents further changes to redux state by actions that may have triggered
  // AJAX requests pre-auth expiration and whose response returns post-logout
  if (
    me === null &&
    !actionsAllowedDuringBlackout.some(allowedAction =>
      action.type.includes(allowedAction)
    )
  ) {
    return
  }
  next(action)
}

export default errorsMiddleware
<|endoftext|>


<commit_before>'use strict';

var paramOwner = {
    name        : 'owner',
    required    : true,
    type        : 'string',
    location    : 'uri',
    description : 'The owner of the repo.'
};

var paramRepo = {
    name        : 'repo',
    required    : true,
    type        : 'string',
    location    : 'uri',
    description : 'The name of the repo.'
};

var paramSha = {
    name        : 'sha',
    required    : true,
    type        : 'string',
    location    : 'uri',
    description : 'The name of the SHA.'
};

var paramMessage = {
    name        : 'message',
    required    : true,
    type        : 'string',
    location    : 'uri',
    description : 'The commit message.'
};

var paramTree = {
    name        : 'tree',
    required    : true,
    type        : 'string',
    location    : 'uri',
    description : 'The SHA of the tree object this commit points to.'
};

var paramParents = {
    name        : 'parents',
    required    : true,
    type        : 'array',
    location    : 'uri',
    description : 'The SHAs of the commits that were the parents of this commit. If omitted or empty, the commit will be written as a root commit. For a single parent, an array of one SHA should be provided; for a merge commit, an array of more than one should be provided.'
};

module.exports = {
    name     : 'Git Data Commits',
    methods : [
        {
            name     : 'Get a Commit',
            synopsis : '',
            method   : 'GET',
            uri      : '/repos/:owner/:repo/git/commits/:sha',
            oauth    : false,
            params   : [
                paramOwner,
                paramRepo,
                paramSha
            ]
        },
        {
            name     : 'Create a Commit',
            synopsis : '',
            method   : 'POST',
            uri      : '/repos/:owner/:repo/git/commits',
            oauth    : false,
            params   : [
                paramOwner,
                paramRepo,
                paramMessage,
                paramTree,
                paramParents // @TODO optional committer and author parameters are excluded for now
            ]
        }
    ]
};
<commit_msg>Refs #70 - Add optional parameters to Create Commit endpoint<commit_after>'use strict';

var paramOwner = {
    name        : 'owner',
    required    : true,
    type        : 'string',
    location    : 'uri',
    description : 'The owner of the repo.'
};

var paramRepo = {
    name        : 'repo',
    required    : true,
    type        : 'string',
    location    : 'uri',
    description : 'The name of the repo.'
};

var paramSha = {
    name        : 'sha',
    required    : true,
    type        : 'string',
    location    : 'uri',
    description : 'The name of the SHA.'
};

var paramMessage = {
    name        : 'message',
    required    : true,
    type        : 'string',
    location    : 'uri',
    description : 'The commit message.'
};

var paramTree = {
    name        : 'tree',
    required    : true,
    type        : 'string',
    location    : 'uri',
    description : 'The SHA of the tree object this commit points to.'
};

var paramParents = {
    name        : 'parents',
    required    : true,
    type        : 'array',
    location    : 'uri',
    description : 'The SHAs of the commits that were the parents of this commit. If omitted or empty, the commit will be written as a root commit. For a single parent, an array of one SHA should be provided; for a merge commit, an array of more than one should be provided.'
};

module.exports = {
    name     : 'Git Data Commits',
    methods : [
        {
            name     : 'Get a Commit',
            synopsis : '',
            method   : 'GET',
            uri      : '/repos/:owner/:repo/git/commits/:sha',
            oauth    : false,
            params   : [
                paramOwner,
                paramRepo,
                paramSha
            ]
        },
        {
            name     : 'Create a Commit',
            synopsis : '',
            method   : 'POST',
            uri      : '/repos/:owner/:repo/git/commits',
            oauth    : false,
            params   : [
                paramOwner,
                paramRepo,
                paramMessage,
                paramTree,
                paramParents,
                {
                    name         : 'author',
                    required     : false,
                    type         : 'hash',
                    location     : 'body',
                    description  : 'If the author section is omitted, it will be filled in with the authenticated user\'s information and the current date.',
                    params       : [
                        {
                            name        : 'name',
                            type        : 'string',
                            required    : false,
                            location    : 'body',
                            description : 'The name of the author (or commiter) of the commit'
                        },
                        {
                            name        : 'email',
                            type        : 'string',
                            required    : false,
                            location    : 'body',
                            description : 'The email of the author (or commiter) of the commit'
                        },
                        {
                            name        : 'date',
                            type        : 'string',
                            required    : false,
                            location    : 'body',
                            description : 'Indicates when this commit was authored (or committed). This is a timestamp in ISO 8601 format: YYYY-MM-DDTHH:MM:SSZ.'
                        }
                    ]
                },
                {
                    name         : 'committer',
                    required     : false,
                    type         : 'hash',
                    location     : 'body',
                    description  : 'The committer section is optional and will be filled with the author data if omitted.',
                    params       : [
                        {
                            name        : 'name',
                            type        : 'string',
                            required    : false,
                            location    : 'body',
                            description : 'The name of the author (or commiter) of the commit'
                        },
                        {
                            name        : 'email',
                            type        : 'string',
                            required    : false,
                            location    : 'body',
                            description : 'The email of the author (or commiter) of the commit'
                        },
                        {
                            name        : 'date',
                            type        : 'string',
                            required    : false,
                            location    : 'body',
                            description : 'Indicates when this commit was authored (or committed). This is a timestamp in ISO 8601 format: YYYY-MM-DDTHH:MM:SSZ.'
                        }
                    ]
                }
            ]
        }
    ]
};
<|endoftext|>


<commit_before>module.exports = {
  env: {
    node: true,
  },
  extends: ['airbnb-base', 'prettier'],
  plugins: ['import', 'promise'],
  rules: {
    'require-await': 'error',
    'no-use-before-define': 0,
    'no-restricted-syntax': 0,
    'no-await-in-loop': 0,
    'prefer-template': 'off',
    'promise/always-return': 'error',
    'promise/no-return-wrap': 'error',
    'promise/param-names': 'error',
    'promise/catch-or-return': 'error',
    'promise/no-native': 'off',
    'promise/no-nesting': 'warn',
    'promise/no-promise-in-callback': 'warn',
    'promise/no-callback-in-promise': 'warn',
    'promise/avoid-new': 'warn',
  },
};
<commit_msg>chore: eslint prefer-destructuring off<commit_after>module.exports = {
  env: {
    node: true,
  },
  extends: ['airbnb-base', 'prettier'],
  plugins: ['import', 'promise'],
  rules: {
    'require-await': 'error',
    'no-use-before-define': 0,
    'no-restricted-syntax': 0,
    'no-await-in-loop': 0,
    'prefer-destructuring': 'off',
    'prefer-template': 'off',
    'promise/always-return': 'error',
    'promise/no-return-wrap': 'error',
    'promise/param-names': 'error',
    'promise/catch-or-return': 'error',
    'promise/no-native': 'off',
    'promise/no-nesting': 'warn',
    'promise/no-promise-in-callback': 'warn',
    'promise/no-callback-in-promise': 'warn',
    'promise/avoid-new': 'warn',
  },
};
<|endoftext|>


<commit_before>function loadEnv(envFile) {
  require('fs').readFileSync(envFile)
    .toString()
    .split('\n')
    .forEach(function(line) {
      var segments = line.split('='),
          variable = segments[0],
          value = segments[1];

      if ( variable && value ) {
        process.env[variable] = value;
      }
    });
}

function ensureInEnv(variables) {
  variables.forEach(function(variable) {
    if ( !process.env[variable] ) {
      console.log(variable, 'is needed in .env.')
      process.exit(1);
    }
  });
}

function configureGlobalJson(grunt) {
  var targetPath = 'server/config/global.json',
      templatePath = targetPath + '.template',
      target,
      template = grunt.file.read(templatePath),
      output,
      env = process.env;

  output = grunt.template.process(template, {
    data: {
      PARSE_DEV_APP_ID:      env.PARSE_DEV_APP_ID,
      PARSE_DEV_MASTER_KEY:  env.PARSE_DEV_MASTER_KEY,
      PARSE_PROD_APP_ID:     env.PARSE_PROD_APP_ID,
      PARSE_PROD_MASTER_KEY: env.PARSE_PROD_MASTER_KEY
    }
  });

  if ( grunt.file.exists(targetPath) && output !== target ) {
    grunt.file.write(targetPath, output);
  }
}

module.exports = function(grunt) {
  grunt.registerTask('configure:development', 'Configure for the development environment.', function() {
    loadEnv('.env');

    ensureInEnv([
      'PARSE_DEV_APP_ID',
      'PARSE_DEV_JS_KEY',
      'PARSE_DEV_MASTER_KEY'
    ]);

    process.env.PARSE_APP_ID = process.env.PARSE_DEV_APP_ID;
    process.env.PARSE_JS_KEY = process.env.PARSE_DEV_JS_KEY;

    configureGlobalJson(grunt);
  });

  grunt.registerTask('configure:production', 'Configure for the production environment.', function() {
    loadEnv('.env');

    ensureInEnv([
      'PARSE_PROD_APP_ID',
      'PARSE_PROD_JS_KEY',
      'PARSE_PROD_MASTER_KEY'
    ]);

    process.env.PARSE_APP_ID = process.env.PARSE_PROD_APP_ID;
    process.env.PARSE_JS_KEY = process.env.PARSE_PROD_JS_KEY;

    configureGlobalJson(grunt);
  });
};
<commit_msg>write global.json if absent<commit_after>function loadEnv(envFile) {
  require('fs').readFileSync(envFile)
    .toString()
    .split('\n')
    .forEach(function(line) {
      var segments = line.split('='),
          variable = segments[0],
          value = segments[1];

      if ( variable && value ) {
        process.env[variable] = value;
      }
    });
}

function ensureInEnv(variables) {
  variables.forEach(function(variable) {
    if ( !process.env[variable] ) {
      console.log(variable, 'is needed in .env.')
      process.exit(1);
    }
  });
}

function configureGlobalJson(grunt) {
  var targetPath = 'server/config/global.json',
      templatePath = targetPath + '.template',
      template = grunt.file.read(templatePath),
      output,
      env = process.env;

  output = grunt.template.process(template, {
    data: {
      PARSE_DEV_APP_ID:      env.PARSE_DEV_APP_ID,
      PARSE_DEV_MASTER_KEY:  env.PARSE_DEV_MASTER_KEY,
      PARSE_PROD_APP_ID:     env.PARSE_PROD_APP_ID,
      PARSE_PROD_MASTER_KEY: env.PARSE_PROD_MASTER_KEY
    }
  });

  if ( !grunt.file.exists(targetPath) || grunt.file.read(targetPath) !== output ) {
    grunt.file.write(targetPath, output);
  }
}

module.exports = function(grunt) {
  grunt.registerTask('configure:development', 'Configure for the development environment.', function() {
    loadEnv('.env');

    ensureInEnv([
      'PARSE_DEV_APP_ID',
      'PARSE_DEV_JS_KEY',
      'PARSE_DEV_MASTER_KEY'
    ]);

    process.env.PARSE_APP_ID = process.env.PARSE_DEV_APP_ID;
    process.env.PARSE_JS_KEY = process.env.PARSE_DEV_JS_KEY;

    configureGlobalJson(grunt);
  });

  grunt.registerTask('configure:production', 'Configure for the production environment.', function() {
    loadEnv('.env');

    ensureInEnv([
      'PARSE_PROD_APP_ID',
      'PARSE_PROD_JS_KEY',
      'PARSE_PROD_MASTER_KEY'
    ]);

    process.env.PARSE_APP_ID = process.env.PARSE_PROD_APP_ID;
    process.env.PARSE_JS_KEY = process.env.PARSE_PROD_JS_KEY;

    configureGlobalJson(grunt);
  });
};
<|endoftext|>


<commit_before>var     _ = require('underscore')
,   fp    = require('functionpool')
, ffmpeg  = require('./ffmpeg/')
,   fs    = require ('fs')
,  mbc    = require('mbc-common')
, conf    = mbc.config.Caspa
, logger  = mbc.logger().addLogger('caspa_util')
;

var _exists     = fs.exists     || require('path').exists;
var _existsSync = fs.existsSync || require('path').existsSync;

var db = mbc.db();

exports.merge = function (original_filename, callback) {
    var i = 1;
    var path = require ('path');
    var source_base = path.join (conf.Dirs.uploads, '/resumable-' + original_filename + '.');

    dest = path.join (__dirname, '/public/uploads/', original_filename);
    if (_existsSync (dest))
        return;

    for (; _existsSync (source_base + i); i++)  {
        logger.debug('--->', source_base + i);

        var writter = fs.createWriteStream(dest, {'flags': 'a'});
        writter.write (fs.readFileSync (source_base +i));
    };

    var id = setInterval (function () {
        logger.info('about to call merge_finish');
        exports.merge_finish(dest, id, callback)
    }, 200);

    return dest;
}

/* all this hack, is because sometimes merge_finish was called before dest could be found
   this hopes to fix it */

exports.merge_finish = function (dest, id, callback) {
    if (! _existsSync (dest))
        return;

    clearInterval (id);

    var stat = fs.statSync (dest);
    logger.debug('all good, pasing it to parse', exports.parse_pool);
    exports.parse_pool.task(dest, stat, function (res, err) {
        if (err)
            return (logger.error('error:', err));
        logger.debug('parsed: ' + stat.name);
        exports.sc_pool.task(res, callback, function (err, res) {return res});
    });
}

/*--------------------------------------------------------------------------------------------------------------------*/
// Populate database with sample data -- Only used once: the first time the application is started.
// You'd typically not find this code in a real-life app, since the database would already exist.
var populateDB = function() {
    /*
    setInterval(function () {_addMedia ({ file: 'test' + Date.now(), _id: Date.now()})},
                4*1000);

    return;
    */
}

exports.sc_pool = new fp.Pool({size: 1}, function (media, callback, done) {
    var dest = conf.Dirs.screenshots + '/' + media._id + '.jpg';
    logger.info('starting sc', media.file);
/*
    if (_existsSync('./public/sc/' + media._id)) {
        console.log ('skipping screenshot of: ' + md5 + '(file already there).');
        return done(media);
    }
*/
    var f = new ffmpeg();
    f.run (media.file, dest, {
            size: '150x100',
            onCodecData: function(metadata) {
                logger.info('here');
                if (!callback)
                    return;

                logger.debug('metadata: ', metadata);
                metadata._id  = media._id;
                metadata.file = media.file;
                metadata.stat = media.stat;
                metadata.checksum = media._id;
                callback (metadata);
            }
    }, function(retcode, fds) {
        logger.info('here0 ');
        if (! _existsSync (dest) || retcode) {
            var error = new Error('File not created' + fds.err);
            logger.error('ERROR', error);
            return done (error);
        }

        logger.info('sc ok: ' + media._id);
        return done(media);
    });
});

exports.parse_pool = new fp.Pool({size: 1}, function (file, stat, done) {
    var spawn = require('child_process').spawn,
    md5sum    = spawn('md5sum', [file]);

    logger.info("looking at :" + file);
    md5sum.stdout.on('data', function (data) {
        var md5 = data.toString().split(' ')[0];

        db.collection('medias').findOne(md5, function(err, item) {
            if (!err && item) {
                if (stat === item.stat) return (done(item));
                else item.stat = stat;
            } else {
                item = { _id: md5 , file: file, stat: stat};
            }

            return done(item);
        });

    });
});

exports.scrape_files = function (path, callback) {
  var walk      = require('walk')
    , spawn     = require('child_process').spawn
    , bs        = 10*1024*1024
    , observe   = path;

    logger.info('launched obeserver on path: ' + observe);

    /* Ok, this a bit messy, it goes like this:
       + we get the file;
       + spawn a binary to calculate md5;
       + give that to the ffmpeg process that will:
         . extract codec data;
         . take a screenshot at 5s from start;
       + when all is done and good, we _addMedia, to get it into the medias objects;
    */

    //This listens for files found
    walk.walk(observe, { followLinks: false })
    .on('file', function (root, stat, next) {
        var file = root + '/' +  stat.name;
        next();
        if (! stat.name.match(/\.(webm|mp4|flv|avi|mpeg|mpeg2|mpg|mov|mkv|ogm|ogg)$/i)) {
            return new Error('file not a vid');
        }

        exports.parse_pool.task(file, stat, function (res, err) {
            if (err)
                return (logger.error('error:', err));
            logger.debug('parsed: ' + stat.name, res);
            exports.sc_pool.task(res, callback, function (err, res) {return res});
        });

    })
    .on('end', function () {
        logger.info("all done");
    });
}

exports.check_media = function (media, cb, arg) {
    if (!arg)
        arg = media;

    _exists (media.file, function (e) {
        if (!e)
            return;
        if (cb)
            cb(arg)
        _exists (conf.Dirs.screenshots + '/' + media._id + '.jpg', function (e) {
            if (!e)
                exports.sc_pool.task (media, null, function (res, err) {
                    if (err) {
                        logger.error(new Error("couldn't sc"));
                    }
                });
        });
    });
}
<commit_msg>Making a class with utils to reuse db connection<commit_after>var     _ = require('underscore')
,   fp    = require('functionpool')
, ffmpeg  = require('./ffmpeg/')
,   fs    = require ('fs')
,  mbc    = require('mbc-common')
, conf    = mbc.config.Caspa
, logger  = mbc.logger().addLogger('caspa_util')
, collections = mbc.config.Common.Collections
;

var _exists     = fs.exists     || require('path').exists;
var _existsSync = fs.existsSync || require('path').existsSync;

var utils = module.exports = exports = function(db) {
    this.db = db || mbc.db();
}

utils.prototype.merge = function (original_filename, callback) {
    var i = 1;
    var path = require ('path');
    var source_base = path.join (conf.Dirs.uploads, '/resumable-' + original_filename + '.');

    dest = path.join (__dirname, '/public/uploads/', original_filename);
    if (_existsSync (dest))
        return;

    for (; _existsSync (source_base + i); i++)  {
        logger.debug('--->', source_base + i);

        var writter = fs.createWriteStream(dest, {'flags': 'a'});
        writter.write (fs.readFileSync (source_base +i));
    };

    var self = this;
    var id = setInterval (function () {
        logger.info('about to call merge_finish');
        self.merge_finish(dest, id, callback)
    }, 200);

    return dest;
}

/* all this hack, is because sometimes merge_finish was called before dest could be found
   this hopes to fix it */

utils.prototype.merge_finish = function (dest, id, callback) {
    if (! _existsSync (dest))
        return;

    clearInterval (id);

    var stat = fs.statSync (dest);
    logger.debug('all good, pasing it to parse', this.parse_pool());

    var self = this;
    this.parse_pool().task(dest, stat, function (res, err) {
        if (err)
            return (logger.error('error:', err));
        logger.debug ('parsed: ' + stat.name);
        self.sc_pool.task(res, callback, function (err, res) {return res});
    });
}

/*--------------------------------------------------------------------------------------------------------------------*/
// Populate database with sample data -- Only used once: the first time the application is started.
// You'd typically not find this code in a real-life app, since the database would already exist.
utils.prototype.populateDB = function() {
    /*
    setInterval(function () {_addMedia ({ file: 'test' + Date.now(), _id: Date.now()})},
                4*1000);

    return;
    */
}

utils.prototype.sc_pool = new fp.Pool({size: 1}, function (media, callback, done) {
    var dest = conf.Dirs.screenshots + '/' + media._id + '.jpg';
    logger.info('starting sc', media.file);
/*
    if (_existsSync('./public/sc/' + media._id)) {
        logger.info ('skipping screenshot of: ' + md5 + '(file already there).');
        return done(media);
    }
*/
    var f = new ffmpeg();
    f.run (media.file, dest, {
            size: '150x100',
            onCodecData: function(metadata) {
                logger.info('here');
                if (!callback)
                    return;

                logger.debug('metadata: ', metadata);
                metadata._id  = media._id;
                metadata.file = media.file;
                metadata.stat = media.stat;
                metadata.checksum = media._id;
                callback (metadata);
            }
    }, function(retcode, fds) {
        logger.info('here0 ');
        if (! _existsSync (dest) || retcode) {
            var error = new Error('File not created' + fds.err);
            logger.error('ERROR', error);
            return done (error);
        }

        logger.info('sc ok: ' + media._id);
        return done(media);
    });
});

utils.prototype.parse_pool = function () {
    var self = this;
    return new fp.Pool({size: 1}, function (file, stat, done) {
        var spawn = require('child_process').spawn,
        md5sum    = spawn('md5sum', [file]);

        logger.info("looking at :" + file);
        md5sum.stdout.on('data', function (data) {
            var md5 = data.toString().split(' ')[0];

            self.db.collection(collections.Medias).findOne(md5, function(err, item) {
                if (!err && item) {
                    if (stat === item.stat) return (done(item));
                    else item.stat = stat;
                } else {
                    item = { _id: md5 , file: file, stat: stat};
                }

                return done(item);
            });
        });
    });
};

utils.prototype.scrape_files = function (path, callback) {
  var walk      = require('walk')
    , spawn     = require('child_process').spawn
    , bs        = 10*1024*1024
    , observe   = path;

    logger.info('launched obeserver on path: ' + observe);

    /* Ok, this a bit messy, it goes like this:
       + we get the file;
       + spawn a binary to calculate md5;
       + give that to the ffmpeg process that will:
         . extract codec data;
         . take a screenshot at 5s from start;
       + when all is done and good, we _addMedia, to get it into the medias objects;
    */

    var self = this;
    //This listens for files found
    walk.walk(observe, { followLinks: false })
    .on('file', function (root, stat, next) {
        var file = root + '/' +  stat.name;
        next();
        if (! stat.name.match(/\.(webm|mp4|flv|avi|mpeg|mpeg2|mpg|mov|mkv|ogm|ogg)$/i)) {
            var error = new Error('file not a vid');
            logger.error('ERROR', error);
            return error;
        }

        self.parse_pool().task(file, stat, function (res, err) {
            if (err)
                return (logger.error('error:', err));
            logger.debug('parsed: ' + stat.name, res);
            self.sc_pool.task(res, callback, function (err, res) {return res});
        });

    })
    .on('end', function () {
        logger.info("all done");
    });
}

utils.prototype.check_media = function (media, cb, arg) {
    var self = this;
    if (!arg)
        arg = media;

    _exists (media.file, function (e) {
        if (!e)
            return;
        if (cb)
            cb(arg)
        _exists (conf.Dirs.screenshots + '/' + media._id + '.jpg', function (e) {
            if (!e)
                self.sc_pool.task (media, null, function (res, err) {
                    if (err) {
                        logger.error(new Error("couldn't sc"));
                    }
                });
        });
    });
}
<|endoftext|>


<commit_before>(function($) {
  $(function() {
    var popOver, tab;

    $("body").prepend("
Show me what to test

");
    $("head").prepend("<link href='"+window.whereuat_stylesheet_url+"' media='screen' rel='stylesheet' type='text/css'>");

    popOver = $("#uat-bar .pop-over");
    tab     = $("#uat-bar a.go");

    tab.toggle(
      function() {
        if (popOver.find("ol").length > 0) {
          slideOut();
        } else {
          $.ajax({
            url: '/whereuat',
            success: function(response) {
              popOver.append(response);
              slideOut();
            }
          });
        }
      },
      function() {
        slideIn();
      }
    );

    function slideOut() {
      popOver.show("slide", {direction: "left"}, 500);
      tab.animate({left: '400px'}, 510);
    }

    function slideIn() {
      tab.animate({left: '0px'}, 490);
      popOver.hide("slide", {direction: "left"}, 500);
    }

    $("#uat-bar a.accept").live("click", function() {
      var acceptLink, storyName, storyId, spinner;
      acceptLink = $(this);
      storyId = acceptLink.siblings(".story-id").html();
      storyName = acceptLink.siblings("span.story");
      spinner = acceptLink.siblings(".spinner");
      spinner.fadeIn();
      $.ajax({
        method: "POST",
        url: '/whereuat/' + storyId + '/accept',
        success: function(response) {
          storyName.css("text-decoration", "line-through");
          storyName.css("background", "green");
          spinner.fadeOut();
        }
      });
      return false;
    });

    $("#uat-bar a.reject").live("click",
      function() {
        var rejectLink, reasonForm;
        rejectLink = $(this);
        reasonForm = rejectLink.siblings("form");
        if (reasonForm.is(':visible')) {
          reasonForm.slideUp();
        } else {
          reasonForm.slideDown();
        }
        return false;
      }
    );

    $("#uat-bar button.reject").live("click", function() {
      var button, reasonForm, storyName, storyId, spinner;
      button = $(this);
      button.attr("disabled", "disabled");
      reasonForm = button.parent();
      storyId = reasonForm.siblings(".story-id").html();
      storyName = reasonForm.siblings("span.story");
      spinner = reasonForm.siblings(".spinner");
      spinner.fadeIn();
      $.ajax({
        method: "POST",
        url: '/whereuat/' + storyId + '/reject',
        data: {reason: $(".reason").val()},
        success: function(response) {
          storyName.css("text-decoration", "line-through");
          storyName.css("background", "red");
          reasonForm.slideUp();
          spinner.fadeOut();
        }
      });
      return false;
    });

  });
})(jQuery);
<commit_msg>Aaaah, let the code *breathe*<commit_after>(function($) {
  $(function() {
    var popOver, tab;

    $("body").prepend("
Show me what to test

");
    $("head").prepend("<link href='"+window.whereuat_stylesheet_url+"' media='screen' rel='stylesheet' type='text/css'>");

    popOver = $("#uat-bar .pop-over");
    tab     = $("#uat-bar a.go");

    tab.toggle(
      function() {
        if (popOver.find("ol").length > 0) {
          slideOut();
        } else {
          $.ajax({
            url: '/whereuat',
            success: function(response) {
              popOver.append(response);
              slideOut();
            }
          });
        }
      },
      function() {
        slideIn();
      }
    );

    function slideOut() {
      popOver.show("slide", {direction: "left"}, 500);
      tab.animate({left: '400px'}, 510);
    }

    function slideIn() {
      tab.animate({left: '0px'}, 490);
      popOver.hide("slide", {direction: "left"}, 500);
    }

    $("#uat-bar a.accept").live("click", function() {
      var acceptLink, storyName, storyId, spinner;

      acceptLink = $(this);

      storyId    = acceptLink.siblings(".story-id").html();
      storyName  = acceptLink.siblings("span.story");
      spinner    = acceptLink.siblings(".spinner");

      spinner.fadeIn();

      $.ajax({
        method: "POST",
        url: '/whereuat/' + storyId + '/accept',
        success: function(response) {
          storyName.css("text-decoration", "line-through");
          storyName.css("background", "green");
          spinner.fadeOut();
        }
      });

      return false;
    });

    $("#uat-bar a.reject").live("click",
      function() {
        var rejectLink, reasonForm;

        rejectLink = $(this);

        reasonForm = rejectLink.siblings("form");

        if (reasonForm.is(':visible')) {
          reasonForm.slideUp();
        } else {
          reasonForm.slideDown();
        }

        return false;
      }
    );

    $("#uat-bar button.reject").live("click", function() {
      var button, reasonForm, storyName, storyId, spinner;

      button     = $(this);

      reasonForm = button.parent();
      storyId    = reasonForm.siblings(".story-id").html();
      storyName  = reasonForm.siblings("span.story");
      spinner    = reasonForm.siblings(".spinner");

      spinner.fadeIn();

      $.ajax({
        method: "POST",
        url: '/whereuat/' + storyId + '/reject',
        data: {reason: $(".reason").val()},
        success: function(response) {
          storyName.css("text-decoration", "line-through");
          storyName.css("background", "red");
          reasonForm.slideUp();
          spinner.fadeOut();
        }
      });

      return false;
    });

  });
})(jQuery);
<|endoftext|>


<commit_before>(function(root, factory) {
  if(typeof exports === 'object') {
    module.exports = factory(require('backbone'), require('underscore'), require('immutable'));
  } else if(typeof define === 'function' && define.amd) {
    define(['backbone', 'underscore', immutable], factory);
  } else {
    root.FluxCrudStore = factory(root.Backbone, root._, root.Immutable);
  }
}(this, function(Backbone, _, Immutable) {
  var require = function(name) {
    return {'backbone': Backbone, 'underscore': _, 'immutable': Immutable}[name];
  };
require=(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})({1:[function(require,module,exports){
'use strict';

var Collection = require('backbone').Collection;
var OrderedMap = require('immutable').OrderedMap;
var extend = Collection.extend;
var _ = require('underscore');

var BACKBONE_EVENTS = 'add remove change reset sync';

var CrudStore = function () {
  this.initialize();
};
CrudStore.extend = extend;
CrudStore.instance = function () {
  return new this();
};

_(CrudStore.prototype).extend({
  collection: Collection,

  initialize: function () {
    if (!this.viewModel) {
      throw 'viewModel must be set on the Store class';
    }

    if (!this.collection) {
      throw 'collection must be set on the Store class';
    }

    this._collection = new this.collection();
    this._viewModels = new OrderedMap();
    this._isFetchingAll = false;
    this._isFetching = {};
  },

  addChangeListener: function (callback) {
    if (!_(callback).isFunction()) {
      throw 'Callback param is not a function!';
    }

    this._collection.on(BACKBONE_EVENTS, callback);
  },

  removeChangeListener: function (callback) {
    if (!_(callback).isFunction()) {
      throw 'Callback param is not a function!';
    }

    this._collection.off(BACKBONE_EVENTS, callback);
  },

  getAll: function () {
    if (this._isFetchingAll) {
      return this._loadingResponse;
    }

    // First pass is to remove any unused models
    this._viewModels.keySeq().forEach(function (key) {
      if (!this._collection.get(key)) {
        this._viewModels = this._viewModels.remove(key);
      }
    }.bind(this));

    // This updates and creates models as necessary
    this._collection.each(this._cacheViewModel.bind(this));

    return this._viewModels;
  },

  get: function (id) {
    if (this._isFetchingAll || this._isFetching[id]) {
      return this._loadingResponse;
    }

    var model = this._collection.get(id);

    if (!model) {
      return null;
    } else {
      return this._cacheViewModel(model);
    }
  },

  _loadingResponse: {
    isLoading: true
  },

  _cacheViewModel: function (model) {
    var viewModel = this._viewModels.get(model.cid);
    if (viewModel) {
      _(model.toJSON()).forEach(function (value, key) {
        viewModel = viewModel.set(key, value);
      });
    } else {
      viewModel = new this.viewModel(model.toJSON());
    }

    this._viewModels = this._viewModels.set(model.cid, viewModel);
    return viewModel;
  }
});

module.exports = CrudStore;

},{"backbone":"backbone","immutable":"immutable","underscore":"underscore"}],2:[function(require,module,exports){
'use strict';

var extend = require('backbone').Collection.extend;
var _ = require('underscore');

var CrudStoreActions = function () {
};
CrudStoreActions.extend = extend;
CrudStoreActions.boundTo = function (Store) {
  var actions = new this();

  var functionAttrs = _(actions).functions();
  _(functionAttrs).each(function (attr) {
    actions[attr] = actions[attr].bind(Store);
  });

  return actions;
};

_(CrudStoreActions.prototype).extend({
  create: function (data) {
    var model = new this._collection.model(data);
    this._collection.add(model);
  },

  createAndSave: function (data) {
    this._collection.create(data);
  },

  update: function (id, data) {
    this._collection.get(id).set(data);
  },

  updateAndSave: function (id, data) {
    var model = this._collection.get(id);
    model.set(data);
    model.save();
  },

  destroy: function (id) {
    this._collection.remove(id);
  },

  destroyAndSave: function (id) {
    this._collection.get(id).destroy();
  },

  load: function (models) {
    this._collection.reset(models);
  },

  fetchAll: function () {
    if (!this._collection.url) {
      throw 'fetchAll action requires \'url\' to be set on collection class!';
    }

    this._isFetchingAll = true;
    this._collection.fetch({
      silent: true,
      success: function () {
        this._isFetchingAll = false;
      }.bind(this)
    });
  },

  fetch: function (id) {
    if (!this._collection.url) {
      throw 'fetch action requires \'url\' to be set on collection class!';
    }

    var model = this._collection.get(id);
    if (!model) {
      model = new this._collection.model({ id: id });
      this._collection.add(model);
    }

    this._isFetching[id] = true;
    model.fetch({
      success: function () {
        this._isFetching[id] = false;
      }.bind(this)
    });
  },

  save: function (id) {
    var model = this._collection.get(id);
    model.save();
  }
});

module.exports = CrudStoreActions;

},{"backbone":"backbone","underscore":"underscore"}],"flux-crud-store":[function(require,module,exports){
'use strict';

var CrudStore = require('./crud_store');
var CrudStoreActions = require('./crud_store_actions');

module.exports = { Store: CrudStore, Actions: CrudStoreActions };

},{"./crud_store":1,"./crud_store_actions":2}]},{},[]);
  return require('flux-crud-store');
}))
<commit_msg>New build<commit_after>(function(root, factory) {
  if(typeof exports === 'object') {
    module.exports = factory(require('backbone'), require('underscore'), require('immutable'));
  } else if(typeof define === 'function' && define.amd) {
    define(['backbone', 'underscore', immutable], factory);
  } else {
    root.FluxCrudStore = factory(root.Backbone, root._, root.Immutable);
  }
}(this, function(Backbone, _, Immutable) {
  var require = function(name) {
    return {'backbone': Backbone, 'underscore': _, 'immutable': Immutable}[name];
  };
require=(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})({1:[function(require,module,exports){
'use strict';

var Collection = require('backbone').Collection;
var OrderedMap = require('immutable').OrderedMap;
var extend = Collection.extend;
var _ = require('underscore');

var BACKBONE_EVENTS = 'add remove change reset sync';

var CrudStore = function () {
  this.initialize();
};
CrudStore.extend = extend;
CrudStore.instance = function () {
  return new this();
};

_(CrudStore.prototype).extend({
  collection: Collection,

  initialize: function () {
    if (!this.viewModel) {
      throw 'viewModel must be set on the Store class';
    }

    if (!this.collection) {
      throw 'collection must be set on the Store class';
    }

    this._collection = new this.collection();
    this._viewModels = new OrderedMap();
    this._isFetchingAll = false;
    this._isFetching = {};
  },

  addChangeListener: function (callback) {
    if (!_(callback).isFunction()) {
      throw 'Callback param is not a function!';
    }

    this._collection.on(BACKBONE_EVENTS, callback);
  },

  removeChangeListener: function (callback) {
    if (!_(callback).isFunction()) {
      throw 'Callback param is not a function!';
    }

    this._collection.off(BACKBONE_EVENTS, callback);
  },

  getAll: function () {
    if (this._isFetchingAll) {
      return this._loadingResponse;
    }

    // First pass is to remove any unused models
    this._viewModels.keySeq().forEach(function (key) {
      if (!this._collection.get(key)) {
        this._viewModels = this._viewModels.remove(key);
      }
    }.bind(this));

    // This updates and creates models as necessary
    this._collection.each(this._cacheViewModel.bind(this));

    return this._viewModels;
  },

  get: function (id) {
    if (this._isFetchingAll || this._isFetching[id]) {
      return this._loadingResponse;
    }

    var model = this._collection.get(id);

    if (!model) {
      return null;
    } else {
      return this._cacheViewModel(model);
    }
  },

  _loadingResponse: {
    isLoading: true
  },

  _cacheViewModel: function (model) {
    var viewModel = this._viewModels.get(model.cid);
    if (viewModel) {
      _(model.toJSON()).forEach(function (value, key) {
        viewModel = viewModel.set(key, value);
      });
    } else {
      viewModel = new this.viewModel(model.toJSON());
    }

    this._viewModels = this._viewModels.set(model.cid, viewModel);
    return viewModel;
  }
});

module.exports = CrudStore;

},{"backbone":"backbone","immutable":"immutable","underscore":"underscore"}],2:[function(require,module,exports){
'use strict';

var extend = require('backbone').Collection.extend;
var _ = require('underscore');

var CrudStoreActions = function () {
};
CrudStoreActions.extend = extend;
CrudStoreActions.boundTo = function (Store) {
  var actions = new this();

  var functionAttrs = _(actions).functions();
  _(functionAttrs).each(function (attr) {
    actions[attr] = actions[attr].bind(Store);
  });

  return actions;
};

_(CrudStoreActions.prototype).extend({
  create: function (data) {
    var model = new this._collection.model(data);
    this._collection.add(model);
  },

  createAndSave: function (data) {
    this._collection.create(data);
  },

  update: function (id, data) {
    var model = this._collection.get(id);
    if (!model) {
      throw 'Cannot call update action with id: ' + id + ' because model ' +
        'not exist.';
    }

    model.set(data);
  },

  updateAndSave: function (id, data) {
    var model = this._collection.get(id);
    if (!model) {
      throw 'Cannot call updateAndSave action with id: ' + id + ' because ' +
        'model not exist.';
    }

    model.set(data);
    model.save();
  },

  destroy: function (id) {
    var model = this._collection.get(id);
    if (!model) {
      throw 'Cannot call destroy action with id: ' + id + ' because model ' +
        'not exist.';
    }

    this._collection.remove(id);
  },

  destroyAndSave: function (id) {
    var model = this._collection.get(id);
    if (!model) {
      throw 'Cannot call destroyAndSave action with id: ' + id + ' because ' +
        'model not exist.';
    }

    model.destroy();
  },

  load: function (models) {
    this._collection.reset(models);
  },

  fetchAll: function () {
    if (!this._collection.url) {
      throw 'fetchAll action requires \'url\' to be set on collection class!';
    }

    this._isFetchingAll = true;
    this._collection.fetch({
      silent: true,
      success: function () {
        this._isFetchingAll = false;
      }.bind(this)
    });
  },

  fetch: function (id) {
    if (!this._collection.url) {
      throw 'fetch action requires \'url\' to be set on collection class!';
    }

    var model = this._collection.get(id);
    if (!model) {
      model = new this._collection.model({ id: id });
      this._collection.add(model);
    }

    this._isFetching[id] = true;
    model.fetch({
      success: function () {
        this._isFetching[id] = false;
      }.bind(this)
    });
  },

  save: function (id) {
    var model = this._collection.get(id);
    if (!model) {
      throw 'Cannot call save action with id: ' + id + ' because model ' +
        'not exist.';
    }

    model.save();
  }
});

module.exports = CrudStoreActions;

},{"backbone":"backbone","underscore":"underscore"}],"flux-crud-store":[function(require,module,exports){
'use strict';

var CrudStore = require('./crud_store');
var CrudStoreActions = require('./crud_store_actions');

module.exports = { Store: CrudStore, Actions: CrudStoreActions };

},{"./crud_store":1,"./crud_store_actions":2}]},{},[]);
  return require('flux-crud-store');
}))
<|endoftext|>


<commit_before>var httpProxy = require('../lib/http-proxy/passes/web-outgoing'),
    expect = require('expect.js');

describe('lib/http-proxy/passes/web-outgoing.js', function () {
  describe('#setRedirectHostRewrite', function () {
    beforeEach(function() {
      this.req = {
        headers: {
          host: 'ext-auto.com'
        }
      };
      this.proxyRes = {
        statusCode: 301,
        headers: {
          location: 'http://backend.com/'
        }
      };
      this.options = {
        target: 'http://backend.com'
      };
    });

    context('rewrites location host with hostRewrite', function() {
      beforeEach(function() {
        this.options.hostRewrite = 'ext-manual.com';
      });
      [201, 301, 302, 307, 308].forEach(function(code) {
        it('on ' + code, function() {
          this.proxyRes.statusCode = code;
          httpProxy.setRedirectHostRewrite(this.req, {}, this.proxyRes, this.options);
          expect(this.proxyRes.headers.location).to.eql('http://ext-manual.com/');
        });
      });

      it('not on 200', function() {
        this.proxyRes.statusCode = 200;
        httpProxy.setRedirectHostRewrite(this.req, {}, this.proxyRes, this.options);
        expect(this.proxyRes.headers.location).to.eql('http://backend.com/');
      });

      it('not when hostRewrite is unset', function() {
        delete this.options.hostRewrite;
        httpProxy.setRedirectHostRewrite(this.req, {}, this.proxyRes, this.options);
        expect(this.proxyRes.headers.location).to.eql('http://backend.com/');
      });

      it('takes precedence over autoRewrite', function() {
        this.options.autoRewrite = true;
        httpProxy.setRedirectHostRewrite(this.req, {}, this.proxyRes, this.options);
        expect(this.proxyRes.headers.location).to.eql('http://ext-manual.com/');
      });

      it('not when the redirected location does not match target host', function() {
        this.proxyRes.statusCode = 302;
        this.proxyRes.headers.location = 'http://some-other/';
        httpProxy.setRedirectHostRewrite(this.req, {}, this.proxyRes, this.options);
        expect(this.proxyRes.headers.location).to.eql('http://some-other/');
      });

      it('not when the redirected location does not match target port', function() {
        this.proxyRes.statusCode = 302;
        this.proxyRes.headers.location = 'http://backend.com:8080/';
        httpProxy.setRedirectHostRewrite(this.req, {}, this.proxyRes, this.options);
        expect(this.proxyRes.headers.location).to.eql('http://backend.com:8080/');
      });
    });

    context('rewrites location host with autoRewrite', function() {
      beforeEach(function() {
        this.options.autoRewrite = true;
      });
      [201, 301, 302, 307, 308].forEach(function(code) {
        it('on ' + code, function() {
          this.proxyRes.statusCode = code;
          httpProxy.setRedirectHostRewrite(this.req, {}, this.proxyRes, this.options);
          expect(this.proxyRes.headers.location).to.eql('http://ext-auto.com/');
        });
      });

      it('not on 200', function() {
        this.proxyRes.statusCode = 200;
        httpProxy.setRedirectHostRewrite(this.req, {}, this.proxyRes, this.options);
        expect(this.proxyRes.headers.location).to.eql('http://backend.com/');
      });

      it('not when autoRewrite is unset', function() {
        delete this.options.autoRewrite;
        httpProxy.setRedirectHostRewrite(this.req, {}, this.proxyRes, this.options);
        expect(this.proxyRes.headers.location).to.eql('http://backend.com/');
      });

      it('not when the redirected location does not match target host', function() {
        this.proxyRes.statusCode = 302;
        this.proxyRes.headers.location = 'http://some-other/';
        httpProxy.setRedirectHostRewrite(this.req, {}, this.proxyRes, this.options);
        expect(this.proxyRes.headers.location).to.eql('http://some-other/');
      });

      it('not when the redirected location does not match target port', function() {
        this.proxyRes.statusCode = 302;
        this.proxyRes.headers.location = 'http://backend.com:8080/';
        httpProxy.setRedirectHostRewrite(this.req, {}, this.proxyRes, this.options);
        expect(this.proxyRes.headers.location).to.eql('http://backend.com:8080/');
      });
    });

    context('rewrites location protocol with protocolRewrite', function() {
      beforeEach(function() {
        this.options.protocolRewrite = 'https';
      });
      [201, 301, 302, 307, 308].forEach(function(code) {
        it('on ' + code, function() {
          this.proxyRes.statusCode = code;
          httpProxy.setRedirectHostRewrite(this.req, {}, this.proxyRes, this.options);
          expect(this.proxyRes.headers.location).to.eql('https://backend.com/');
        });
      });

      it('not on 200', function() {
        this.proxyRes.statusCode = 200;
        httpProxy.setRedirectHostRewrite(this.req, {}, this.proxyRes, this.options);
        expect(this.proxyRes.headers.location).to.eql('http://backend.com/');
      });

      it('not when protocolRewrite is unset', function() {
        delete this.options.protocolRewrite;
        httpProxy.setRedirectHostRewrite(this.req, {}, this.proxyRes, this.options);
        expect(this.proxyRes.headers.location).to.eql('http://backend.com/');
      });

      it('works together with hostRewrite', function() {
        this.options.hostRewrite = 'ext-manual.com';
        httpProxy.setRedirectHostRewrite(this.req, {}, this.proxyRes, this.options);
        expect(this.proxyRes.headers.location).to.eql('https://ext-manual.com/');
      });

      it('works together with autoRewrite', function() {
        this.options.autoRewrite = true;
        httpProxy.setRedirectHostRewrite(this.req, {}, this.proxyRes, this.options);
        expect(this.proxyRes.headers.location).to.eql('https://ext-auto.com/');
      });
    });
  });

  describe('#setConnection', function () {
    it('set the right connection with 1.0 - `close`', function() {
      var proxyRes = { headers: {} };
      httpProxy.setConnection({
        httpVersion: '1.0',
        headers: {
          connection: null
        }
      }, {}, proxyRes);

      expect(proxyRes.headers.connection).to.eql('close');
    });

    it('set the right connection with 1.0 - req.connection', function() {
      var proxyRes = { headers: {} };
      httpProxy.setConnection({
        httpVersion: '1.0',
        headers: {
          connection: 'hey'
        }
      }, {}, proxyRes);

      expect(proxyRes.headers.connection).to.eql('hey');
    });

    it('set the right connection - req.connection', function() {
      var proxyRes = { headers: {} };
      httpProxy.setConnection({
        httpVersion: null,
        headers: {
          connection: 'hola'
        }
      }, {}, proxyRes);

      expect(proxyRes.headers.connection).to.eql('hola');
    });

    it('set the right connection - `keep-alive`', function() {
      var proxyRes = { headers: {} };
      httpProxy.setConnection({
        httpVersion: null,
        headers: {
          connection: null
        }
      }, {}, proxyRes);

      expect(proxyRes.headers.connection).to.eql('keep-alive');
    });

  });

  describe('#writeStatusCode', function () {
    it('should write status code', function() {
      var res = {
        writeHead: function(n) {
          expect(n).to.eql(200);
        }
      };

      httpProxy.writeStatusCode({}, res, { statusCode: 200 });
    });
  });

  describe('#writeHeaders', function() {
    beforeEach(function() {
      this.proxyRes = {
        headers: {
          hey: 'hello',
          how: 'are you?',
          'set-cookie': 'hello; domain=my.domain; path=/'
        }
      };
      this.res = {
        setHeader: function(k, v) {
          this.headers[k] = v;
        },
        headers: {}
      };
    });

    it('writes headers', function() {
      var options = {};

      httpProxy.writeHeaders({}, this.res, this.proxyRes, options);

      expect(this.res.headers.hey).to.eql('hello');
      expect(this.res.headers.how).to.eql('are you?');
    });

    it('does not rewrite domain', function() {
      var options = {};

      httpProxy.writeHeaders({}, this.res, this.proxyRes, options);

      expect(this.res.headers['set-cookie']).to.eql('hello; domain=my.domain; path=/');
    });

    it('rewrites domain', function() {
      var options = {
        cookieDomainRewrite: 'my.new.domain'
      };

      httpProxy.writeHeaders({}, this.res, this.proxyRes, options);

      expect(this.res.headers['set-cookie']).to.eql('hello; domain=my.new.domain; path=/');
    });

    it('removes domain', function() {
      var options = {
        cookieDomainRewrite: ''
      };

      httpProxy.writeHeaders({}, this.res, this.proxyRes, options);

      expect(this.res.headers['set-cookie']).to.eql('hello; path=/');
    });

    it('rewrites headers with advanced configuration', function() {
      var options = {
        cookieDomainRewrite: {
          '*': '',
          'my.old.domain': 'my.new.domain',
          'my.special.domain': 'my.special.domain'
        }
      };
      this.proxyRes.headers['set-cookie'] = [
        'hello-on-my.domain; domain=my.domain; path=/',
        'hello-on-my.old.domain; domain=my.old.domain; path=/',
        'hello-on-my.special.domain; domain=my.special.domain; path=/'
      ];

      httpProxy.writeHeaders({}, this.res, this.proxyRes, options);

      expect(this.res.headers['set-cookie'])
        .to.contain('hello-on-my.domain; path=/');
      expect(this.res.headers['set-cookie'])
        .to.contain('hello-on-my.old.domain; domain=my.new.domain; path=/');
      expect(this.res.headers['set-cookie'])
        .to.contain('hello-on-my.special.domain; domain=my.special.domain; path=/');
    });
  });

  describe('#removeChunked', function() {
    var proxyRes = {
      headers: {
        'transfer-encoding': 'hello'
      }
    };

    httpProxy.removeChunked({ httpVersion: '1.0' }, {}, proxyRes);

    expect(proxyRes.headers['transfer-encoding']).to.eql(undefined);
  });

});
<commit_msg>test case added<commit_after>var httpProxy = require('../lib/http-proxy/passes/web-outgoing'),
    expect = require('expect.js');

describe('lib/http-proxy/passes/web-outgoing.js', function () {
  describe('#setRedirectHostRewrite', function () {
    beforeEach(function() {
      this.req = {
        headers: {
          host: 'ext-auto.com'
        }
      };
      this.proxyRes = {
        statusCode: 301,
        headers: {
          location: 'http://backend.com/'
        }
      };
      this.options = {
        target: 'http://backend.com'
      };
    });

    context('rewrites location host with hostRewrite', function() {
      beforeEach(function() {
        this.options.hostRewrite = 'ext-manual.com';
      });
      [201, 301, 302, 307, 308].forEach(function(code) {
        it('on ' + code, function() {
          this.proxyRes.statusCode = code;
          httpProxy.setRedirectHostRewrite(this.req, {}, this.proxyRes, this.options);
          expect(this.proxyRes.headers.location).to.eql('http://ext-manual.com/');
        });
      });

      it('not on 200', function() {
        this.proxyRes.statusCode = 200;
        httpProxy.setRedirectHostRewrite(this.req, {}, this.proxyRes, this.options);
        expect(this.proxyRes.headers.location).to.eql('http://backend.com/');
      });

      it('not when hostRewrite is unset', function() {
        delete this.options.hostRewrite;
        httpProxy.setRedirectHostRewrite(this.req, {}, this.proxyRes, this.options);
        expect(this.proxyRes.headers.location).to.eql('http://backend.com/');
      });

      it('takes precedence over autoRewrite', function() {
        this.options.autoRewrite = true;
        httpProxy.setRedirectHostRewrite(this.req, {}, this.proxyRes, this.options);
        expect(this.proxyRes.headers.location).to.eql('http://ext-manual.com/');
      });

      it('not when the redirected location does not match target host', function() {
        this.proxyRes.statusCode = 302;
        this.proxyRes.headers.location = 'http://some-other/';
        httpProxy.setRedirectHostRewrite(this.req, {}, this.proxyRes, this.options);
        expect(this.proxyRes.headers.location).to.eql('http://some-other/');
      });

      it('not when the redirected location does not match target port', function() {
        this.proxyRes.statusCode = 302;
        this.proxyRes.headers.location = 'http://backend.com:8080/';
        httpProxy.setRedirectHostRewrite(this.req, {}, this.proxyRes, this.options);
        expect(this.proxyRes.headers.location).to.eql('http://backend.com:8080/');
      });
    });

    context('rewrites location host with autoRewrite', function() {
      beforeEach(function() {
        this.options.autoRewrite = true;
      });
      [201, 301, 302, 307, 308].forEach(function(code) {
        it('on ' + code, function() {
          this.proxyRes.statusCode = code;
          httpProxy.setRedirectHostRewrite(this.req, {}, this.proxyRes, this.options);
          expect(this.proxyRes.headers.location).to.eql('http://ext-auto.com/');
        });
      });

      it('not on 200', function() {
        this.proxyRes.statusCode = 200;
        httpProxy.setRedirectHostRewrite(this.req, {}, this.proxyRes, this.options);
        expect(this.proxyRes.headers.location).to.eql('http://backend.com/');
      });

      it('not when autoRewrite is unset', function() {
        delete this.options.autoRewrite;
        httpProxy.setRedirectHostRewrite(this.req, {}, this.proxyRes, this.options);
        expect(this.proxyRes.headers.location).to.eql('http://backend.com/');
      });

      it('not when the redirected location does not match target host', function() {
        this.proxyRes.statusCode = 302;
        this.proxyRes.headers.location = 'http://some-other/';
        httpProxy.setRedirectHostRewrite(this.req, {}, this.proxyRes, this.options);
        expect(this.proxyRes.headers.location).to.eql('http://some-other/');
      });

      it('not when the redirected location does not match target port', function() {
        this.proxyRes.statusCode = 302;
        this.proxyRes.headers.location = 'http://backend.com:8080/';
        httpProxy.setRedirectHostRewrite(this.req, {}, this.proxyRes, this.options);
        expect(this.proxyRes.headers.location).to.eql('http://backend.com:8080/');
      });
    });

    context('rewrites location protocol with protocolRewrite', function() {
      beforeEach(function() {
        this.options.protocolRewrite = 'https';
      });
      [201, 301, 302, 307, 308].forEach(function(code) {
        it('on ' + code, function() {
          this.proxyRes.statusCode = code;
          httpProxy.setRedirectHostRewrite(this.req, {}, this.proxyRes, this.options);
          expect(this.proxyRes.headers.location).to.eql('https://backend.com/');
        });
      });

      it('not on 200', function() {
        this.proxyRes.statusCode = 200;
        httpProxy.setRedirectHostRewrite(this.req, {}, this.proxyRes, this.options);
        expect(this.proxyRes.headers.location).to.eql('http://backend.com/');
      });

      it('not when protocolRewrite is unset', function() {
        delete this.options.protocolRewrite;
        httpProxy.setRedirectHostRewrite(this.req, {}, this.proxyRes, this.options);
        expect(this.proxyRes.headers.location).to.eql('http://backend.com/');
      });

      it('works together with hostRewrite', function() {
        this.options.hostRewrite = 'ext-manual.com';
        httpProxy.setRedirectHostRewrite(this.req, {}, this.proxyRes, this.options);
        expect(this.proxyRes.headers.location).to.eql('https://ext-manual.com/');
      });

      it('works together with autoRewrite', function() {
        this.options.autoRewrite = true;
        httpProxy.setRedirectHostRewrite(this.req, {}, this.proxyRes, this.options);
        expect(this.proxyRes.headers.location).to.eql('https://ext-auto.com/');
      });
    });
  });

  describe('#setConnection', function () {
    it('set the right connection with 1.0 - `close`', function() {
      var proxyRes = { headers: {} };
      httpProxy.setConnection({
        httpVersion: '1.0',
        headers: {
          connection: null
        }
      }, {}, proxyRes);

      expect(proxyRes.headers.connection).to.eql('close');
    });

    it('set the right connection with 1.0 - req.connection', function() {
      var proxyRes = { headers: {} };
      httpProxy.setConnection({
        httpVersion: '1.0',
        headers: {
          connection: 'hey'
        }
      }, {}, proxyRes);

      expect(proxyRes.headers.connection).to.eql('hey');
    });

    it('set the right connection - req.connection', function() {
      var proxyRes = { headers: {} };
      httpProxy.setConnection({
        httpVersion: null,
        headers: {
          connection: 'hola'
        }
      }, {}, proxyRes);

      expect(proxyRes.headers.connection).to.eql('hola');
    });

    it('set the right connection - `keep-alive`', function() {
      var proxyRes = { headers: {} };
      httpProxy.setConnection({
        httpVersion: null,
        headers: {
          connection: null
        }
      }, {}, proxyRes);

      expect(proxyRes.headers.connection).to.eql('keep-alive');
    });

    it('don`t set connection with 2.0 if exist', function() {
      var proxyRes = { headers: {} };
      httpProxy.setConnection({
        httpVersion: '2.0',
        headers: {
          connection: 'namstey'
        }
      }, {}, proxyRes);

      expect(proxyRes.headers.connection).to.eql(undefined);
    });

    it('don`t set connection with 2.0 if doesn`t exist', function() {
      var proxyRes = { headers: {} };
      httpProxy.setConnection({
        httpVersion: '2.0',
        headers: {}
      }, {}, proxyRes);

      expect(proxyRes.headers.connection).to.eql(undefined);
    })

  });

  describe('#writeStatusCode', function () {
    it('should write status code', function() {
      var res = {
        writeHead: function(n) {
          expect(n).to.eql(200);
        }
      };

      httpProxy.writeStatusCode({}, res, { statusCode: 200 });
    });
  });

  describe('#writeHeaders', function() {
    beforeEach(function() {
      this.proxyRes = {
        headers: {
          hey: 'hello',
          how: 'are you?',
          'set-cookie': 'hello; domain=my.domain; path=/'
        }
      };
      this.res = {
        setHeader: function(k, v) {
          this.headers[k] = v;
        },
        headers: {}
      };
    });

    it('writes headers', function() {
      var options = {};

      httpProxy.writeHeaders({}, this.res, this.proxyRes, options);

      expect(this.res.headers.hey).to.eql('hello');
      expect(this.res.headers.how).to.eql('are you?');
    });

    it('does not rewrite domain', function() {
      var options = {};

      httpProxy.writeHeaders({}, this.res, this.proxyRes, options);

      expect(this.res.headers['set-cookie']).to.eql('hello; domain=my.domain; path=/');
    });

    it('rewrites domain', function() {
      var options = {
        cookieDomainRewrite: 'my.new.domain'
      };

      httpProxy.writeHeaders({}, this.res, this.proxyRes, options);

      expect(this.res.headers['set-cookie']).to.eql('hello; domain=my.new.domain; path=/');
    });

    it('removes domain', function() {
      var options = {
        cookieDomainRewrite: ''
      };

      httpProxy.writeHeaders({}, this.res, this.proxyRes, options);

      expect(this.res.headers['set-cookie']).to.eql('hello; path=/');
    });

    it('rewrites headers with advanced configuration', function() {
      var options = {
        cookieDomainRewrite: {
          '*': '',
          'my.old.domain': 'my.new.domain',
          'my.special.domain': 'my.special.domain'
        }
      };
      this.proxyRes.headers['set-cookie'] = [
        'hello-on-my.domain; domain=my.domain; path=/',
        'hello-on-my.old.domain; domain=my.old.domain; path=/',
        'hello-on-my.special.domain; domain=my.special.domain; path=/'
      ];

      httpProxy.writeHeaders({}, this.res, this.proxyRes, options);

      expect(this.res.headers['set-cookie'])
        .to.contain('hello-on-my.domain; path=/');
      expect(this.res.headers['set-cookie'])
        .to.contain('hello-on-my.old.domain; domain=my.new.domain; path=/');
      expect(this.res.headers['set-cookie'])
        .to.contain('hello-on-my.special.domain; domain=my.special.domain; path=/');
    });
  });

  describe('#removeChunked', function() {
    var proxyRes = {
      headers: {
        'transfer-encoding': 'hello'
      }
    };

    httpProxy.removeChunked({ httpVersion: '1.0' }, {}, proxyRes);

    expect(proxyRes.headers['transfer-encoding']).to.eql(undefined);
  });

});
<|endoftext|>