<commit_before>/**
 * marked - A markdown parser
 * Copyright (c) 2011, Christopher Jeffrey. (MIT Licensed)
 */

;(function() {

/**
 * Block-Level Grammar
 */

var block = {
  newline: /^\n+/,
  block: /^ {4,}[^\n]*(?:\n {4,}[^\n]*)*/,
  hr: /^( *[\-*_]){3,}/,
  heading: /^ *(#{1,6}) *([^\n#]*) *#*/,
  lheading: /^([^\n]+)\n *(=|-){3,}/,
  blockquote: /^ *>[^\n]*(?:\n *>[^\n]*)*/,
  //list: /^(?:( *)(\*|\+|-|\d+\.)[^\n]+(?:\n[^\n]+)*(?:\n{1,2}|$)){2,}/,
  //list: /^(?:( *)(\*|\+|-|\d+\.)[^\n]+(?:\n[^\n]*)*){2,}(?:\n\n\1?(?!\*|\+|-|\d\.)|$)/,
  //list: /^(?:( *)(\*|\+|-|\d+\.)[^\n]+(?:\n[^\n]+|\n\n)*){2,}/,
  //list: /^( *)(\*|\+|-|\d+\.)[\s\S]+?(\1\2[\s\S]+?(?=\1\2))*/,

  // simple
  //list: /^(?:( *)(\*|\+|-|\d+\.)[^\n]*(?:\n\1 [^\n]+)*){2,}/,

  // very good, does it all
  //list: /^(?:( *)(\*|\+|-|\d+\.)[^\n]*(?:\n(?:\1 |)[^\n]+)*){2,}/,

  // better, faster
  //list: /^(?:( *)(\*|\+|-|\d+\.)[^\n]*(?:\n[^\n]+)*){2,}/,

  // fastest
  //list: /^( *)(\*|\+|-|\d+\.)[^\n]*(?:\n[^\n]+)*/,

  // fastest with loose list support
  // list: /^( *)(\*|\+|-|\d+\.)[^\n]*(?:\n[^\n]+|\n{2}\1\2[^\n]*)*/,

  // fix ordered lists:
  list: /^( *)([*+-]|\d+\.)[^\n]*(?:\n[^\n]+|\n{2}\1(?:\2|\d+\.)[^\n]*)*/,

  // the first list item
  //list: /^( *)(\*|\+|-|\d+\.)[^\n]*(?:\n(?!\1\2)[^\n]+)*/,

  // all list items
  //list: /^(?:( *)(\*|\+|-|\d+\.)[^\n]*(?:\n(?!\1\2)[^\n]+)*){2,}/,

  // need the question mark because a trailing list item might not have a newline after it
  //list: /^(?:( *)(\*|\+|-|\d+\.)[^\n]*\n(?:(?!\1\2)[^\n]+\n?)*){2,}/,

  // instead of question mark...
  //list: /^(?:( *)(\*|\+|-|\d+\.)[^\n]*\n(?:(?!\1\2)[^\n]+(?:\n|$))*){2,}/,

  //list: /^(?:( *)(\*|\+|-|\d+\.)[^\n]*\n(?:(?!\1\2)[^\n]+(?:\n|$))*){2,}/,

  html: /^<([^\/\s>]+)[^\n>]*>[^\n]*(?:\n[^\n]+)*\n?<\/\1>/,
  text: /^[^\n]+/
};

block.keys = [
  'newline',
  'block',
  'heading',
  'lheading',
  'hr',
  'blockquote',
  'list',
  'html',
  'text'
];

/**
 * Lexer
 */

block.lexer = function(str) {
  var tokens = []
    , links = {};

  // normalize whitespace
  str = str.replace(/\r\n/g, '\n')
           .replace(/\r/g, '\n')
           .replace(/\t/g, '    ');

  // experimental
  // str = str.replace(/^ +$/gm, '');

  // grab link definitons
  str = str.replace(
    /^ {0,3}\[([^\]]+)\]: *([^ ]+)(?: +"([^"]+)")? *(?:\n|$)/gm,
    function(_, id, href, title) {
      links[id] = {
        href: href,
        title: title
      };
      return '';
    }
  );

  tokens.links = links;

  return block.token(str, tokens);
};

block.token = function(str, tokens) {
  var rules = block
    , keys = block.keys
    , len = keys.length
    , key
    , cap
    , loose;

  var scan = function() {
    if (!str) return;
    for (var i = 0; i < len; i++) {
      key = keys[i];
      if (cap = rules[key].exec(str)) {
        str = str.substring(cap[0].length);
        return true;
      }
    }
  };

  while (scan()) {
    switch (key) {
      case 'newline':
        if (cap[0].length > 1) {
          tokens.push({
            type: 'space'
          });
        }
        break;
      case 'hr':
        tokens.push({
          type: 'hr'
        });
        break;
      case 'lheading':
        tokens.push({
          type: 'heading',
          depth: cap[2] === '=' ? 1 : 2,
          text: cap[1]
        });
        break;
      case 'heading':
        tokens.push({
          type: 'heading',
          depth: cap[1].length,
          text: cap[2]
        });
        break;
      case 'block':
        cap = cap[0].replace(/^ {4}/gm, '');
        tokens.push({
          type: 'block',
          text: cap
        });
        break;
      case 'list':
        tokens.push({
          type: 'list_start',
          ordered: isFinite(cap[2])
        });
        loose = /\n *\n *(?:\*|\+|-|\d+\.)/.test(cap[0]);
        //loose = false; // /\n *\n(?! *$)/.test(cap[0]);
        //loose = '\n *\n' + cap[1]
        //      + '(?:\\*|\\+|-|\\d+\\.)';
        //loose = new RegExp(loose).test(cap[0]);
        // get each top-level
        // item in the list
        //console.log('----');
        //console.log(cap[0]);
        //console.log('----');
        cap = cap[0].match(
          // /^( *)(\*|\+|-|\d+\.)[^\n]+(?:\n\1+(?!\*|\+|-|\d\.)[^\n]*)*/gm
          // /^( *)(\*|\+|-|\d+\.)[^\n]+(?:\n\1+(?!\*|\+|-|\d\.)[^\n]*|\n)*/gm

          // /^( *)(\*|\+|-|\d+\.)[^\n]*(?:\n(?!\1\2)[^\n]*)*/gm

          // fix ordered lists:
          /^( *)([*+-]|\d+\.)[^\n]*(?:\n(?!\1(?:\2|\d+\.))[^\n]*)*/gm
        );
        each(cap, function(item) {
          // remove the list items sigil
          // so its seen as the next token
          item = item.replace(/^ *(\*|\+|-|\d+\.) */, '');
          // outdent whatever the
          // list item contains, hacky
          var space = /\n( +)/.exec(item);
          if (space) {
            space = new RegExp('^' + space[1], 'gm');
            item = item.replace(space, '');
          }
          tokens.push({
            type: loose
              ? 'loose_item_start'
              : 'list_item_start'
          });
          block.token(item, tokens);
          tokens.push({
            type: 'list_item_end'
          });
        });
        tokens.push({
          type: 'list_end'
        });
        break;
      case 'html':
      case 'text':
        tokens.push({
          type: key,
          text: cap[0]
        });
        break;
      case 'blockquote':
        tokens.push({
          type: 'blockquote_start'
        });
        cap = cap[0].replace(/^ *>/gm, '');
        block.token(cap, tokens);
        tokens.push({
          type: 'blockquote_end'
        });
        break;
    }
  }

  return tokens;
};

/**
 * Inline Processing
 */

var inline = {
  escape: /^\\([\\`*{}\[\]()#+\-.!])/,
  autolink: /^<([^ >]+(@|:\/)[^ >]+)>/,
  tag: /^<[^\n>]+>/,
  link: /^!?\[([^\]]+)\]\(([^\)]+)\)/,
  reflink: /^!?\[([^\]]+)\]\[([^\]]+)\]/,
  strong: /^__([\s\S]+?)__|^\*\*([\s\S]+?)\*\*/,
  em: /^_([^_]+)_|^\*([^*]+)\*/,
  code: /^`([^`]+)`|^``([\s\S]+?)``/
};

inline.keys = [
  'escape',
  'autolink',
  'tag',
  'link',
  'reflink',
  'strong',
  'em',
  'code'
];

// hacky, but performant
inline.text = (function(rules) {
  var keys = rules.keys
    , i = 0
    , l = keys.length
    , body = [];

  for (; i < l; i++) {
    body.push(rules[keys[i]].source
      .replace(/(^|[^\[])\^/g, '$1'));
  }

  keys.push('text');

  return new RegExp(
    '^([\\s\\S]+?)(?='
    + body.join('|')
    + '|$)'
  );
})(inline);

/**
 * Inline Lexer
 */

inline.lexer = function(str) {
  var out = ''
    , links = tokens.links
    , link
    , text
    , href;

  var rules = inline
    , keys = inline.keys
    , len = keys.length
    , key
    , cap;

  var scan = function() {
    if (!str) return;
    for (var i = 0; i < len; i++) {
      key = keys[i];
      if (cap = rules[key].exec(str)) {
        str = str.substring(cap[0].length);
        return true;
      }
    }
  };

  while (scan()) {
    switch (key) {
      case 'escape':
        out += cap[1];
        break;
      case 'tag':
        out += cap[0];
        break;
      case 'link':
      case 'reflink':
        if (cap[0][0] !== '!') {
          if (key === 'reflink') {
            link = links[cap[2]];
            if (!link) throw new
              Error('Undefined Reference: ' + cap[2]);
          } else {
            link = {
              href: cap[2],
              title: cap[3]
            };
          }
          out += ''
            + inline.lexer(cap[1])
            + '';
        } else {
          if (key === 'reflink') {
            link = links[cap[2]];
            if (!link) throw new
              Error('Undefined Reference: ' + cap[2]);
          } else {
            text = /^([^\s]+)\s*(.+)?$/.exec(cap[2]);
            link = {
              href: text[1],
              title: text[2]
            };
          }
          out += '';
        }
        break;
      case 'autolink':
        if (cap[2] === '@') {
          text = mangle(cap[1]);
          href = mangle('mailto:') + text;
        } else {
          text = escape(cap[1]);
          href = text;
        }
        out += ''
          + text
          + '';
        break;
      case 'strong':
        out += ''
          + inline.lexer(cap[2] || cap[1])
          + '';
        break;
      case 'em':
        out += ''
          + inline.lexer(cap[2] || cap[1])
          + '';
        break;
      case 'code':
        out += ''
          + escape(cap[2] || cap[1])
          + '';
        break;
      case 'text':
        out += escape(cap[1]);
        break;
      default:
        break;
    }
  }

  return out;
};

/**
 * Parsing
 */

var tokens
  , token;

var next = function() {
  return token = tokens.pop();
};

var tok = function() {
  switch (token.type) {
    case 'space':
      return '';
    case 'hr':
      return '
';
    case 'heading':
      return '<h' + token.depth + '>'
        + inline.lexer(token.text)
        + '</h' + token.depth + '>';
    case 'block':
      return '
'
        + escape(token.text)
        + '
';
    case 'blockquote_start':
      var body = [];
      while (next().type !== 'blockquote_end') {
        body.push(tok());
      }
      return '
'
        + body.join('')
        + '
';
    case 'list_start':
      var body = []
        , type = token.ordered ? 'ol' : 'ul';
      while (next().type !== 'list_end') {
        body.push(tok());
      }
      return '<' + type + '>'
        + body.join('')
        + '</' + type + '>';
    case 'list_item_start':
      var body = [];
      while (next().type !== 'list_item_end') {
        body.push(token.type === 'text'
          ? inline.lexer(token.text)
          : tok());
      }
      return '
'
        + body.join(' ')
        + '
';
    case 'loose_item_start':
      var body = [];
      while (next().type !== 'list_item_end') {
        body.push(tok());
      }
      return '
'
        + body.join(' ')
        + '
';
    case 'html':
      return inline.lexer(token.text);
    case 'text':
      var body = [ token.text ]
        , top;
      while ((top = tokens[tokens.length-1])
             && top.type === 'text') {
        body.push(next().text);
      }
      return '
'
        + inline.lexer(body.join(' '))
        + '
';
  }
};

var parse = function(src) {
  tokens = src.reverse();

  var out = [];
  while (next()) {
    out.push(tok());
  }

  tokens = null;
  token = null;

  return out.join(' ');
};

/**
 * Helpers
 */

var escape = function(html) {
  return html
    .replace(/&/g, '&')
    .replace(/</g, '<')
    .replace(/>/g, '>')
    .replace(/"/g, '"')
    .replace(/'/g, ''');
};

var mangle = function(str) {
  var out = ''
    , ch
    , i = 0
    , l = str.length;

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

  return out;
};

var each = function(obj, func) {
  var i = 0, l = obj.length;
  for (; i < l; i++) func(obj[i]);
};

/**
 * Expose
 */

var marked = function(str) {
  return parse(block.lexer(str));
};

marked.parser = parse;
marked.lexer = block.lexer;

if (typeof module !== 'undefined') {
  module.exports = marked;
} else {
  this.marked = marked;
}

}).call(this);
<commit_msg>unquote<commit_after>/**
 * marked - A markdown parser
 * Copyright (c) 2011, Christopher Jeffrey. (MIT Licensed)
 */

;(function() {

/**
 * Block-Level Grammar
 */

var block = {
  newline: /^\n+/,
  block: /^ {4,}[^\n]*(?:\n {4,}[^\n]*)*/,
  hr: /^( *[\-*_]){3,}/,
  heading: /^ *(#{1,6}) *([^\n#]*) *#*/,
  lheading: /^([^\n]+)\n *(=|-){3,}/,
  blockquote: /^ *>[^\n]*(?:\n *>[^\n]*)*/,
  //list: /^(?:( *)(\*|\+|-|\d+\.)[^\n]+(?:\n[^\n]+)*(?:\n{1,2}|$)){2,}/,
  //list: /^(?:( *)(\*|\+|-|\d+\.)[^\n]+(?:\n[^\n]*)*){2,}(?:\n\n\1?(?!\*|\+|-|\d\.)|$)/,
  //list: /^(?:( *)(\*|\+|-|\d+\.)[^\n]+(?:\n[^\n]+|\n\n)*){2,}/,
  //list: /^( *)(\*|\+|-|\d+\.)[\s\S]+?(\1\2[\s\S]+?(?=\1\2))*/,

  // simple
  //list: /^(?:( *)(\*|\+|-|\d+\.)[^\n]*(?:\n\1 [^\n]+)*){2,}/,

  // very good, does it all
  //list: /^(?:( *)(\*|\+|-|\d+\.)[^\n]*(?:\n(?:\1 |)[^\n]+)*){2,}/,

  // better, faster
  //list: /^(?:( *)(\*|\+|-|\d+\.)[^\n]*(?:\n[^\n]+)*){2,}/,

  // fastest
  //list: /^( *)(\*|\+|-|\d+\.)[^\n]*(?:\n[^\n]+)*/,

  // fastest with loose list support
  // list: /^( *)(\*|\+|-|\d+\.)[^\n]*(?:\n[^\n]+|\n{2}\1\2[^\n]*)*/,

  // fix ordered lists:
  list: /^( *)([*+-]|\d+\.)[^\n]*(?:\n[^\n]+|\n{2}\1(?:\2|\d+\.)[^\n]*)*/,

  // the first list item
  //list: /^( *)(\*|\+|-|\d+\.)[^\n]*(?:\n(?!\1\2)[^\n]+)*/,

  // all list items
  //list: /^(?:( *)(\*|\+|-|\d+\.)[^\n]*(?:\n(?!\1\2)[^\n]+)*){2,}/,

  // need the question mark because a trailing list item might not have a newline after it
  //list: /^(?:( *)(\*|\+|-|\d+\.)[^\n]*\n(?:(?!\1\2)[^\n]+\n?)*){2,}/,

  // instead of question mark...
  //list: /^(?:( *)(\*|\+|-|\d+\.)[^\n]*\n(?:(?!\1\2)[^\n]+(?:\n|$))*){2,}/,

  //list: /^(?:( *)(\*|\+|-|\d+\.)[^\n]*\n(?:(?!\1\2)[^\n]+(?:\n|$))*){2,}/,

  html: /^<([^\/\s>]+)[^\n>]*>[^\n]*(?:\n[^\n]+)*\n?<\/\1>/,
  text: /^[^\n]+/
};

block.keys = [
  'newline',
  'block',
  'heading',
  'lheading',
  'hr',
  'blockquote',
  'list',
  'html',
  'text'
];

/**
 * Lexer
 */

block.lexer = function(str) {
  var tokens = []
    , links = {};

  // normalize whitespace
  str = str.replace(/\r\n/g, '\n')
           .replace(/\r/g, '\n')
           .replace(/\t/g, '    ');

  // experimental
  // str = str.replace(/^ +$/gm, '');

  // grab link definitons
  str = str.replace(
    /^ {0,3}\[([^\]]+)\]: *([^ ]+)(?: +"([^"]+)")? *(?:\n|$)/gm,
    function(_, id, href, title) {
      links[id] = {
        href: href,
        title: unquote(title)
      };
      return '';
    }
  );

  tokens.links = links;

  return block.token(str, tokens);
};

block.token = function(str, tokens) {
  var rules = block
    , keys = block.keys
    , len = keys.length
    , key
    , cap
    , loose;

  var scan = function() {
    if (!str) return;
    for (var i = 0; i < len; i++) {
      key = keys[i];
      if (cap = rules[key].exec(str)) {
        str = str.substring(cap[0].length);
        return true;
      }
    }
  };

  while (scan()) {
    switch (key) {
      case 'newline':
        if (cap[0].length > 1) {
          tokens.push({
            type: 'space'
          });
        }
        break;
      case 'hr':
        tokens.push({
          type: 'hr'
        });
        break;
      case 'lheading':
        tokens.push({
          type: 'heading',
          depth: cap[2] === '=' ? 1 : 2,
          text: cap[1]
        });
        break;
      case 'heading':
        tokens.push({
          type: 'heading',
          depth: cap[1].length,
          text: cap[2]
        });
        break;
      case 'block':
        cap = cap[0].replace(/^ {4}/gm, '');
        tokens.push({
          type: 'block',
          text: cap
        });
        break;
      case 'list':
        tokens.push({
          type: 'list_start',
          ordered: isFinite(cap[2])
        });
        loose = /\n *\n *(?:\*|\+|-|\d+\.)/.test(cap[0]);
        //loose = false; // /\n *\n(?! *$)/.test(cap[0]);
        //loose = '\n *\n' + cap[1]
        //      + '(?:\\*|\\+|-|\\d+\\.)';
        //loose = new RegExp(loose).test(cap[0]);
        // get each top-level
        // item in the list
        //console.log('----');
        //console.log(cap[0]);
        //console.log('----');
        cap = cap[0].match(
          // /^( *)(\*|\+|-|\d+\.)[^\n]+(?:\n\1+(?!\*|\+|-|\d\.)[^\n]*)*/gm
          // /^( *)(\*|\+|-|\d+\.)[^\n]+(?:\n\1+(?!\*|\+|-|\d\.)[^\n]*|\n)*/gm

          // /^( *)(\*|\+|-|\d+\.)[^\n]*(?:\n(?!\1\2)[^\n]*)*/gm

          // fix ordered lists:
          /^( *)([*+-]|\d+\.)[^\n]*(?:\n(?!\1(?:\2|\d+\.))[^\n]*)*/gm
        );
        each(cap, function(item) {
          // remove the list items sigil
          // so its seen as the next token
          item = item.replace(/^ *(\*|\+|-|\d+\.) */, '');
          // outdent whatever the
          // list item contains, hacky
          var space = /\n( +)/.exec(item);
          if (space) {
            space = new RegExp('^' + space[1], 'gm');
            item = item.replace(space, '');
          }
          tokens.push({
            type: loose
              ? 'loose_item_start'
              : 'list_item_start'
          });
          block.token(item, tokens);
          tokens.push({
            type: 'list_item_end'
          });
        });
        tokens.push({
          type: 'list_end'
        });
        break;
      case 'html':
      case 'text':
        tokens.push({
          type: key,
          text: cap[0]
        });
        break;
      case 'blockquote':
        tokens.push({
          type: 'blockquote_start'
        });
        cap = cap[0].replace(/^ *>/gm, '');
        block.token(cap, tokens);
        tokens.push({
          type: 'blockquote_end'
        });
        break;
    }
  }

  return tokens;
};

/**
 * Inline Processing
 */

var inline = {
  escape: /^\\([\\`*{}\[\]()#+\-.!])/,
  autolink: /^<([^ >]+(@|:\/)[^ >]+)>/,
  tag: /^<[^\n>]+>/,
  link: /^!?\[([^\]]+)\]\(([^\)]+)\)/,
  reflink: /^!?\[([^\]]+)\]\[([^\]]+)\]/,
  strong: /^__([\s\S]+?)__|^\*\*([\s\S]+?)\*\*/,
  em: /^_([^_]+)_|^\*([^*]+)\*/,
  code: /^`([^`]+)`|^``([\s\S]+?)``/
};

inline.keys = [
  'escape',
  'autolink',
  'tag',
  'link',
  'reflink',
  'strong',
  'em',
  'code'
];

// hacky, but performant
inline.text = (function(rules) {
  var keys = rules.keys
    , i = 0
    , l = keys.length
    , body = [];

  for (; i < l; i++) {
    body.push(rules[keys[i]].source
      .replace(/(^|[^\[])\^/g, '$1'));
  }

  keys.push('text');

  return new RegExp(
    '^([\\s\\S]+?)(?='
    + body.join('|')
    + '|$)'
  );
})(inline);

/**
 * Inline Lexer
 */

inline.lexer = function(str) {
  var out = ''
    , links = tokens.links
    , link
    , text
    , href;

  var rules = inline
    , keys = inline.keys
    , len = keys.length
    , key
    , cap;

  var scan = function() {
    if (!str) return;
    for (var i = 0; i < len; i++) {
      key = keys[i];
      if (cap = rules[key].exec(str)) {
        str = str.substring(cap[0].length);
        return true;
      }
    }
  };

  while (scan()) {
    switch (key) {
      case 'escape':
        out += cap[1];
        break;
      case 'tag':
        out += cap[0];
        break;
      case 'link':
      case 'reflink':
        if (cap[0][0] !== '!') {
          if (key === 'reflink') {
            link = links[cap[2]];
            if (!link) throw new
              Error('Undefined Reference: ' + cap[2]);
          } else {
            link = {
              href: cap[2],
              title: unquote(cap[3])
            };
          }
          out += ''
            + inline.lexer(cap[1])
            + '';
        } else {
          if (key === 'reflink') {
            link = links[cap[2]];
            if (!link) throw new
              Error('Undefined Reference: ' + cap[2]);
          } else {
            text = /^([^\s]+)\s*(.+)?$/.exec(cap[2]);
            link = {
              href: text[1],
              title: unquote(text[2])
            };
          }
          out += '';
        }
        break;
      case 'autolink':
        if (cap[2] === '@') {
          text = mangle(cap[1]);
          href = mangle('mailto:') + text;
        } else {
          text = escape(cap[1]);
          href = text;
        }
        out += ''
          + text
          + '';
        break;
      case 'strong':
        out += ''
          + inline.lexer(cap[2] || cap[1])
          + '';
        break;
      case 'em':
        out += ''
          + inline.lexer(cap[2] || cap[1])
          + '';
        break;
      case 'code':
        out += ''
          + escape(cap[2] || cap[1])
          + '';
        break;
      case 'text':
        out += escape(cap[1]);
        break;
      default:
        break;
    }
  }

  return out;
};

/**
 * Parsing
 */

var tokens
  , token;

var next = function() {
  return token = tokens.pop();
};

var tok = function() {
  switch (token.type) {
    case 'space':
      return '';
    case 'hr':
      return '
';
    case 'heading':
      return '<h' + token.depth + '>'
        + inline.lexer(token.text)
        + '</h' + token.depth + '>';
    case 'block':
      return '
'
        + escape(token.text)
        + '
';
    case 'blockquote_start':
      var body = [];
      while (next().type !== 'blockquote_end') {
        body.push(tok());
      }
      return '
'
        + body.join('')
        + '
';
    case 'list_start':
      var body = []
        , type = token.ordered ? 'ol' : 'ul';
      while (next().type !== 'list_end') {
        body.push(tok());
      }
      return '<' + type + '>'
        + body.join('')
        + '</' + type + '>';
    case 'list_item_start':
      var body = [];
      while (next().type !== 'list_item_end') {
        body.push(token.type === 'text'
          ? inline.lexer(token.text)
          : tok());
      }
      return '
'
        + body.join(' ')
        + '
';
    case 'loose_item_start':
      var body = [];
      while (next().type !== 'list_item_end') {
        body.push(tok());
      }
      return '
'
        + body.join(' ')
        + '
';
    case 'html':
      return inline.lexer(token.text);
    case 'text':
      var body = [ token.text ]
        , top;
      while ((top = tokens[tokens.length-1])
             && top.type === 'text') {
        body.push(next().text);
      }
      return '
'
        + inline.lexer(body.join(' '))
        + '
';
  }
};

var parse = function(src) {
  tokens = src.reverse();

  var out = [];
  while (next()) {
    out.push(tok());
  }

  tokens = null;
  token = null;

  return out.join(' ');
};

/**
 * Helpers
 */

var escape = function(html) {
  return html
    .replace(/&/g, '&')
    .replace(/</g, '<')
    .replace(/>/g, '>')
    .replace(/"/g, '"')
    .replace(/'/g, ''');
};

var mangle = function(str) {
  var out = ''
    , ch
    , i = 0
    , l = str.length;

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

  return out;
};

var each = function(obj, func) {
  var i = 0, l = obj.length;
  for (; i < l; i++) func(obj[i]);
};

var unquote = function(str) {
  if (!str) return str;
  var ch = str[0];
  return (ch === '"' || ch === '\'')
          ? str.slice(1, -1) : str;
};

/**
 * Expose
 */

var marked = function(str) {
  return parse(block.lexer(str));
};

marked.parser = parse;
marked.lexer = block.lexer;

if (typeof module !== 'undefined') {
  module.exports = marked;
} else {
  this.marked = marked;
}

}).call(this);
<|endoftext|>


<commit_before>'use strict';

function Matrix() {

  this.transformations = [];

  return this;
}

Matrix.prototype.calc = function(x, y, isRelative) {
  var newXY = [x,y];

  this.transformations.forEach(function(trans) {
    if( isRelative && trans.operation === 'translate'){
      return;
    }
    if(isRelative){
      newXY = [
        newXY[0] * trans.matrix[0] + newXY[1] * trans.matrix[2],
        newXY[0] * trans.matrix[1] + newXY[1] * trans.matrix[3]
      ];
    } else {
      newXY = [
        newXY[0] * trans.matrix[0] + newXY[1] * trans.matrix[2] + trans.matrix[4],
        newXY[0] * trans.matrix[1] + newXY[1] * trans.matrix[3] + trans.matrix[5]
      ];
    }
  });
  return newXY;
};

// params = [a, b, c, d, e, f]
Matrix.prototype.matrix = function(params) {
  this.transformations.unshift({
    'operation' : 'matrix',
    'matrix' : params
  });
};

// params = [angle <, x, y>]
Matrix.prototype.rotate = function(params) {

  var alpha = params[0] * Math.PI / 180;
  var cosa = Math.cos(alpha);
  var sina = Math.sin(alpha);

  if (params.length === 3) {
    // Rotation about point ( params[1], params[2])

    this.translate([ params[1], params[2]]);

    this.transformations.unshift({
      'operation' : 'rotate',
      'matrix' : [ cosa, sina, -sina, cosa, 0, 0 ],
    });
    this.translate([ -params[1], -params[2] ]);

  } else {
    // Rotation about point ( 0, 0)

    this.transformations.unshift({
      'operation' : 'rotate',
      'matrix' : [ cosa, sina, -sina, cosa, 0, 0 ]
    });
  }
};

// params = [x <, y>]
Matrix.prototype.scale = function(params) {
  this.transformations.unshift({
    'operation' : 'scale',
    'matrix' : [ params[0] , 0, 0, (params.length === 2 ? params[1] : params[0]), 0, 0 ],
  });
};

// params = [angle]
Matrix.prototype.skewX = function(params) {
  this.transformations.unshift({
    'operation' : 'skewX',
    'matrix' : [ 1, 0, Math.tan(params[0] * Math.PI / 180), 1, 0, 0 ],
  });
};

// params = [angle]
Matrix.prototype.skewY = function(params) {
  this.transformations.unshift({
    'operation' : 'skewY',
    'matrix' : [ 1, Math.tan(params[0] * Math.PI / 180), 0, 1, 0, 0 ],
  });
};

// params = [x <, y>]
Matrix.prototype.translate = function(params) {
  this.transformations.unshift({
    'operation' : 'translate',
    'matrix' : [ 1, 0, 0, 1, params[0], (params.length === 2 ? params[1] : 0) ],
  });
};

module.exports = Matrix;
<commit_msg>matrix logic cleanup<commit_after>'use strict';

function Matrix() {
  this.queue = []; // list of matrixes to apply
}

// params = [a, b, c, d, e, f]
Matrix.prototype.matrix = function(params) {
  this.queue.unshift(params);
};

// params = [angle <, x, y>]
Matrix.prototype.rotate = function(params) {

  var alpha = params[0] * Math.PI / 180;
  var cosa = Math.cos(alpha);
  var sina = Math.sin(alpha);

  if (params.length === 3) {
    // Rotation about point ( params[1], params[2])
    this.translate([ params[1], params[2]]);
    this.queue.unshift([ cosa, sina, -sina, cosa, 0, 0 ]);
    this.translate([ -params[1], -params[2] ]);

  } else {
    // Rotation around (0, 0)
    this.queue.unshift([ cosa, sina, -sina, cosa, 0, 0 ]);
  }
};

// params = [x <, y>]
Matrix.prototype.scale = function(params) {
  this.queue.unshift([ params[0] , 0, 0, (params.length === 2 ? params[1] : params[0]), 0, 0 ]);
};

// params = [angle]
Matrix.prototype.skewX = function(params) {
  this.queue.unshift([ 1, 0, Math.tan(params[0] * Math.PI / 180), 1, 0, 0 ]);
};

// params = [angle]
Matrix.prototype.skewY = function(params) {
  this.queue.unshift([ 1, Math.tan(params[0] * Math.PI / 180), 0, 1, 0, 0 ]);
};

// params = [x <, y>]
Matrix.prototype.translate = function(params) {
  this.queue.unshift([ 1, 0, 0, 1, params[0], (params.length === 2 ? params[1] : 0) ]);
};

// Apply list of matrixes to X,Y point. If isRelative set,
// then `translate` skipped
//
Matrix.prototype.calc = function(x, y, isRelative) {
  var newXY = [x,y];

  this.queue.forEach(function(trans) {
    newXY = [
      newXY[0] * trans[0] + newXY[1] * trans[2] + (isRelative ? 0 : trans[4]),
      newXY[0] * trans[1] + newXY[1] * trans[3] + (isRelative ? 0 : trans[5])
    ];
  });
  return newXY;
};

module.exports = Matrix;
<|endoftext|>


<commit_before>var File = require('./file');
var Cache = require('./cache');
var module_cache = Cache('modules');

/**
 * Parse and get the engine package infos.
 *
 * @private
 * @param {string} The module name or the custom module config object.
 * @param {function} The callback function.
 * @param {object} The package of the parent module.
 */
module.exports = function getModulePackage (module, callback, parentPackage, version) {

    // append module prefix for custom modules
    var moduleName = typeof module === 'object' ? '_inst_mod:' + module.name : module;

    // get module package info from cache
    var cachedPackage = module_cache.get(moduleName + (version ? '@' + version : ''));

    // return cached object
    if (cachedPackage) {
        return callback(null, cachedPackage);
    }

    // handle custom modules
    if (typeof module === 'object') {

        // for custom modules the base path is the repo itself
        module._base = engine.repo;
        module.name = moduleName;
        module._id = moduleName;

        // call module handler with custom package object
        handleModule(module, callback, parentPackage);
        return;
    }

    // create module path
    var base = (parentPackage ? parentPackage._base : engine.repo) + 'node_modules/' + moduleName + '/';

    // read and parse the packackage json file
    File.json(base + 'package.json', function (err, modulePackage) {

        // handle error
        if (err) {
            return callback(err);
        }

        // handle module packet not found
        if (!modulePackage) {
            return callback(new Error('No module package found.'));
        }

        // TODO what if modulePackage.name !== moduleName ?

        // ensure module id
        modulePackage._id = modulePackage._id || modulePackage.name + '@' + modulePackage.version;

        // save module base path
        modulePackage._base = base;

        // call module handler with the parsed package.json
        handleModule(modulePackage, callback, parentPackage);
    });
};

/**
 * Update module component paths and load client dependencies.
 *
 * @private
 * @param {string} The module name or the custom module config object.
 * @param {object} The package info.
 * @param {function} The callback function.
 * @param {object} The package of the parent module.
 */
function handleModule (modulePackage, callback, parentPackage) {

    // save package info in cache
    module_cache.set(modulePackage._id, modulePackage);

    // save the top level modules packages also without a version
    if (!parentPackage) {
        module_cache.set(modulePackage.name, modulePackage);
    }

    // create loading handler callback for child modules
    if (parentPackage) {
        callback = loadHandler(parentPackage, callback);
    }

    // load module client dependencies
    if (modulePackage.clientDependencies) {
        for (var i = 0, l = modulePackage.clientDependencies.length; i < l; ++i) {
            getModulePackage(
                modulePackage.clientDependencies[i],
                callback,
                modulePackage,
                modulePackage.dependencies[module]
            );
        }
    }

    // return module package
    if (!modulePackage.components) {

        // return custom module
        return callback(null, modulePackage);
    }

    // add fingerprints to module resources
    File.prepareComponents(modulePackage, function (err, components) {

        if (err) {
            console.error('lib/comp.js#245', err.toString());
            return callback(err);
        }

        callback(null, modulePackage);
    });

}

/**
 * Handle recursive module loading and merge child components to the parent
 * module package.
 *
 * @private
 * @param {object} The object with the source arrays.
 * @param {object} Options fot the fingerprint mehtod.
 * @param {function} The callback function.
 */
function loadHandler (parentPackage, callback) {

    parentPackage && (parentPackage._elmsToLoad = (parentPackage.clientDependencies || '').length + 1);

    return function (err, modulePackage) {

        if (err || !modulePackage) {
            err = err || new Error('No module package found.');
            console.error('lib/comp.js#274', err.toString());

        } else {

            // merge module components into parent module
            if (parentPackage && modulePackage.components) {

                for (var type in modulePackage.components) {

                    // ensure component type array
                    parentPackage.components[type] = parentPackage.components[type] || [];

                    // push the module components to the parent module components
                    for (var i = 0; i < modulePackage.components[type].length; ++i) {
                        parentPackage.components[type].push(modulePackage.components[type][i]);
                    }
                }
            }
        }

        // return the module packge for top level modules
        if (!parentPackage) {
            return callback(null, modulePackage);
        }

        // return pareent package, when all submodules are merged
        if (--parentPackage._elmsToLoad === 0) {
            callback(null, parentPackage);
        }
    };
}
<commit_msg>build recusrive client module loader<commit_after>var File = require('./file');
var Cache = require('./cache');
var module_cache = Cache('modules');

/**
 * Parse and get the engine package infos.
 *
 * @private
 * @param {string} The module name or the custom module config object.
 * @param {function} The callback function.
 * @param {object} The package of the parent module.
 */
module.exports = function getModulePackage (module, callback, parentPackage) {

    // get cache key to look for cached packages
    var cachedPackage = module._id || module;

    // handle client dependency
    if (parentPackage) {

        // check if client dependency exists
        if (!parentPackage.dependencies[module]) {
            return callback(new Error('Client module dependency not found.'));
        }

        // update cache key with version
        cachedPackage += '@' + parentPackage.dependencies[module];
    }

    // return cached object
    if ((cachedPackage = module_cache.get(cachedPackage))) {
        return callback(null, cachedPackage);
    }

    // handle custom modules
    if (typeof module === 'object') {
        return handleModule(module, callback);
    }

    // create module path
    var base = (parentPackage ? parentPackage._base : engine.repo) + 'node_modules/' + module + '/';

    // read and parse the packackage json file
    File.json(base + 'package.json', function (err, modulePackage) {

        // handle error
        if (err) {
            return callback(err);
        }

        // ensure module id
        modulePackage._id = modulePackage._id || modulePackage.name + '@' + modulePackage.version;

        // save module base path
        modulePackage._base = base;

        // call module handler with the parsed package.json
        handleModule(modulePackage, callback, parentPackage);
    });
};

/**
 * Update module component paths and load client dependencies.
 *
 * @private
 * @param {string} The module name or the custom module config object.
 * @param {object} The package info.
 * @param {function} The callback function.
 * @param {object} The package of the parent module.
 */
function handleModule (modulePackage, callback, parentPackage) {

    // check if client config exists
    var client = modulePackage.engine_instance;
    if (
      !client ||
      !client.client ||
      (
          !client.client.dependencies &&
          !client.client.module &&
          !client.client.markup &&
          !client.client.styles
      )
    ) {
        return callback(null, modulePackage);
    }
    client = client.client;

    var countDown = 1;
    var recursiveHandler = function (err, modPkg) {

        // TODO handle error
        // TODO merge modPkg files to modulePackage

        // save package info in cache
        module_cache.set(modPkg._id, modPkg);

        if (--countDown === 0) {

            // save the top level modules packages also without a version
            if (!parentPackage && modPkg.version !== 'custom') {
                module_cache.set(modPkg.name, modPkg);
            }

            callback(null, modulePackage);
        }
    };

    // handle client dependencies
    if (client.dependencies) {

        countDown += client.dependencies.length;

        for (var i = 0, l = client.dependencies.length; i < l; ++i) {
            getModulePackage(
                client.dependencies[i],
                recursiveHandler,
                modulePackage
            );
        }
    }

    // prepare files
    if (client.module || client.markup || client.styles) {
        File.prepare(client, function (err, files) {

            // TODO update file path on module package

            recursiveHandler(null, modulePackage);
        });
    }
}

/**
 * Handle recursive module loading and merge child components to the parent
 * module package.
 *
 * @private
 * @param {object} The object with the source arrays.
 * @param {object} Options fot the fingerprint mehtod.
 * @param {function} The callback function.
 */
function loadHandler (parentPackage, callback) {

    parentPackage && (parentPackage._elmsToLoad = (parentPackage.clientDependencies || '').length + 1);

    return function (err, modulePackage) {

        if (err || !modulePackage) {
            err = err || new Error('No module package found.');
            console.error('lib/comp.js#274', err.toString());

        } else {

            // merge module components into parent module
            if (parentPackage && modulePackage.components) {

                for (var type in modulePackage.components) {

                    // ensure component type array
                    parentPackage.components[type] = parentPackage.components[type] || [];

                    // push the module components to the parent module components
                    for (var i = 0; i < modulePackage.components[type].length; ++i) {
                        parentPackage.components[type].push(modulePackage.components[type][i]);
                    }
                }
            }
        }

        // return the module packge for top level modules
        if (!parentPackage) {
            return callback(null, modulePackage);
        }

        // return pareent package, when all submodules are merged
        if (--parentPackage._elmsToLoad === 0) {
            callback(null, parentPackage);
        }
    };
}
<|endoftext|>


<commit_before>var moment = require('moment');

exports.dateFormat = function(datestamp) {
    var date = moment(datestamp);

    if (date.isBefore(moment(), 'week')) {
        return date.format('MMM D, YYYY');
    }
    else {
        return date.fromNow();
    }
};

exports.section = function(name, options) {
    if(!this._sections) {
        this._sections = {};
    }
    this._sections[name] = options.fn(this);
    return null;
}

exports.urlFormat = function(url) {
    if (url.lastIndexOf('http://', 0) === 0) {
        url = url.substring(7);

        if (url.lastIndexOf('www.', 0) === 0) {
            url = url.substring(4);
        }
    }
    return url;
}
<commit_msg>Make sure URL helped doesn't break if a url is undefined<commit_after>var moment = require('moment');

exports.dateFormat = function(datestamp) {
    var date = moment(datestamp);

    if (date.isBefore(moment(), 'week')) {
        return date.format('MMM D, YYYY');
    }
    else {
        return date.fromNow();
    }
};

exports.section = function(name, options) {
    if(!this._sections) {
        this._sections = {};
    }
    this._sections[name] = options.fn(this);
    return null;
}

exports.urlFormat = function(url) {
	if(typeof url !== "undefined" && url != null) {
	    if (url.lastIndexOf('http://', 0) === 0) {
	        url = url.substring(7);

	        if (url.lastIndexOf('www.', 0) === 0) {
	            url = url.substring(4);
	        }
	    }
	    return url;
	}
}
<|endoftext|>


<commit_before>'use strict';

const	topLogPrefix	= 'larvitproduct: helpers.js - ',
	dataWriter	= require(__dirname + '/dataWriter.js'),
	request	= require('request'),
	lUtils	= require('larvitutils'),
	log	= require('winston'),
	_	= require('lodash');

let	intercom,
	esUrl,
	es;

function formatEsResult(esResult, cb) {
	const	logPrefix	= topLogPrefix + 'formatEsResult() - ',
		product	= {};

	if (esResult === false) {
		return cb(null, product);
	}

	if ( ! esResult._id) {
		const	err	= new Error('Missing esResult._id, full esResult: ' + JSON.stringify(esResult));
		log.warn(logPrefix + err.message);
		return cb(err);
	}

	product.uuid	= esResult._id;

	if (esResult._source) {
		product.attributes = _.cloneDeep(esResult._source);

		if (product.attributes.created) {
			product.created	= new Date(esResult._source.created);
			delete product.attributes.created;
		}
	}

	cb(null, product);
}

function getAttributeValues(attributeName, cb) {
	const	searchBody	= {'size':0, 'aggs':{'thingie':{'terms':{'field':attributeName}}}, 'query':{'bool':{'must':[]}}},
		logPrefix	= topLogPrefix + 'getAttributeValues() - url: ' + esUrl + '/larvitproduct/product/_search',
		values	= [],
		url	= esUrl + '/larvitproduct/product/_search';

	searchBody.aggs.thingie.terms.size = 2147483647; // http://stackoverflow.com/questions/22927098/show-all-elasticsearch-aggregation-results-buckets-and-not-just-10

	ready(function (err) {
		if (err) return cb(err);

		request({'url': url, 'body': searchBody, 'json': true}, function (err, response, body) {
			if (err) {
				log.error(logPrefix + err.message);
				return cb(err);
			}

			for (let i = 0; body.aggregations.thingie.buckets[i] !== undefined; i ++) {
				values.push(body.aggregations.thingie.buckets[i].key);
			}

			cb(null, values, body.aggregations.thingie.buckets);
		});
	});
}

function getKeywords(cb) {

	ready(function (err) {
		const	logPrefix	= topLogPrefix + 'getKeywords() - url: "' + esUrl + '/larvitproduct/_mapping/product"',
			url	= esUrl + '/larvitproduct/_mapping/product';

		if (err) { return cb(err); }

		request({'url': url, 'json': true}, function (err, response, body) {
			const	keywords	= [];

			if (err) {
				log.warn(logPrefix + 'Could not get mappings when calling. err: ' + err.message);
				return cb(err);
			}

			if (response.statusCode !== 200) {
				const	err	= new Error('non-200 statusCode: ' + response.statusCode);
				log.warn(logPrefix + err.message);
				return cb(err);
			}

			for (const fieldName of Object.keys(body.larvitproduct.mappings.product.properties)) {
				const	fieldProps	= body.larvitproduct.mappings.product.properties[fieldName];

				if (fieldProps.type === 'keyword') {
					keywords.push(fieldName);
				} else if (fieldProps.fields && fieldProps.fields.keyword && fieldProps.fields.keyword.type === 'keyword') {
					keywords.push(fieldName + '.keyword');
				}
			}

			cb(null, keywords);
		});
	});
}

function ready(cb) {
	dataWriter.ready(function (err) {
		intercom	= lUtils.instances.intercom;
		es	= lUtils.instances.elasticsearch;
		esUrl	= 'http://' + es.transport._config.host;
		cb(err);
	});
}

function updateByQuery(updateBody, cb) {
	const	options	= {'exchange': dataWriter.exchangeName},
		message	= {};

	message.action	= 'updateByQuery';
	message.params	= {};

	message.params.updateBody	= updateBody;

	intercom.send(message, options, function (err, msgUuid) {
		if (err) return cb(err);

		dataWriter.emitter.once(msgUuid, cb);
	});
}

exports.attributes	= [];
exports.formatEsResult	= formatEsResult;
exports.getAttributeValues	= getAttributeValues;
exports.getKeywords	= getKeywords;
exports.updateByQuery	= updateByQuery;
<commit_msg>Moved url definition to after ready()<commit_after>'use strict';

const	topLogPrefix	= 'larvitproduct: helpers.js - ',
	dataWriter	= require(__dirname + '/dataWriter.js'),
	request	= require('request'),
	lUtils	= require('larvitutils'),
	log	= require('winston'),
	_	= require('lodash');

let	intercom,
	esUrl,
	es;

function formatEsResult(esResult, cb) {
	const	logPrefix	= topLogPrefix + 'formatEsResult() - ',
		product	= {};

	if (esResult === false) {
		return cb(null, product);
	}

	if ( ! esResult._id) {
		const	err	= new Error('Missing esResult._id, full esResult: ' + JSON.stringify(esResult));
		log.warn(logPrefix + err.message);
		return cb(err);
	}

	product.uuid	= esResult._id;

	if (esResult._source) {
		product.attributes = _.cloneDeep(esResult._source);

		if (product.attributes.created) {
			product.created	= new Date(esResult._source.created);
			delete product.attributes.created;
		}
	}

	cb(null, product);
}

function getAttributeValues(attributeName, cb) {
	ready(function (err) {
		const	searchBody	= {'size':0, 'aggs':{'thingie':{'terms':{'field':attributeName}}}, 'query':{'bool':{'must':[]}}},
			logPrefix	= topLogPrefix + 'getAttributeValues() - url: ' + esUrl + '/larvitproduct/product/_search',
			values	= [],
			url	= esUrl + '/larvitproduct/product/_search';

		if (err) return cb(err);

		searchBody.aggs.thingie.terms.size = 2147483647; // http://stackoverflow.com/questions/22927098/show-all-elasticsearch-aggregation-results-buckets-and-not-just-10

		request({'url': url, 'body': searchBody, 'json': true}, function (err, response, body) {
			if (err) {
				log.error(logPrefix + err.message);
				return cb(err);
			}

			for (let i = 0; body.aggregations.thingie.buckets[i] !== undefined; i ++) {
				values.push(body.aggregations.thingie.buckets[i].key);
			}

			cb(null, values, body.aggregations.thingie.buckets);
		});
	});
}

function getKeywords(cb) {

	ready(function (err) {
		const	logPrefix	= topLogPrefix + 'getKeywords() - url: "' + esUrl + '/larvitproduct/_mapping/product"',
			url	= esUrl + '/larvitproduct/_mapping/product';

		if (err) { return cb(err); }

		request({'url': url, 'json': true}, function (err, response, body) {
			const	keywords	= [];

			if (err) {
				log.warn(logPrefix + 'Could not get mappings when calling. err: ' + err.message);
				return cb(err);
			}

			if (response.statusCode !== 200) {
				const	err	= new Error('non-200 statusCode: ' + response.statusCode);
				log.warn(logPrefix + err.message);
				return cb(err);
			}

			for (const fieldName of Object.keys(body.larvitproduct.mappings.product.properties)) {
				const	fieldProps	= body.larvitproduct.mappings.product.properties[fieldName];

				if (fieldProps.type === 'keyword') {
					keywords.push(fieldName);
				} else if (fieldProps.fields && fieldProps.fields.keyword && fieldProps.fields.keyword.type === 'keyword') {
					keywords.push(fieldName + '.keyword');
				}
			}

			cb(null, keywords);
		});
	});
}

function ready(cb) {
	dataWriter.ready(function (err) {
		intercom	= lUtils.instances.intercom;
		es	= lUtils.instances.elasticsearch;
		esUrl	= 'http://' + es.transport._config.host;
		cb(err);
	});
}

function updateByQuery(updateBody, cb) {
	const	options	= {'exchange': dataWriter.exchangeName},
		message	= {};

	message.action	= 'updateByQuery';
	message.params	= {};

	message.params.updateBody	= updateBody;

	intercom.send(message, options, function (err, msgUuid) {
		if (err) return cb(err);

		dataWriter.emitter.once(msgUuid, cb);
	});
}

exports.attributes	= [];
exports.formatEsResult	= formatEsResult;
exports.getAttributeValues	= getAttributeValues;
exports.getKeywords	= getKeywords;
exports.updateByQuery	= updateByQuery;
<|endoftext|>


<commit_before>/*
 * https://github.com/5orenso
 *
 * Copyright (c) 2016 Øistein Sørensen
 * Licensed under the MIT license.
 */
'use strict';

/**
 * Module for my app
 * @constructor
 * @param {hash} opt - Constructor options.
 * @property {string} [config={}] The config files.
 */
function MyApp(opt) {
    let opts = opt || {};
    if (opts.debug) {
        console.log(opts);
    }
}

/**
 * Run function
 * @returns {string} word - Result for this function.
 */
MyApp.prototype.run = () => {
    // Start my application and do all your stuff.
    return MyApp.prototype.say('Yo!');
};

/**
 * Say function
 * @param {string} text - Text to say.
 * @returns {string} text - Just saying.
 */
MyApp.prototype.say = (text) => {
    return text;
};

module.exports = MyApp;
<commit_msg>Added more comments.<commit_after>/*
 * https://github.com/5orenso
 *
 * Copyright (c) 2016 Øistein Sørensen
 * Licensed under the MIT license.
 */
'use strict';

/**
 * Module for my app
 * @constructor
 * @param {hash} opt - Constructor options.
 * @property {string} [config={}] The config files.
 */
function MyApp(opt) {
    let opts = opt || {};
    if (opts.debug) {
        console.log(opts);
    }
}

/**
 * Run function
 * @returns {string} word - Result for this function.
 */
MyApp.prototype.run = () => {
    // Start my application and do all your stuff.
    return MyApp.prototype.say('Yo!');
};

/**
 * Say function
 * @param {string} text - Text to say.
 *
 * @example
 * var res = myapp.say('Hello world!');
 * console.log(res);
 * // Hello World!
 *
 * @returns {string} text - Just saying.
 */
MyApp.prototype.say = (text) => {
    return text;
};

module.exports = MyApp;
<|endoftext|>


<commit_before>//////////////////////////////////////////
// Needle -- Node.js HTTP Client
// Written by Tomás Pollak <tomas@forkhq.com>
// (c) 2012-2013 - Fork Ltd.
// MIT Licensed
//////////////////////////////////////////

var fs          = require('fs'),
    http        = require('http'),
    https       = require('https'),
    url         = require('url'),
    Readable    = require('stream').Readable,
    stringify   = require('qs').stringify,
    multipart   = require('./multipart'),
    auth        = require('./auth');

//////////////////////////////////////////
// variabilia
//////////////////////////////////////////

var version     = JSON.parse(fs.readFileSync(__dirname + '/../package.json').toString()).version,
    debugging   = !!process.env.DEBUG;

try { var unzip = require('zlib').unzip } catch(e) { /* unzip not supported */ }

var user_agent = 'Needle/' + version;
user_agent    += ' (Node.js ' + process.version + '; ' + process.platform + ' ' + process.arch + ')';

var node_tls_opts = 'agent pfx key passphrase cert ca ciphers rejectUnauthorized secureProtocol';

var debug = function(str, obj) {
  if (debugging)
    console.log(str, obj);
}

//////////////////////////////////////////
// content type parsers
//////////////////////////////////////////

var parsers = {
  'application/json': function(data, callback) {
    try {
      callback(null, data && JSON.parse(data));
    } catch(e) {
      callback(e, data);
    }
  }
};

try {
  var xml2js = require('xml2js');
  parsers['application/xml'] = function(data, callback) {
    var xml_parser = new xml2js.Parser({ explicitRoot: true, explicitArray: false });
    xml_parser.parseString(data, function(err, result) {
      callback(err, err ? data : result); // return original if err failed
    });
  };
  parsers['text/xml'] = parsers['application/xml'];
  parsers['application/rss+xml'] = parsers['application/xml'];
} catch(e) { /* xml2js not found */ }

//////////////////////////////////////////
// defaults
//////////////////////////////////////////

var defaults = {
  accept          : '*/*',
  connection      : 'close',
  user_agent      : user_agent,
  follow          : 0,
  decode_response : true,
  parse_response  : true,
  timeout         : 10000,
  encoding        : 'utf8',
  boundary        : '--------------------NODENEEDLEHTTPCLIENT'
}

//////////////////////////////////////////
// the main act
//////////////////////////////////////////

var Needle = {

  request: function(method, uri, data, options, callback) {

    var self     = this;
    var callback = (typeof options == 'function') ? options : callback;
    var options  = options || {};

    // if no 'http' is found on URL, prepend it
    if (uri.indexOf('http') == -1) uri = 'http://' + uri;

    var config = {
      base_opts       : {},
      proxy           : options.proxy,
      output          : options.output,
      encoding        : options.encoding || (options.multipart ? 'binary' : defaults.encoding),
      decode_response : options.decode === false ? false : defaults.decode_response,
      parse_response  : options.parse === false ? false : defaults.parse_response,
      follow          : options.follow === true ? 10 : typeof options.follow == 'number' ? options.follow : defaults.follow,
      timeout         : (typeof options.timeout == 'number') ? options.timeout : defaults.timeout
    }

    // if any of node's TLS options are passed, let them be passed to https.request()
    node_tls_opts.split(' ').forEach(function(key) {
      if (typeof options[key] != 'undefined') {
        config.base_opts[key] = options[key];
        if (typeof options.agent == 'undefined')
          config.base_opts.agent = false; // otherwise tls options are skipped
      }
    });

    config.headers = {
      'Accept'     : options.accept     || defaults.accept,
      'Connection' : options.connection || defaults.connection,
      'User-Agent' : options.user_agent || defaults.user_agent
    }

    if (options.compressed && typeof unzip != 'undefined')
      config.headers['Accept-Encoding'] = 'gzip,deflate';

    for (var h in options.headers)
      config.headers[h] = options.headers[h];

    if (options.username && options.password) {
      if (options.auth && (options.auth == 'auto' || options.auth == 'digest')) {
        config.credentials = [options.username, options.password];
      } else {
        var auth_header = options.proxy ? 'Proxy-Authorization' : 'Authorization';
        config.headers[auth_header] = auth.basic(options.username, options.password);
      }
    }

    if (data) {
      if (options.multipart) {
        var boundary = options.boundary || defaults.boundary;
        return multipart.build(data, boundary, function(err, body) {
          if (err) throw(err);
          config.headers['Content-Type'] = 'multipart/form-data; boundary=' + boundary;
          config.headers['Content-Length'] = body.length;
          self.send_request(1, method, uri, config, body, callback);
        });

      } else {
        var post_data = (typeof(data) === 'string') ? data :
            options.json ? JSON.stringify(data) : stringify(data);

        if (!config.headers['Content-Type']) {
          config.headers['Content-Type'] = options.json
          ? 'application/json'
          : 'application/x-www-form-urlencoded';
        }

        post_data = new Buffer(post_data, config.encoding)
        config.headers['Content-Length'] = post_data.length;
      }
    }

    return this.send_request(1, method, uri, config, post_data, callback);
  },

  get_request_opts: function(method, uri, config) {
    var opts      = config.base_opts, proxy = config.proxy;
    var remote    = proxy ? url.parse(proxy) : url.parse(uri);

    opts.protocol = remote.protocol;
    opts.host     = remote.hostname;
    opts.port     = remote.port || (remote.protocol == 'https:' ? 443 : 80);
    opts.path     = proxy ? uri : remote.pathname + (remote.search || '');
    opts.method   = method;
    opts.headers  = config.headers;
    opts.headers['Host'] = proxy ? url.parse(uri).hostname : remote.hostname;

    return opts;
  },

  get_auth_header: function(header, credentials, request_opts) {
    var type = header.split(' ')[0],
        user = credentials[0],
        pass = credentials[1];

    if (type == 'Digest') {
      return auth.digest(header, user, pass, request_opts.method, request_opts.path);
    } else if (type == 'Basic') {
      return auth.basic(user, pass);
    }
  },

  send_request: function(count, method, uri, config, post_data, callback) {

    var timer,
        self = this,
        request_opts = this.get_request_opts(method, uri, config),
        protocol = request_opts.protocol == 'https:' ? https : http;

    if (Readable && !config.out) {
      config.out = new Readable();
      config.out.on('error', function(er) { /* noop */ })
    }

    debug('Making request #' + count, request_opts);
    var request = protocol.request(request_opts, function(resp) {

      var headers = resp.headers;
      debug('Got response', headers);
      if (timer) clearTimeout(timer);

      // if redirect code is found, send a GET request to that location if enabled via 'follow' option
      if ([301, 302].indexOf(resp.statusCode) != -1 && headers.location) {
        if (count <= config.follow)
          return self.send_request(++count, 'GET', url.resolve(uri, headers.location), config, null, callback);
        else if (config.follow > 0)
          return callback(new Error('Max redirects reached. Possible loop in: ' + headers.location));
      }

      // if authentication is requested and credentials were not passed, resend request if we have user/pass
      if (resp.statusCode == 401 && headers['www-authenticate'] && config.credentials) {
        if (!config.headers['Authorization']) { // only if authentication hasn't been sent
          var auth_header = self.get_auth_header(headers['www-authenticate'], config.credentials, request_opts);

          if (auth_header) {
            config.headers['Authorization'] = auth_header;
            return self.send_request(count, method, uri, config, post_data, callback);
          }
        }
      }

      var chunks = [], length = 0,
          compressed = /gzip|deflate/.test(headers['content-encoding']),
          mime = self.parse_content_type(headers['content-type']);

      var response_opts = {
        output       : config.output,
        parse        : config.parse_response, // parse XML or JSON
        content_type : mime.type,
        text         : mime.type && mime.type.indexOf('text/') != -1,
        charset      : mime.charset
      }

      if (response_opts.text)
        response_opts.decode = config.decode_response; // only allow iconv decoding on text bodies

    // response.setEncoding(response_opts.utf8 ? 'utf8' : 'binary');

      resp.on('data', function(chunk) {
        chunks.push(chunk);
        if (config.out) config.out.push(chunk);
        length += chunk.length;
        // debug('Got ' + length + ' bytes.')
      });

      resp.on('end', function() {
        if (config.out) config.out.push(null); // close readable out stream

        // build the body by merging all the chunks we received
        var pos = 0;
        resp.bytes = length;
        resp.body  = new Buffer(resp.bytes);
        for (var i = 0, len = chunks.length; i < len; i++) {
          (new Buffer(chunks[i])).copy(resp.body, pos);
          pos += chunks[i].length;
        }

        // if no unzip support, or no deflated body requested, return
        if (!compressed || typeof unzip == 'undefined')
          return self.response_end(response_opts, resp, callback);

        unzip(resp.body, function(err, buff) {
          if (!err && buff) resp.body = buff; // only if no errors
          self.response_end(response_opts, resp, callback);
        });

      });

    });

    // unless timeout was disabled, set a timeout to abort the request
    if (config.timeout > 0) {
      timer = setTimeout(function() {
        request.abort();
      }, config.timeout)
    }

    request.on('error', function(err) {
      debug('Request error', err);
      if (timer) clearTimeout(timer);
      if (callback) callback(err || new Error('Unknown error when making request.'));
    });

    if (post_data) request.write(post_data, config.encoding);
    request.end();

    return config.out || request;
  },

  parse_content_type: function(header) {
    if (!header || header == '') return {};

    var charset = 'iso-8859-1', arr = header.split(';');
    try { charset = arr[1].match(/charset=(.+)/)[1] } catch (e) { /* not found */ }

    return { type: arr[0], charset: charset };
  },

  response_end: function(opts, resp, callback) {
    if (!callback) return; // no point in going ahead

    var handle_output = function(err, final) {
      if (final) resp.body = final;

      if (err || !opts.output || resp.statusCode != 200)
        return callback(err, resp, resp.body);

      // err is nil and output requested, so write to file
      fs.writeFile(opts.output, resp.body, function(e) {
        callback(e, resp, resp.body);
      })
    }

    // if there's a parser for the content type received, process it
    if (opts.parse && parsers[opts.content_type]) {
      parsers[opts.content_type](resp.body.toString(), handle_output);
    } else {
      // if charset is not UTF-8 and decode option is true, transmogrify it
      if (opts.decode && opts.charset && !opts.charset.match(/utf-?8$/i))
        resp.body = require('iconv-lite').decode(resp.body, opts.charset);

      handle_output(null, opts.text ? resp.body.toString() : resp.body);
    }

  }

}

exports.version = version;

exports.defaults = function(obj) {
  for (var key in obj) {
    if (defaults[key] && typeof obj[key] != 'undefined')
      defaults[key] = obj[key];
  }
  return defaults;
}

exports.head   = function(uri, options, callback) {
  return Needle.request('HEAD', uri, null, options, callback);
}

exports.get    = function(uri, options, callback) {
  return Needle.request('GET', uri, null, options, callback);
}

exports.post   = function(uri, data, options, callback) {
  return Needle.request('POST', uri, data, options, callback);
}

exports.put    = function(uri, data, options, callback) {
  return Needle.request('PUT', uri, data, options, callback);
}

exports.delete = function(uri, data, options, callback) {
  return Needle.request('DELETE', uri, data, options, callback);
}

exports.request = function(method, uri, data, opts, callback) {
  return Needle.request(method.toUpperCase(), uri, data, opts, callback);
};
<commit_msg>Include port in Host header when it's not the default.<commit_after>//////////////////////////////////////////
// Needle -- Node.js HTTP Client
// Written by Tomás Pollak <tomas@forkhq.com>
// (c) 2012-2013 - Fork Ltd.
// MIT Licensed
//////////////////////////////////////////

var fs          = require('fs'),
    http        = require('http'),
    https       = require('https'),
    url         = require('url'),
    Readable    = require('stream').Readable,
    stringify   = require('qs').stringify,
    multipart   = require('./multipart'),
    auth        = require('./auth');

//////////////////////////////////////////
// variabilia
//////////////////////////////////////////

var version     = JSON.parse(fs.readFileSync(__dirname + '/../package.json').toString()).version,
    debugging   = !!process.env.DEBUG;

try { var unzip = require('zlib').unzip } catch(e) { /* unzip not supported */ }

var user_agent = 'Needle/' + version;
user_agent    += ' (Node.js ' + process.version + '; ' + process.platform + ' ' + process.arch + ')';

var node_tls_opts = 'agent pfx key passphrase cert ca ciphers rejectUnauthorized secureProtocol';

var debug = function(str, obj) {
  if (debugging)
    console.log(str, obj);
}

//////////////////////////////////////////
// content type parsers
//////////////////////////////////////////

var parsers = {
  'application/json': function(data, callback) {
    try {
      callback(null, data && JSON.parse(data));
    } catch(e) {
      callback(e, data);
    }
  }
};

try {
  var xml2js = require('xml2js');
  parsers['application/xml'] = function(data, callback) {
    var xml_parser = new xml2js.Parser({ explicitRoot: true, explicitArray: false });
    xml_parser.parseString(data, function(err, result) {
      callback(err, err ? data : result); // return original if err failed
    });
  };
  parsers['text/xml'] = parsers['application/xml'];
  parsers['application/rss+xml'] = parsers['application/xml'];
} catch(e) { /* xml2js not found */ }

//////////////////////////////////////////
// defaults
//////////////////////////////////////////

var defaults = {
  accept          : '*/*',
  connection      : 'close',
  user_agent      : user_agent,
  follow          : 0,
  decode_response : true,
  parse_response  : true,
  timeout         : 10000,
  encoding        : 'utf8',
  boundary        : '--------------------NODENEEDLEHTTPCLIENT'
}

//////////////////////////////////////////
// the main act
//////////////////////////////////////////

var Needle = {

  request: function(method, uri, data, options, callback) {

    var self     = this;
    var callback = (typeof options == 'function') ? options : callback;
    var options  = options || {};

    // if no 'http' is found on URL, prepend it
    if (uri.indexOf('http') == -1) uri = 'http://' + uri;

    var config = {
      base_opts       : {},
      proxy           : options.proxy,
      output          : options.output,
      encoding        : options.encoding || (options.multipart ? 'binary' : defaults.encoding),
      decode_response : options.decode === false ? false : defaults.decode_response,
      parse_response  : options.parse === false ? false : defaults.parse_response,
      follow          : options.follow === true ? 10 : typeof options.follow == 'number' ? options.follow : defaults.follow,
      timeout         : (typeof options.timeout == 'number') ? options.timeout : defaults.timeout
    }

    // if any of node's TLS options are passed, let them be passed to https.request()
    node_tls_opts.split(' ').forEach(function(key) {
      if (typeof options[key] != 'undefined') {
        config.base_opts[key] = options[key];
        if (typeof options.agent == 'undefined')
          config.base_opts.agent = false; // otherwise tls options are skipped
      }
    });

    config.headers = {
      'Accept'     : options.accept     || defaults.accept,
      'Connection' : options.connection || defaults.connection,
      'User-Agent' : options.user_agent || defaults.user_agent
    }

    if (options.compressed && typeof unzip != 'undefined')
      config.headers['Accept-Encoding'] = 'gzip,deflate';

    for (var h in options.headers)
      config.headers[h] = options.headers[h];

    if (options.username && options.password) {
      if (options.auth && (options.auth == 'auto' || options.auth == 'digest')) {
        config.credentials = [options.username, options.password];
      } else {
        var auth_header = options.proxy ? 'Proxy-Authorization' : 'Authorization';
        config.headers[auth_header] = auth.basic(options.username, options.password);
      }
    }

    if (data) {
      if (options.multipart) {
        var boundary = options.boundary || defaults.boundary;
        return multipart.build(data, boundary, function(err, body) {
          if (err) throw(err);
          config.headers['Content-Type'] = 'multipart/form-data; boundary=' + boundary;
          config.headers['Content-Length'] = body.length;
          self.send_request(1, method, uri, config, body, callback);
        });

      } else {
        var post_data = (typeof(data) === 'string') ? data :
            options.json ? JSON.stringify(data) : stringify(data);

        if (!config.headers['Content-Type']) {
          config.headers['Content-Type'] = options.json
          ? 'application/json'
          : 'application/x-www-form-urlencoded';
        }

        post_data = new Buffer(post_data, config.encoding)
        config.headers['Content-Length'] = post_data.length;
      }
    }

    return this.send_request(1, method, uri, config, post_data, callback);
  },

  get_request_opts: function(method, uri, config) {
    var opts      = config.base_opts, proxy = config.proxy;
    var remote    = proxy ? url.parse(proxy) : url.parse(uri);

    opts.protocol = remote.protocol;
    opts.host     = remote.hostname;
    opts.port     = remote.port || (remote.protocol == 'https:' ? 443 : 80);
    opts.path     = proxy ? uri : remote.pathname + (remote.search || '');
    opts.method   = method;
    opts.headers  = config.headers;
    opts.headers['Host'] = proxy ? url.parse(uri).hostname : remote.hostname;
    if (opts.port != 80) opts.headers['Host'] += ':' + opts.port;

    return opts;
  },

  get_auth_header: function(header, credentials, request_opts) {
    var type = header.split(' ')[0],
        user = credentials[0],
        pass = credentials[1];

    if (type == 'Digest') {
      return auth.digest(header, user, pass, request_opts.method, request_opts.path);
    } else if (type == 'Basic') {
      return auth.basic(user, pass);
    }
  },

  send_request: function(count, method, uri, config, post_data, callback) {

    var timer,
        self = this,
        request_opts = this.get_request_opts(method, uri, config),
        protocol = request_opts.protocol == 'https:' ? https : http;

    if (Readable && !config.out) {
      config.out = new Readable();
      config.out.on('error', function(er) { /* noop */ })
    }

    debug('Making request #' + count, request_opts);
    var request = protocol.request(request_opts, function(resp) {

      var headers = resp.headers;
      debug('Got response', headers);
      if (timer) clearTimeout(timer);

      // if redirect code is found, send a GET request to that location if enabled via 'follow' option
      if ([301, 302].indexOf(resp.statusCode) != -1 && headers.location) {
        if (count <= config.follow)
          return self.send_request(++count, 'GET', url.resolve(uri, headers.location), config, null, callback);
        else if (config.follow > 0)
          return callback(new Error('Max redirects reached. Possible loop in: ' + headers.location));
      }

      // if authentication is requested and credentials were not passed, resend request if we have user/pass
      if (resp.statusCode == 401 && headers['www-authenticate'] && config.credentials) {
        if (!config.headers['Authorization']) { // only if authentication hasn't been sent
          var auth_header = self.get_auth_header(headers['www-authenticate'], config.credentials, request_opts);

          if (auth_header) {
            config.headers['Authorization'] = auth_header;
            return self.send_request(count, method, uri, config, post_data, callback);
          }
        }
      }

      var chunks = [], length = 0,
          compressed = /gzip|deflate/.test(headers['content-encoding']),
          mime = self.parse_content_type(headers['content-type']);

      var response_opts = {
        output       : config.output,
        parse        : config.parse_response, // parse XML or JSON
        content_type : mime.type,
        text         : mime.type && mime.type.indexOf('text/') != -1,
        charset      : mime.charset
      }

      if (response_opts.text)
        response_opts.decode = config.decode_response; // only allow iconv decoding on text bodies

    // response.setEncoding(response_opts.utf8 ? 'utf8' : 'binary');

      resp.on('data', function(chunk) {
        chunks.push(chunk);
        if (config.out) config.out.push(chunk);
        length += chunk.length;
        // debug('Got ' + length + ' bytes.')
      });

      resp.on('end', function() {
        if (config.out) config.out.push(null); // close readable out stream

        // build the body by merging all the chunks we received
        var pos = 0;
        resp.bytes = length;
        resp.body  = new Buffer(resp.bytes);
        for (var i = 0, len = chunks.length; i < len; i++) {
          (new Buffer(chunks[i])).copy(resp.body, pos);
          pos += chunks[i].length;
        }

        // if no unzip support, or no deflated body requested, return
        if (!compressed || typeof unzip == 'undefined')
          return self.response_end(response_opts, resp, callback);

        unzip(resp.body, function(err, buff) {
          if (!err && buff) resp.body = buff; // only if no errors
          self.response_end(response_opts, resp, callback);
        });

      });

    });

    // unless timeout was disabled, set a timeout to abort the request
    if (config.timeout > 0) {
      timer = setTimeout(function() {
        request.abort();
      }, config.timeout)
    }

    request.on('error', function(err) {
      debug('Request error', err);
      if (timer) clearTimeout(timer);
      if (callback) callback(err || new Error('Unknown error when making request.'));
    });

    if (post_data) request.write(post_data, config.encoding);
    request.end();

    return config.out || request;
  },

  parse_content_type: function(header) {
    if (!header || header == '') return {};

    var charset = 'iso-8859-1', arr = header.split(';');
    try { charset = arr[1].match(/charset=(.+)/)[1] } catch (e) { /* not found */ }

    return { type: arr[0], charset: charset };
  },

  response_end: function(opts, resp, callback) {
    if (!callback) return; // no point in going ahead

    var handle_output = function(err, final) {
      if (final) resp.body = final;

      if (err || !opts.output || resp.statusCode != 200)
        return callback(err, resp, resp.body);

      // err is nil and output requested, so write to file
      fs.writeFile(opts.output, resp.body, function(e) {
        callback(e, resp, resp.body);
      })
    }

    // if there's a parser for the content type received, process it
    if (opts.parse && parsers[opts.content_type]) {
      parsers[opts.content_type](resp.body.toString(), handle_output);
    } else {
      // if charset is not UTF-8 and decode option is true, transmogrify it
      if (opts.decode && opts.charset && !opts.charset.match(/utf-?8$/i))
        resp.body = require('iconv-lite').decode(resp.body, opts.charset);

      handle_output(null, opts.text ? resp.body.toString() : resp.body);
    }

  }

}

exports.version = version;

exports.defaults = function(obj) {
  for (var key in obj) {
    if (defaults[key] && typeof obj[key] != 'undefined')
      defaults[key] = obj[key];
  }
  return defaults;
}

exports.head   = function(uri, options, callback) {
  return Needle.request('HEAD', uri, null, options, callback);
}

exports.get    = function(uri, options, callback) {
  return Needle.request('GET', uri, null, options, callback);
}

exports.post   = function(uri, data, options, callback) {
  return Needle.request('POST', uri, data, options, callback);
}

exports.put    = function(uri, data, options, callback) {
  return Needle.request('PUT', uri, data, options, callback);
}

exports.delete = function(uri, data, options, callback) {
  return Needle.request('DELETE', uri, data, options, callback);
}

exports.request = function(method, uri, data, opts, callback) {
  return Needle.request(method.toUpperCase(), uri, data, opts, callback);
};
<|endoftext|>


<commit_before>import {
  EditorState,
  convertFromRaw,
  CompositeDecorator,
} from 'draft-js';

import Link, { findLinkEntities } from '../components/entities/link';

const decorator = new CompositeDecorator([
  {
    strategy: findLinkEntities,
    component: Link,
  },
]);

const createEditorState = (content = null, decorators = null) => {
  if (content === null) {
    return EditorState.createEmpty(decorator);
  }
  let dec = decorator;
  if (decorators !== null) {
    dec = decorators;
  }
  return EditorState.createWithContent(convertFromRaw(content), dec);
};

export default createEditorState;
<commit_msg>COde cleanup in medl. Use default arguments<commit_after>import {
  EditorState,
  convertFromRaw,
  CompositeDecorator,
} from 'draft-js';

import Link, { findLinkEntities } from '../components/entities/link';

const defaultDecorators = new CompositeDecorator([
  {
    strategy: findLinkEntities,
    component: Link,
  },
]);

const createEditorState = (content = null, decorators = defaultDecorators) => {
  if (content === null) {
    return EditorState.createEmpty(decorators);
  }
  return EditorState.createWithContent(convertFromRaw(content), decorators);
};

export default createEditorState;
<|endoftext|>


<commit_before>const injectSvg = require('svg-injector');

import { get } from '../util/utils.js';

class NicSvg {
    constructor(svgElem, jsonPath) {
        this.svgElem = svgElem;
        this.jsonPath = jsonPath;
    }

    svgToDom() {
        return injectSvg(document.getElementById(this.svgElem));
    }

    getJSON(url = this.jsonPath) {
      return get(url)
      .then(function() {
        return JSON.parse(url);
      })
      .catch(function(err) {
        console.log("getJSON failed for", url, err);
        throw err;
      });
    }

    build() {
      this.getJSON();
      this.svgToDom();
    }

}

export {NicSvg}
<commit_msg>getjson after the svg elem is render<commit_after>const injectSvg = require('svg-injector');

import { get } from '../utils/get.js';
import { dom } from '../utils/dom.js';

class NicSvg {

    constructor(svgElem, jsonPath) {
        this.svgElem = svgElem;
        this.jsonPath = jsonPath;
    }

    getJSON(url = this.jsonPath) {
      return get(url)
      .then(function(config) {
        return dom(JSON.parse(config));
      })
      .catch(function(err) {
        console.log("getJSON failed for", url, err);
        throw err;
      });
    }

    svgToDom() {
      let _this = this;
      return injectSvg(
              document.getElementById(this.svgElem),
              { evalScripts: 'once' },
              function () {
                // call getJSON once all the requested SVG elements have been injected.
                _this.getJSON();
              }
            );
    }

    build() {
      this.svgToDom();
    }

}

export {NicSvg}
<|endoftext|>


<commit_before>(function($) {
  var timeout;
  $.notice = function(message, options) {

    var animationOffset = '10px';
    var opts = $.extend({}, $.notice.defaults, options);
    var el;

    var close = function() {
      if (timeout) {
        clearTimeout(timeout);
      }

      if(opts.anchor === 'top') {
        $('.notice').animate({ opacity: 0, top: '-='+animationOffset }, {
          complete: function() {
            $(this).remove();
          }
        });
      } else {
        $('.notice').animate({ opacity: 0, bottom: '-='+animationOffset }, {
          complete: function() {
            $(this).remove();
          }
        });
      }
    };

    //close any open messages
    close();

    if (message == 'close') {
      return;
    }

    var container = $(opts.container);
    var containerOffset = container.offset();

    el = $(opts.template)
      .css({
        zIndex: opts.zIndex,
        overflow: 'hidden',
        position: 'fixed',
        padding: opts.padding,
        display: 'block',
        margin: '0 auto',
        opacity: 0,
        'border-radius': opts.borderRadius,
        'line-height': opts.height+'px',
        'text-align': 'center',
        background: opts.levels[opts.level].background,
        color: opts.levels[opts.level].foreground
      })
      .addClass((opts.level)?'notice-'+opts.level:false)
      .find('.notice-text')
        .html(message)
        .end()
      .find('.notice-close')
        .css({
          display: (opts.showClose) ? 'block' : 'none'
        })
        .on('click', function() {
          close();
        })
        .end()
      .appendTo(container);

    if(opts.anchor === 'top') {
      el.css({
        left: ((container.width() - el.width()) / 2) + containerOffset.left,
        top: (opts.offsetTop || containerOffset.top) - animationOffset
      })
      .animate({ opacity: 0.9, top: '+='+animationOffset });
    } else {
      el.css({
        left: ((container.width() - el.width()) / 2) + containerOffset.left,
        bottom: opts.offsetBottom - animationOffset
      })
      .animate({ opacity: 0.9, bottom: '+='+animationOffset });
    }

    if (typeof opts.timeout === 'number') {
      timeout = setTimeout(function() {
        close();
      }, opts.timeout);
    }

    return el;
  };

  $.notice.defaults = {
    //container to append notice to
    container: 'body',
    //template (shouldn't be changed)
    template: '

',
    //height of notice
    height: 30,
    //timeout before auto closing, set to false to disable auto close
    timeout: 5000,
    //level (info, success, error)
    level: 'info',
    //top offset for notice
    offsetTop: 0,
    offsetBottom: 0,
    anchor: 'top',
    zIndex: 1000,
    showClose: false,
    borderRadius: '10px',
    padding: '10px 20px 10px 20px',
    levels: {
      info: {
        background: '#333',
        foreground: '#fff'
      },
      success: {
        background: '#dff0d8',
        foreground: '#3d6c2a'
      },
      warning: {
        background: '#f9fad2',
        foreground: '#888b0f'
      },
      error: {
        background: '#f2dede',
        foreground: '#712d2d'
      }
    }

  };
})(window.jQuery || window.Zepto);
<commit_msg>Cleaned up bottom code.<commit_after>(function($) {
  var timeout;
  $.notice = function(message, options) {

    var animationOffset = '10px';
    var opts = $.extend({}, $.notice.defaults, options);
    var el;

    var close = function() {
      if (timeout) {
        clearTimeout(timeout);
      }

      var animateProps = {
        opacity: 0
      };

      if(opts.anchor === 'top') {
        animateProps.top = '-=' + animationOffset;
      } else {
        animateProps.bottom = '-=' + animationOffset;
      }

      $('.notice').animate(animateProps, {
        complete: function() {
          $(this).remove();
        }
      });
    };

    //close any open messages
    close();

    if (message == 'close') {
      return;
    }

    var container = $(opts.container);
    var containerOffset = container.offset();

    el = $(opts.template)
      .css({
        zIndex: opts.zIndex,
        overflow: 'hidden',
        position: 'fixed',
        padding: opts.padding,
        display: 'block',
        margin: '0 auto',
        opacity: 0,
        'border-radius': opts.borderRadius,
        'line-height': opts.height+'px',
        'text-align': 'center',
        background: opts.levels[opts.level].background,
        color: opts.levels[opts.level].foreground
      })
      .addClass((opts.level)?'notice-'+opts.level:false)
      .find('.notice-text')
        .html(message)
        .end()
      .find('.notice-close')
        .css({
          display: (opts.showClose) ? 'block' : 'none'
        })
        .on('click', function() {
          close();
        })
        .end()
      .appendTo(container);

    var alignment = {
      left: ((container.width() - el.width()) / 2) + containerOffset.left
    };

    var animateProps = {
      opacity: 0.9
    };

    if(opts.anchor === 'top') {
      alignment.top = (opts.offsetTop || containerOffset.top) - animationOffset;
      animateProps.top = '+=' + animationOffset;
    } else {
      alignment.bottom = opts.offsetBottom - animationOffset;
      animateProps.bottom = '+=' + (opts.offsetBottom + ~~animationOffset);
    }

    el.css(alignment)
      .animate(animateProps);

    if (typeof opts.timeout === 'number') {
      timeout = setTimeout(function() {
        close();
      }, opts.timeout);
    }

    return el;
  };

  $.notice.defaults = {
    //container to append notice to
    container: 'body',
    //template (shouldn't be changed)
    template: '

',
    //height of notice
    height: 30,
    //timeout before auto closing, set to false to disable auto close
    timeout: 5000,
    //level (info, success, error)
    level: 'info',
    //top offset for notice
    offsetTop: 0,
    offsetBottom: 0,
    anchor: 'top',
    zIndex: 1000,
    showClose: false,
    borderRadius: '10px',
    padding: '10px 20px 10px 20px',
    levels: {
      info: {
        background: '#333',
        foreground: '#fff'
      },
      success: {
        background: '#dff0d8',
        foreground: '#3d6c2a'
      },
      warning: {
        background: '#f9fad2',
        foreground: '#888b0f'
      },
      error: {
        background: '#f2dede',
        foreground: '#712d2d'
      }
    }

  };
})(window.jQuery || window.Zepto);
<|endoftext|>


<commit_before>var config = require('./config')

var logStack = []

module.exports = {
  log: function (message, data) {
    var isDebugMode = config.get('debug') == 'true'
    var hasConsole = window.console

    logStack.push({
      msg: message,
      data: data
    })

    if (isDebugMode && hasConsole) {
      window.console.log(message, data)
    }

  }
}
<commit_msg>Add method to get logStack from logger<commit_after>var config = require('./config')

var logStack = []

module.exports = {
  getLogStack: function () {
    return logStack
  },

  log: function (message, data) {
    var isDebugMode = config.get('debug') == 'true'
    var hasConsole = window.console

    logStack.push({
      msg: message,
      data: data
    })

    if (isDebugMode && hasConsole) {
      window.console.log(message, data)
    }

  }
}
<|endoftext|>


<commit_before>const mongoose = require('mongoose')
const middleware = require('./middleware/Format.js')

const fieldSchema = new mongoose.Schema({
  name: String,
  value: String,
  inline: Boolean
})

const embedSchema = new mongoose.Schema({
  title: String,
  description: String,
  url: String,
  color: Number,
  footerText: String,
  authorName: String,
  authorIconUrl: String,
  authorUrl: String,
  thumbnailUrl: String,
  imageUrl: String,
  timestamp: String,
  fields: [fieldSchema]
})

const schema = new mongoose.Schema({
  feed: mongoose.Types.ObjectId,
  text: String,
  embeds: [embedSchema]
})

fieldSchema.pre('validate', middleware.checkEmptyField)
embedSchema.pre('validate', middleware.checkEmptyEmbed)

exports.schema = schema
exports.model = mongoose.model('MessageFormat', schema)
<commit_msg>Fix Format model name<commit_after>const mongoose = require('mongoose')
const middleware = require('./middleware/Format.js')

const fieldSchema = new mongoose.Schema({
  name: String,
  value: String,
  inline: Boolean
})

const embedSchema = new mongoose.Schema({
  title: String,
  description: String,
  url: String,
  color: Number,
  footerText: String,
  authorName: String,
  authorIconUrl: String,
  authorUrl: String,
  thumbnailUrl: String,
  imageUrl: String,
  timestamp: String,
  fields: [fieldSchema]
})

const schema = new mongoose.Schema({
  feed: mongoose.Types.ObjectId,
  text: String,
  embeds: [embedSchema]
})

fieldSchema.pre('validate', middleware.checkEmptyField)
embedSchema.pre('validate', middleware.checkEmptyEmbed)

exports.schema = schema
exports.model = mongoose.model('Format', schema)
<|endoftext|>


<commit_before>function StateTransitionValidation() {
	this.state = 2;
	this.base = false;
}

StateTransitionValidation.prototype = {
	VALID: 1, // State transition is completely valid here.
	PARTIAL: 2, // State transition is not yet fully valid.
	CONFLICT: 3, // State transition conflicts with another transition here.
	INVALID: 4, // State transition is otherwise invalid.
	DUPLICATE: 5, // State transition already occurred here.
}

var StateTransition = {
	id: 0x00,
	rand: function() {
		return String.fromCharCode(
			Math.floor(Math.random() * 256),
			Math.floor(Math.random() * 256),
			Math.floor(Math.random() * 256),
			Math.floor(Math.random() * 256),
			Math.floor(Math.random() * 256),
			Math.floor(Math.random() * 256),
			Math.floor(Math.random() * 256),
			Math.floor(Math.random() * 256),
			Math.floor(Math.random() * 256),
			Math.floor(Math.random() * 256),
			Math.floor(Math.random() * 256),
			Math.floor(Math.random() * 256),
			Math.floor(Math.random() * 256),
			Math.floor(Math.random() * 256),
			Math.floor(Math.random() * 256)
			)
	},

	xor: function(b) {
		var a = this.id;
		var n = "";

		for (var i=0;i<a.length;i++) {
			n += String.fromCharCode(a.charCodeAt(i) ^ b.charCodeAt(i));
		}

		return n;
	},

	/*
		Apply this transition to the state object.
		Like setting unspent/spent outputs or storing metadata.

		THERE IS NO GUARANTEE OF ORDER OF APPLICATION, THAT SHOULD BE DONE BY VALIDATE
	*/
	apply: function(state) {

	},

	/*
		Can we apply the transition to this state (delta)?
	*/
	validate: function(state, validation) {
		if (!validation) {
			validation = new StateTransitionValidation(this)
			// store something, like how many inputs we still need
		}

		// validation.state should be changed if:
		//  1. we need no more inputs, or whatever, then VALID
		//     (by the way, we need to set the validation.base to this state)
		//  2. we still need inputs, so PARTIAL
		//  3. this transition occurs within the state already, so DUPLICATE
		//  4. this transition conflicts with a different transition, so CONFLICT
		//  5. this transition is invalid for some reason, so INVALID

		return validation;
	}
}

function ConsensusState(parent, transition) {
	if (transition)
		this.transitions = [transition]
	else
		this.transitions = []

	this.parent = parent;
	this.children = [];
	this._retain = 0;

	if (parent) {
		this.id = parent.id;
		parent.children.push(this)
		this.root = parent.root;
	} else {
		this.id = StateTransition.rand();
		this.root = this;
		this.shifts = {};
	}

	if (transition) {
		transition.apply(this)
		this.id = transition.xor(this.id)
	}
}

ConsensusState.prototype = {
	// returns a new state
	shift: function(transition, validation) {
		if (validation.state == validation.VALID) {
			// check the base object for cached transitions
			var n;

			if (validation.base.shifts[transition.xor(this.id)]) {
				n = validation.base.shifts[transition.xor(this.id)];
			} else {
				n = new ConsensusState(this, transition)

				// we need to cache this transition
				validation.base.shifts[transition.xor(this.id)] = n;

				// new child means we retain
				n.retain();
			}

			// retain our new state
			n.retain();

			// release ourselves
			this.release();

			return n;
		}
		return false;
	},
	validate: function(transition) {
		var cur = this;

		var validation = false; // store our validation state

		while (cur) {
			validation = transition.validate(cur, validation);

			switch (validation.state) {
				case validation.VALID:
				case validation.PARTIAL:
					// do nothing, continue up the chain
				break;
				case validation.CONFLICT:
				case validation.INVALID:
				case validation.DUPLICATE:
					return validation;
				break;
			}

			cur = cur.parent;
		}

		return validation;
	},
	retain: function() {
		this._retain++;
	},
	release: function() {
		this._retain--;

		if (this._retain == 0) {
			// We (may) serve as the parent for a number of child states in this.children
			// We should merge our state with all of our children

			// nothing will ever shift to this state
			delete this.root.shifts[this.id];

			this.children.forEach(function(child) {
				child.parent = this.parent;

				this.transitions.forEach(function(t) {
					t.apply(child) // apply parent transition to child state
				})
				child.transitions = this.transitions.concat(child.transitions)

				child.release();
			}, this)

			this.children = []
		}
	}
}

//////////////////////// INVENTORY STORAGE

function InventoryValidation(transition) {

}

InventoryValidation.prototype = new StateTransitionValidation();

function InventoryTransition(name, obj) {
	//this.name = name;
	//this.obj = obj;
	this.id = this.rand();

	this.apply = function(state) {
		if (typeof state.objs == "undefined") {
			state.objs = {};
		}

		state.objs[name] = obj;
	}

	this.validate = function(state, validation) {
		if (!validation) {
			validation = new InventoryValidation(this)
		}

		if (state.transitions.indexOf(this) != -1) {
			validation.state = validation.DUPLICATE;
		} else {
			validation.state = validation.VALID;
			validation.base = state.root; // TODO wtf
		}

		return validation;
	}
}

InventoryTransition.prototype = StateTransition;

var inv1 = new InventoryTransition("first", "test lol") // transaction 1
var inv2 = new InventoryTransition("second", "rofl lol") // transaction 2
var inv3 = new InventoryTransition("third", "POOP lol") // transaction 3

var root = new ConsensusState(false, false) // root state
var node1 = root;
var node2 = root; // same state
var node3 = root; // same state

node1.retain() // node 1 retains state
node2.retain() // node 2 retains state
node3.retain() // node 3 retains state

var val1 = node1.validate(inv1) // node 1 validates first transition
node1 = node1.shift(inv1, val1) // node 1 performs first transition

var val2 = node2.validate(inv2) // node 2 validates second transition
node2 = node2.shift(inv2, val2) // node 2 performs second transition

var val3 = node1.validate(inv2) // node 1 validates second transition
node1 = node1.shift(inv2, val3) // node 1 performs second transition

var val4 = node2.validate(inv1) // node 2 validates first transition
node2 = node2.shift(inv1, val4) // node 2 performs first transition

var val5 = node3.validate(inv2) // node 3 validates second transition
node3 = node3.shift(inv2, val5) // node 3 performs second transition

var val6 = node3.validate(inv3) // node 3 performs third transaction
node3 = node3.shift(inv3, val6) // node 3 performs third transaction

var val7 = node3.validate(inv1) // node 3 validates first transition
node3 = node3.shift(inv1, val7) // node 3 performs first transition

var val8 = node1.validate(inv3)
node1 = node1.shift(inv3, val8)

var val9 = node2.validate(inv3)
node2 = node2.shift(inv3, val9)

console.log(node1)
console.log(node2)
console.log(node3)
console.log("root: ")
console.log(root)
<commit_msg>refactor<commit_after>function StateTransitionValidation() {
	this.state = 2;
}

StateTransitionValidation.prototype = {
	VALID: 1, // State transition is completely valid here.
	PARTIAL: 2, // State transition is not yet fully valid.
	CONFLICT: 3, // State transition conflicts with another transition here.
	INVALID: 4, // State transition is otherwise invalid.
	DUPLICATE: 5, // State transition already occurred here.
}

var StateTransition = {
	id: 0x00,
	rand: function() {
		return String.fromCharCode(
			Math.floor(Math.random() * 256),
			Math.floor(Math.random() * 256),
			Math.floor(Math.random() * 256),
			Math.floor(Math.random() * 256),
			Math.floor(Math.random() * 256),
			Math.floor(Math.random() * 256),
			Math.floor(Math.random() * 256),
			Math.floor(Math.random() * 256),
			Math.floor(Math.random() * 256),
			Math.floor(Math.random() * 256),
			Math.floor(Math.random() * 256),
			Math.floor(Math.random() * 256),
			Math.floor(Math.random() * 256),
			Math.floor(Math.random() * 256),
			Math.floor(Math.random() * 256)
			)
	},

	xor: function(b) {
		var a = this.id;
		var n = "";

		for (var i=0;i<a.length;i++) {
			n += String.fromCharCode(a.charCodeAt(i) ^ b.charCodeAt(i));
		}

		return n;
	},

	/*
		Apply this transition to the state object.
		Like setting unspent/spent outputs or storing metadata.

		THERE IS NO GUARANTEE OF ORDER OF APPLICATION, THAT SHOULD BE DONE BY VALIDATE
	*/
	apply: function(state) {

	},

	/*
		Can we apply the transition to this state (delta)?
	*/
	validate: function(state, validation) {
		if (!validation) {
			validation = new StateTransitionValidation(this)
			// store something, like how many inputs we still need
		}

		// validation.state should be changed if:
		//  1. we need no more inputs, or whatever, then VALID
		//  2. we still need inputs, so PARTIAL
		//  3. this transition occurs within the state already, so DUPLICATE
		//  4. this transition conflicts with a different transition, so CONFLICT
		//  5. this transition is invalid for some reason, so INVALID

		return validation;
	}
}

function ConsensusState(parent, transition) {
	if (transition)
		this.transitions = [transition]
	else
		this.transitions = []

	this.parent = parent;
	this.children = [];
	this._retain = 0;

	if (parent) {
		this.id = parent.id;
		parent.children.push(this)
		this.root = parent.root;
	} else {
		this.id = StateTransition.rand();
		this.root = this;
		this.shifts = {};
	}

	if (transition) {
		transition.apply(this)
		this.id = transition.xor(this.id)
	}
}

ConsensusState.prototype = {
	// returns a new state
	shift: function(transition, validation) {
		if (validation.state == validation.VALID) {
			// check the base object for cached transitions
			var n;

			if (this.root.shifts[transition.xor(this.id)]) {
				n = this.root.shifts[transition.xor(this.id)];
			} else {
				n = new ConsensusState(this, transition)

				// we need to cache this transition
				this.root.shifts[transition.xor(this.id)] = n;

				// new child means we retain
				n.retain();
			}

			// retain our new state
			n.retain();

			// release ourselves
			this.release();

			return n;
		}
		return false;
	},
	validate: function(transition) {
		var cur = this;

		var validation = false; // store our validation state

		while (cur) {
			validation = transition.validate(cur, validation);

			switch (validation.state) {
				case validation.PARTIAL:
					// do nothing, continue up the chain
				break;
				case validation.VALID:
				case validation.CONFLICT:
				case validation.INVALID:
				case validation.DUPLICATE:
					return validation;
				break;
			}

			cur = cur.parent;
		}

		return validation;
	},
	retain: function() {
		this._retain++;
	},
	release: function() {
		this._retain--;

		if (this._retain == 0) {
			// We (may) serve as the parent for a number of child states in this.children
			// We should merge our state with all of our children

			// nothing will ever shift to this state
			delete this.root.shifts[this.id];

			this.children.forEach(function(child) {
				child.parent = this.parent;

				this.transitions.forEach(function(t) {
					t.apply(child) // apply parent transition to child state
				})
				child.transitions = this.transitions.concat(child.transitions)

				child.release();
			}, this)

			this.children = []
		}
	}
}

//////////////////////// INVENTORY STORAGE

function InventoryValidation(transition) {

}

InventoryValidation.prototype = new StateTransitionValidation();

function InventoryTransition(name, obj) {
	//this.name = name;
	//this.obj = obj;
	this.id = this.rand();

	this.apply = function(state) {
		if (typeof state.objs == "undefined") {
			state.objs = {};
		}

		state.objs[name] = obj;
	}

	this.validate = function(state, validation) {
		if (!validation) {
			validation = new InventoryValidation(this)
		}

		if (state.transitions.indexOf(this) != -1) {
			validation.state = validation.DUPLICATE;
		} else {
			validation.state = validation.VALID;
		}

		return validation;
	}
}

InventoryTransition.prototype = StateTransition;

var inv1 = new InventoryTransition("first", "test lol") // transaction 1
var inv2 = new InventoryTransition("second", "rofl lol") // transaction 2
var inv3 = new InventoryTransition("third", "POOP lol") // transaction 3

var root = new ConsensusState(false, false) // root state
var node1 = root;
var node2 = root; // same state
var node3 = root; // same state

node1.retain() // node 1 retains state
node2.retain() // node 2 retains state
node3.retain() // node 3 retains state

var val1 = node1.validate(inv1)
node1 = node1.shift(inv1, val1)

var val2 = node2.validate(inv2)
node2 = node2.shift(inv2, val2)

var val3 = node1.validate(inv2)
node1 = node1.shift(inv2, val3)

var val4 = node2.validate(inv1)
node2 = node2.shift(inv1, val4)

var val5 = node3.validate(inv2)
node3 = node3.shift(inv2, val5)

var val6 = node3.validate(inv3)
node3 = node3.shift(inv3, val6)

var val7 = node3.validate(inv1)
node3 = node3.shift(inv1, val7)

var val8 = node1.validate(inv3)
node1 = node1.shift(inv3, val8)

var val9 = node2.validate(inv3)
node2 = node2.shift(inv3, val9)

console.log(node1)
console.log(node2)
console.log(node3)
console.log("root: ")
console.log(root)<|endoftext|>