<commit_before>(function (window) {

  var doc = window.document
    , html = doc.documentElement
    , byClass = 'getElementsByClassName'
    , byTag = 'getElementsByTagName'
    , byId = 'getElementById'
    , byAll = 'querySelectorAll'
    , nodeType = 'nodeType'
    , idExp = /^#([\w\-]*)$/
    , classExp = /^\.([\w\-]*)$/
    , tagNameExp = /^(?:[\w\-]+|\*)$/
    , tagNameWithoutEndExp = /^[\w\-]+/
    , tagNameAndOrIdAndOrClassExp = /^([\w\-]+)(?:\#([\w\-]*)|)(?:\.([\w\-]*))(.*)$/
    , tagNameAttributeExp = /^([\w\-]+)(.*)\[([\w\-]+)(?:(\=|\|\=|\~\=|\$\=|\^\=)(.*)|)\]$/
    , splittersExp = /([\s\>\<\+\~]+)/
    , whitespaceExp = /\s/g
    , hasQsa = !!doc[byAll]
    , slice = [].slice
    , _cache = {};

  /**
   * Compare position of elements.
   * MIT Licensed, John Resig.
   *
   * @param {Object} a
   * @param {Object} b
   *
   * @return {Bool}
   */

  function comparePosition (a, b){
    return a.compareDocumentPosition ?
      a.compareDocumentPosition(b) :
      a.contains ?
        (a != b && a.contains(b) && 16) +
          (a != b && b.contains(a) && 8) +
          (a.sourceIndex >= 0 && b.sourceIndex >= 0 ?
            (a.sourceIndex < b.sourceIndex && 4) +
              (a.sourceIndex > b.sourceIndex && 2) :
            1) +
        0 :
        0;
  }

  /**
   * Compare string that it's the same.
   *
   * @return {Bool}
   */

  function compareString (a, b) {
    return a.toLowerCase() === b.toLowerCase();
  }

  /**
   * Simple way to cache objects.
   *
   * @return {Object}
   */

  function cache (sel, els, c) {
    return !c ? _cache[sel] || (_cache[sel] = els) : els;
  }

  /**
   * Each function.
   *
   * @param {Array} a
   * @param {Function} fn
   */

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

  /**
   * Filter array.
   *
   * @param {Array} a
   * @param {Function} fn
   *
   * @return {Array}
   */

  function filter (a, fn) {
    var res = [];
    each(a, function (x) {
      if (fn(x)) res.push(x);
    });
    return res;
  }

  /**
   * Find next element sibiling.
   *
   * @param {Object} el
   *
   * @return {Object}
   */

  function nextElementSibling (el) {
      if (el.nextElementSibling) {
        return el.nextElementSibling;
      } else {
        while (el = el.nextSibling) {
          if (el[nodeType] !== 1) return el;
        }
      }
  }

  /**
   * Find previous element sibling.
   *
   * @param {Object} el
   *
   * @return {Object}
   */

  function previousElementSibling (el) {
    if (el.previousElementSibling) {
      return el.previousElementSibling;
    } else {
      while (el = el.previousSibling) {
        if (el[nodeType] === 1) return el;
      }
    }
  }

  /**
   * Attribute selectors.
   *
   * Supported:
   *   =
   *   |=
   *   ~=
   *   $=
   *   ^=
   *
   * @param {Array} m
   * @param {Object} el
   *
   * @return {Bool}
   */

  function attributeSelectors (m, el) {
    var ret = false, val;

    switch (m[4]) {
      case '=':
        ret = el.getAttribute(m[3]) === m[5];
        break;
      case '|=':
        ret = (el.getAttribute(m[3]) || '').indexOf(m[5] + '-') !== -1;
        break;
      case '~=':
        ret = (el.getAttribute(m[3]) || '').indexOf(m[5]) !== -1;
        break;
      case '$=':
        val = (el.getAttribute(m[3]) || '');
        ret = val.lastIndexOf(m[5]) === val.length - m[5].length;
        break;
      case '^=':
        ret = (el.getAttribute(m[3]) || '').indexOf(m[5]) === 0;
    }

    return ret;
  }

  /**
   * Variation selectors.
   *
   * Supported:
   * - p + p
   * - p ~ p
   * - p > p
   *
   * @param {String} m
   * @param {Object} el
   * @param {Object} el2
   *
   * @return {Bool}
   */

  function variationSelectors (m) {
    var ret = false;

    return ret;
  }

  /**
   * Normalize context.
   *
   * @param {String|Array} ctx
   *
   * @return {Object}
   */

  function normalizeCtx (ctx) {
    if (!ctx) return doc;
    if (typeof ctx === 'string') return isa(ctx)[0];
    if (!ctx[nodeType] && ctx instanceof Array) return ctx[0];
    if (ctx[nodeType]) return ctx;
  }

  /**
   * Find elements by selectors.
   *
   * Supported:
   * - #foo
   * - .foo
   * - div (tagname)
   * - p, a (comma separated selectors)
   * - a[href]
   * - a.internal[href]
   * - a[href=name]
   * - a[href^=he]
   * - a[lang|=en]
   * - a[href~=te]
   * - a[href$=.com]
   * - div > p
   * - div < p
   * - p + p
   * - p ~ p
   *
   * @param {String} sel The selector string
   * @param {Object} ctx The context. Default is document.
   * @param {Bool} c Save to cache? Default is true.
   */

  function isa (sel, ctx, c) {
    var m, els = [];

    // Get the right context to use.
    ctx = normalizeCtx(ctx);

    // If the selector is cached, why not used that? So mutch faster.
    if ((els = cache[sel]) !== undefined) {
      return els;
    }

    if (sel.indexOf(',') !== -1) {
      // Comma separated selectors. E.g $('p, a');
      els = els || [];
      each(sel.split(','), function (a) {
        each(isa(a.replace(whitespaceExp, '')), function (el) {
          els.push(el);
        });
      });
      return els; //(!c ? cache(sel, els) : els);
    } else {
      if (idExp.test(sel)) {
        els = hasQsa ? ctx[byAll](sel.substr(1)) : ((els = ctx[byId](sel.substr(1))) ? [els] : []);
      } else if ((m = classExp.exec(sel)) && ctx[byClass] !== undefined) {
        els = hasQsa ? ctx[byAll](m[1]) : ctx[byClass](m[1]);
      } else if (tagNameExp.test(sel)) {
        els = hasQsa ? ctx[byAll](sel) : ctx[byTag](sel);
      } else if ((m = tagNameAndOrIdAndOrClassExp.exec(sel))) {
        var fr = m.length === 4;
        els = els || [];
        each(ctx[byTag](m[1]), function (el) {
          if ((fr && el.getAttribute('id') === m[2] && (el.getAttribute('class') || '').indexOf(m[3]) !== -1) ||
          (el.getAttribute('id') === m[2] || (el.getAttribute('class') || '').indexOf(m[3]) !== -1)) {
            if (m[4] !== undefined) {
              // build a function that walks all the way to the bottom om the "extra" selectors string.
            } else {
              els.push(el);
            }
          }
        });
      } else if ((m = tagNameAttributeExp.exec(sel))) {
        els = els || [];
        each(isa(m[1]), function (el) {
          if (m[2] !== '') {
            var r = isa(m[1] + m[2]);
            for (var i = 0, l = r.length; i < l; i++) {
              if (el === r[i] && el.hasAttribute(m[3]) && (m[4] !== undefined ? attributeSelectors(m, el) : true)) {
                els.push(el);
                break;
              }
            }
          } else if (el.hasAttribute(m[3]) && (m[4] !== undefined ? attributeSelectors(m, el) : true)) {
            els.push(el);
          }
        });
      } else if ((m = splittersExp.exec(sel))) {
        sel = m[1].length > 2 ? sel = sel.replace(whitespaceExp, '') : sel;
        m = m[1].length > 2 ? m[1].replace(whitespaceExp, '') : m[1];
        els = els || [];
        var sels = sel.split(m), el = isa(sels[0]), tagName = (tagNameWithoutEndExp.exec(sels[1]) || [])[0];
        if ((el = el[0])) {
          if (m === '~') {
            each(isa(sels[1]), function (nextEl) {
              if (nextEl.parentNode === el.parentNode &&
                compareString(nextEl.tagName, tagName) &&
                comparePosition(el, nextEl) & 0x04) {
                  els.push(nextEl);
                }
            });
          } else if (m === '+') {
            each(isa(sels[1]), function (nextEl) {
              if (nextElementSibling(el) === nextEl) {
                els.push(nextEl);
              }
            });
          } else if (m === '>' || m === '<') {
            each(isa(sels[1]), function (child) {
              if ((child.parentNode === el && compareString(child.tagName, tagName)) ||
                (child === el && compareString(child.tagName, el.tagName))) {
                els.push(m === '>' ? child : el);
              }
            });
          } else if (m === ' ') {
            each(isa(sels[0]), function (ctx) {
              els = els.concat(filter(isa(sels[1], ctx, true), function (el) {
                return el && el !== html && el.parentNode;
              }));
            });
          }
        }
      }

      return els; //(!c ? cache(sel, els) : els)
    }
  }

  // Add `isa` to window object.
  window.isa = isa;

})(window);<commit_msg>Added new version of isa.js<commit_after>(function (window) {

  var doc = window.document
    , html = doc.documentElement
    , byClass = 'getElementsByClassName'
    , byTag = 'getElementsByTagName'
    , byId = 'getElementById'
    , byAll = 'querySelectorAll'
    , nodeType = 'nodeType'
    , idExp = /^#([\w\-]*)$/
    , classExp = /^\.([\w\-]*)$/
    , tagNameExp = /^(?:[\w\-]+|\*)$/
    , tagNameWithoutEndExp = /^[\w\-]+/
    , tagNameAndOrIdAndOrClassExp = /^([\w\-]+)(?:\#([\w\-]*)|)(?:\.([\w\-]*))(.*)$/
    , tagNameAttributeExp = /^([\w\-]+)(.*)\[([\w\-]+)(?:(\=|\|\=|\~\=|\$\=|\^\=)(.*)|)\]$/
    , splittersExp = /([\s\>\\<\+\~]+)/
    , whitespaceExp = /\s/g
    , hasQsa = !!doc[byAll]
    , _cache = {};

  // Prototype references.
  var ArrayProto = Array.prototype;

  // Create reference for speeding up the access to the prototype.
  var slice = ArrayProto.slice
    , indexOf = ArrayProto.indexOf
    , lastIndexOf = ArrayProto.lastIndexOf;

  // Native functions that we are using.
  var nativeForEach = ArrayProto.forEach;

  /**
   * Compare position of elements.
   * MIT Licensed, John Resig.
   *
   * @param {Object} a
   * @param {Object} b
   *
   * @return {Bool}
   */

  function comparePosition (a, b){
    return a.compareDocumentPosition ?
      a.compareDocumentPosition(b) :
      a.contains ?
        (a != b && a.contains(b) && 16) +
          (a != b && b.contains(a) && 8) +
          (a.sourceIndex >= 0 && b.sourceIndex >= 0 ?
            (a.sourceIndex < b.sourceIndex && 4) +
              (a.sourceIndex > b.sourceIndex && 2) :
            1) +
        0 :
        0;
  }

  /**
   * Compare string that it's the same.
   *
   * @return {Bool}
   */

  function compareString (a, b) {
    return a.toLowerCase() === b.toLowerCase();
  }

  /**
   * Simple way to cache objects.
   *
   * @return {Object}
   */

  function cache (sel, els, c) {
    return !c ? _cache[sel] || (_cache[sel] = els) : els;
  }

  /**
   * Each function.
   *
   * @param {Array} a
   * @param {Function} fn
   */

  function each (a, fn) {
    if (nativeForEach && a.forEach === nativeForEach) {
      return a.forEach(fn);
    } else {
      var i = 0, l = a.length;
      for (; i < l; i++) fn(a[i]);
    }
  }

  /**
   * Filter array.
   *
   * @param {Array} a
   * @param {Function} fn
   *
   * @return {Array}
   */

  function filter (a, fn) {
    var res = [];
    each(a, function (x) {
      if (fn(x)) res.push(x);
    });
    return res;
  }

  /**
   * Find next element sibiling.
   *
   * @param {Object} el
   *
   * @return {Object}
   */

  function nextElementSibling (el) {
      if (el.nextElementSibling) {
        return el.nextElementSibling;
      } else {
        while (el = el.nextSibling) {
          if (el[nodeType] !== 1) return el;
        }
      }
  }

  /**
   * Find previous element sibling.
   *
   * @param {Object} el
   *
   * @return {Object}
   */

  function previousElementSibling (el) {
    if (el.previousElementSibling) {
      return el.previousElementSibling;
    } else {
      while (el = el.previousSibling) {
        if (el[nodeType] === 1) return el;
      }
    }
  }

  /**
   * Variation selectors.
   *
   * Supported:
   * - p + p
   * - p ~ p
   * - p > p
   *
   * @param {String} m
   * @param {Object} el
   * @param {Object} el2
   *
   * @return {Bool}
   */

  function variationSelectors (m) {
    var ret = false;

    return ret;
  }

  /**
   * Normalize context.
   *
   * @param {String|Array} ctx
   *
   * @return {Object}
   */

  function normalizeCtx (ctx) {
    if (!ctx) return doc;
    if (typeof ctx === 'string') return isa(ctx)[0];
    if (!ctx[nodeType] && ctx instanceof Array) return ctx[0];
    if (ctx[nodeType]) return ctx;
  }

  /**
   * Find elements by selectors.
   *
   * Supported:
   * - #foo
   * - .foo
   * - div (tagname)
   * - p, a (comma separated selectors)
   * - a[href]
   * - a.internal[href]
   * - a[href=name]
   * - a[href^=he]
   * - a[lang|=en]
   * - a[href~=te]
   * - a[href$=.com]
   * - div > p
   * - div < p
   * - p + p
   * - p ~ p
   *
   * @param {String} sel The selector string
   * @param {Object} ctx The context. Default is document.
   * @param {Bool} c Save to cache? Default is true.
   */

  function isa (sel, ctx) {
    var m, tmp, els = [];

    // Get the right context to use.
    ctx = normalizeCtx(ctx);

    // If the selector is cached, why not used that? So mutch faster.
    if ((els = cache[sel]) !== undefined) {
      return els;
    }

    if (sel.indexOf(',') !== -1) {
      // Comma separated selectors. E.g $('p, a');
      els = els || [];
      each(sel.split(','), function (a) {
        each(isa(a.replace(whitespaceExp, '')), function (el) {
          els.push(el);
        });
      });
      return els;
    } else {
      if (idExp.test(sel)) {
        els = hasQsa ? ctx[byAll](sel.substr(1)) : ((els = ctx[byId](sel.substr(1))) ? [els] : []);
      } else if ((m = classExp.exec(sel)) && ctx[byClass] !== undefined) {
        els = hasQsa ? ctx[byAll](m[1]) : ctx[byClass](m[1]);
      } else if (tagNameExp.test(sel)) {
        els = hasQsa ? ctx[byAll](sel) : ctx[byTag](sel);
      } else if ((m = tagNameAndOrIdAndOrClassExp.exec(sel))) {
        var fr = m.length === 4;
        els = els || [];
        each(ctx[byTag](m[1]), function (el) {
          if ((fr && el.getAttribute('id') === m[2] && indexOf.call((el.getAttribute('class') || ''), (m[3]) !== -1) ||
          (el.getAttribute('id') === m[2] || indexOf.call((el.getAttribute('class') || ''), m[3]) !== -1))) {
            if (m[4] !== undefined) {
              // build a function that walks all the way to the bottom om the "extra" selectors string.
            } else {
              els.push(el);
            }
          }
        });
      } else if ((m = tagNameAttributeExp.exec(sel))) {
        els = els || [];
        each(isa(m[1]), function (el) {
          if (m[2] !== '') {
            var r = isa(m[1] + m[2]);
            for (var i = 0, l = r.length; i < l; i++) {
              if (el === r[i] && el.hasAttribute(m[3]) && (m[4] !== undefined && isa.operators[m[4]] ? isa.operators[m[4]](m, el) : true)) {
                els.push(el);
                break;
              }
            }
          } else if (el.hasAttribute(m[3]) && (m[4] !== undefined && isa.operators[m[4]] ? isa.operators[m[4]](m, el) : true)) {
            els.push(el);
          }
        });
      } else if ((m = splittersExp.exec(sel))) {
        sel = m[1].length > 2 ? sel = sel.replace(whitespaceExp, '') : sel;
        m = m[1].length > 2 ? m[1].replace(whitespaceExp, '') : m[1];
        els = els || [];
        var sels = sel.split(m), el = isa(sels[0]), wantedTagName = (tagNameWithoutEndExp.exec(sels[1]) || [])[0];
        if ((el = el[0])) {
          if (m !== ' ' && isa.combinators[m] !== undefined) {
            each(isa(sels[1]), function (nextEl) {
              tmp = isa.combinators[m](el, nextEl, wantedTagName);
              if (tmp) els.push(tmp);
            });
          } else if (m === ' ') {
            each(isa(sels[0]), function (ctx) {
              els = els.concat(filter(isa(sels[1], ctx, true), function (el) {
                return el && el !== html && el.parentNode;
              }));
            });
          }
        }
      }

      return els;
    }
  }

  /**
   * isa operators selectors.
   */

  isa.operators = {
    '=': function (m, el) {
      return el.getAttribute(m[3]) === m[5];
    },

    '|=': function (m, el) {
      return indexOf.call((el.getAttribute(m[3]) || ''), m[5] + '-') !== -1;
    },

    '~=': function (m, el) {
      return indexOf.call((el.getAttribute(m[3]) || ''), m[5]) !== -1;
    },

    '$=': function (m, el) {
      var val  = (el.getAttribute(m[3]) || '');
      return lastIndexOf.call(val, m[5]) === val.length - m[5].length;
    },

    '^=': function (m, el) {
      return indexOf.call((el.getAttribute(m[3]) || ''), m[5]) === 0;
    }
  };

  /**
   * isa combinators selectors.
   */

   isa.combinators = {
     // p ~ p
     '~': function (el, nextEl, wantedTagName) {
       if (nextEl.parentNode === el.parentNode && compareString(nextEl.tagName, wantedTagName) && comparePosition(el, nextEl) & 0x04) {
         return el;
       }
     },

     // p + p
     '+': function (el, nextEl) {
       if (nextElementSibling(el) === nextEl) return el;
     },

     // div > p
     '>': function (el, nextEl, wantedTagName, m) {
       if ((nextEl.parentNode === el && compareString(nextEl.tagName, wantedTagName)) || (nextEl === el && compareString(nextEl.tagName, el.tagName))) {
         return m === '>' ? nextEl : el;
       }
     },

     // div < p
     '<': function (el, nextEl, wantedTagName) {
       return this['>'](el, nextEl, wantedTagName, '<');
     }
   };

  // Add `isa` to window object.
  window.isa = isa;

})(window);<|endoftext|>


<commit_before>let escapeTextForBrowser = require('react/lib/escapeTextForBrowser')

let each = (x, f) => Array.prototype.forEach.call(x, f)
let parse = (node, x) => JSON.parse(node.getAttribute(x))

class Iso {
  constructor() {
    this.html = []
    this.data = []
  }

  add(html, _state = {}, _meta = {}) {
    let state = escapeTextForBrowser(JSON.stringify(_state))
    let meta = escapeTextForBrowser(JSON.stringify(_meta))
    this.html.push(html)
    this.data.push({ state, meta })
    return this
  }

  render() {
    let markup = this.html.reduce((markup, html, i) => {
      return markup + `<div class="___iso-html___" data-key="${i}">${html}</div>`
    }, '')

    let data = this.data.reduce((nodes, data, i) => {
      let { state, meta } = data
      return nodes + `<div class="___iso-state___" data-key="${i}" data-meta="${meta}" data-state="${state}"></div>`
    }, '')

    return (
`
${markup}
${data}
`
    )
  }

  static render(html, state = {}, meta = {}) {
    return new Iso().add(html, state, meta).render()
  }

  static bootstrap(onNode) {
    if (!onNode) {
      return
    }

    let nodes = document.querySelectorAll('.___iso-html___')
    let state = document.querySelectorAll('.___iso-state___')

    let cache = {}

    each(state, (node) => {
      let meta = parse(node, 'data-meta')
      let state = parse(node, 'data-state')
      cache[node.getAttribute('data-key')] = { meta, state }
    })

    each(nodes, (node) => {
      let key = node.getAttribute('data-key')
      if (!cache[key]) {
        return
      }
      let { meta, state } = cache[key]
      onNode(state, meta, node)
    })

    cache = null
  }

  static on(metaKey, metaValue, onNode) {
    Iso.bootstrap((state, meta, node) => {
      if (meta[metaKey] && meta[metaKey] === metaValue) {
        onNode(state, meta, node)
      }
    })
  }
}

module.exports = Iso
<commit_msg>export syntax<commit_after>let escapeTextForBrowser = require('react/lib/escapeTextForBrowser')

let each = (x, f) => Array.prototype.forEach.call(x, f)
let parse = (node, x) => JSON.parse(node.getAttribute(x))

export default class Iso {
  constructor() {
    this.html = []
    this.data = []
  }

  add(html, _state = {}, _meta = {}) {
    let state = escapeTextForBrowser(JSON.stringify(_state))
    let meta = escapeTextForBrowser(JSON.stringify(_meta))
    this.html.push(html)
    this.data.push({ state, meta })
    return this
  }

  render() {
    let markup = this.html.reduce((markup, html, i) => {
      return markup + `<div class="___iso-html___" data-key="${i}">${html}</div>`
    }, '')

    let data = this.data.reduce((nodes, data, i) => {
      let { state, meta } = data
      return nodes + `<div class="___iso-state___" data-key="${i}" data-meta="${meta}" data-state="${state}"></div>`
    }, '')

    return (
`
${markup}
${data}
`
    )
  }

  static render(html, state = {}, meta = {}) {
    return new Iso().add(html, state, meta).render()
  }

  static bootstrap(onNode) {
    if (!onNode) {
      return
    }

    let nodes = document.querySelectorAll('.___iso-html___')
    let state = document.querySelectorAll('.___iso-state___')

    let cache = {}

    each(state, (node) => {
      let meta = parse(node, 'data-meta')
      let state = parse(node, 'data-state')
      cache[node.getAttribute('data-key')] = { meta, state }
    })

    each(nodes, (node) => {
      let key = node.getAttribute('data-key')
      if (!cache[key]) {
        return
      }
      let { meta, state } = cache[key]
      onNode(state, meta, node)
    })

    cache = null
  }

  static on(metaKey, metaValue, onNode) {
    Iso.bootstrap((state, meta, node) => {
      if (meta[metaKey] && meta[metaKey] === metaValue) {
        onNode(state, meta, node)
      }
    })
  }
}
<|endoftext|>


<commit_before>/**
 * @file
 * @author zdying
 */
var __hiipack = require('./global');
var express = require('express');
var path = require('path');
var fs = require('fs');
var fse = require('fs-extra');
var colors = require('colors');
var child_process = require('child_process');
var os = require('os');

var server = require('./server');
var client = require('./client');
var package = require('../package.json');
var program = global.program;

try{
    fse.copy(path.resolve(__hiipack__.root, 'tmpl', '_cache'), __hiipack__.tmpdir, function(err){
        if(err) console.error(err);
    });

    fse.copy(path.resolve(__hiipack__.root, 'tmpl', '_cache'), __hiipack__.tmpdirWithVersion, function(err){
        if(err) console.error(err);
    });
}catch(e){

}

// console.log('__hiipack__.root'.bold.magenta, '==>', __hiipack_root__);
// console.log('__hiipack__.cwd '.bold.magenta, '==>', __hiipack_cwd__);
// console.log(process.env.NODE_PATH);

program
    .version(package.version, '-v, --version')
    .option('-o, --open [open]', 'open in browser, one of: chrome|firefox|safari|opera', /^(chrome|firefox|safari|opera)$/)
    .option('-p, --port <port>', 'service port', 8800)
    .option('-r, --registry <registry>', 'npm registry address')
    .option('-d, --debug', 'print debug log')
    .option('-s, --syncConf <syncConf>', 'custom sync config')
    //TODO add this next version
    // .option('-U, --uglify', 'uglify javascript')
    //TODO add this next version
    // .option('-e, --extract-css', 'extract css from javascript')
    .option('-D, --detail', 'print debug and error detail log')
    // .option('-w, --workspace <workspace>', 'workspace', process.cwd())
    .option('-x, --proxy', 'start the proxy server')
    .option('-t, --type <type>', 'project type: one of react|react-redux|es6|vue|normal|empty', /^(react|react-redux|es6|vue|normal|empty)$/, 'normal')
    .option('--no-color', 'disable log color')
    .option('--no-hot-reload', 'disable hot reload')
    .option('--log-time', 'display log time')
    .option('--https', 'start https server');

program
    .command('init <name>')
    .description('initialize project')
    .action(function(name){
        client.init(name, program.type, program.registry);
    });

program
    .command('start')
    .description('create a local server')
    .action(function(){
        var browser = false;

        if(program.open){
            browser = typeof program.open === 'string' ? program.open : 'chrome';
        }

        server.start(program.port, browser, program.proxy);
    });

program
    .command('min')
    .description('compress/obfuscate project files')
    .action(function(){
        client.build();
    });

program
    .command('pack')
    .description('pack project files')
    .action(function(){
        client.pack();
    });

program
    .command('sync')
    .description('synchronize the current directory to remote server')
    .action(function(){
        client.sync(program.syncConf);
    });

program
    .command('test')
    .description('run unit test')
    .action(function(){
        client.test();
    });

program
    .command('clear')
    .description('clear resulting folders of hiipack')
    .action(function(){
        fse.remove('dev');
        fse.remove('prd');
        fse.remove('ver');
        fse.remove('loc');
        fse.remove('dll');
        // child_process.exec('rm -rdf dll loc dev prd ver')
    });

program
    .command('config [operation] [args...]')
    .description('hiipack config, `operation`: [empty]|list|set|delete')
    .action(function(ope, args, options){
        client.config(ope, args)
    });

program
    .command('ssl')
    .description('show ssl certificate file path.')
    .action(function(){
        console.log(path.resolve('./ssl/'));
    });

program.on('--help', function(){
    console.log('  Examples:');
    console.log('');
    console.log('    $ hii init project_name');
    console.log('    $ hii start');
    console.log('    $ hii start -p 8800');
    console.log('    $ hii pack');
    console.log('    $ hii sync');
    console.log('    $ hii min');
    console.log('');
    console.log('  Wiki:');
    console.log('');
    console.log('    https://github.com/zdying/hiipack/wiki/hiipack-%E4%BD%BF%E7%94%A8%E8%AF%B4%E6%98%8E');
});

program.parse(process.argv);

if(process.argv.length == 2){
    showVersion();
}

function showVersion(){
    var version = package.version.magenta;
    var versionLen = version.length;
    var spaces = new Array(25 - versionLen + 3).join(' ');

    // console.log('');
    // console.log('  .-----------------------------.');
    // console.log('  |  ' + 'hiipack'.bold + ' ' + version + spaces + '  |');
    // console.log('  |  ' + 'author ', 'zdying@live.com'.yellow.bold + '    |');
    // console.log('  |  ' + 'github.com/zdying/hiipack'.green.underline + '  |');
    // console.log('  \'-----------------------------\'');
    // console.log('');

    console.log("");
    console.log("                ,-.");
    console.log("      _,.      /  /");
    console.log("     ; \\____,-==-._  )     " + "hiipack".bold + "/" + version);
    console.log("     //_    `----' {+>     " + "zdying@live.com".bold.yellow);
    console.log("     `  `'--/  /-'`(       " + "github.com\/zdying".green.underline);
    console.log("           /  /");
    console.log("           `='");
    console.log("");
}
<commit_msg>fix bug<commit_after>/**
 * @file
 * @author zdying
 */
var __hiipack = require('./global');
var express = require('express');
var path = require('path');
var fs = require('fs');
var fse = require('fs-extra');
var colors = require('colors');
var child_process = require('child_process');
var os = require('os');

var server = require('./server');
var client = require('./client');
var package = require('../package.json');
var program = global.program;

try{
    fse.copy(path.resolve(__hiipack__.root, 'tmpl', '_cache'), __hiipack__.tmpdir, function(err){
        if(err) console.error(err);
    });

    fse.copy(path.resolve(__hiipack__.root, 'tmpl', '_cache'), __hiipack__.tmpdirWithVersion, function(err){
        if(err) console.error(err);
    });
}catch(e){

}

// console.log('__hiipack__.root'.bold.magenta, '==>', __hiipack_root__);
// console.log('__hiipack__.cwd '.bold.magenta, '==>', __hiipack_cwd__);
// console.log(process.env.NODE_PATH);

program
    .version(package.version, '-v, --version')
    .option('-o, --open [open]', 'open in browser, one of: chrome|firefox|safari|opera', /^(chrome|firefox|safari|opera)$/)
    .option('-p, --port <port>', 'service port', 8800)
    .option('-r, --registry <registry>', 'npm registry address')
    .option('-d, --debug', 'print debug log')
    .option('-s, --syncConf <syncConf>', 'custom sync config')
    //TODO add this next version
    // .option('-U, --uglify', 'uglify javascript')
    //TODO add this next version
    // .option('-e, --extract-css', 'extract css from javascript')
    .option('-D, --detail', 'print debug and error detail log')
    // .option('-w, --workspace <workspace>', 'workspace', process.cwd())
    .option('-x, --proxy', 'start the proxy server')
    .option('-t, --type <type>', 'project type: one of react|react-redux|es6|vue|normal|empty', /^(react|react-redux|es6|vue|normal|empty)$/, 'normal')
    .option('--no-color', 'disable log color')
    .option('--no-hot-reload', 'disable hot reload')
    .option('--log-time', 'display log time')
    .option('--https', 'start https server');

program
    .command('init <name>')
    .description('initialize project')
    .action(function(name){
        client.init(name, program.type, program.registry);
    });

program
    .command('start')
    .description('create a local server')
    .action(function(){
        var browser = false;

        if(program.open){
            browser = typeof program.open === 'string' ? program.open : 'chrome';
        }

        server.start(program.port, browser, program.proxy);
    });

program
    .command('min')
    .description('compress/obfuscate project files')
    .action(function(){
        client.build();
    });

program
    .command('pack')
    .description('pack project files')
    .action(function(){
        client.pack();
    });

program
    .command('sync')
    .description('synchronize the current directory to remote server')
    .action(function(){
        client.sync(program.syncConf);
    });

program
    .command('test')
    .description('run unit test')
    .action(function(){
        client.test();
    });

program
    .command('clear')
    .description('clear resulting folders of hiipack')
    .action(function(){
        fse.remove('dev');
        fse.remove('prd');
        fse.remove('ver');
        fse.remove('loc');
        fse.remove('dll');
        // child_process.exec('rm -rdf dll loc dev prd ver')
    });

program
    .command('config [operation] [args...]')
    .description('hiipack config, `operation`: [empty]|list|set|delete')
    .action(function(ope, args, options){
        client.config(ope, args)
    });

program
    .command('ssl')
    .description('show ssl certificate file path.')
    .action(function(){
        console.log(path.resolve(__dirname, './ssl/'));
    });

program.on('--help', function(){
    console.log('  Examples:');
    console.log('');
    console.log('    $ hii init project_name');
    console.log('    $ hii start');
    console.log('    $ hii start -p 8800');
    console.log('    $ hii pack');
    console.log('    $ hii sync');
    console.log('    $ hii min');
    console.log('');
    console.log('  Wiki:');
    console.log('');
    console.log('    https://github.com/zdying/hiipack/wiki/hiipack-%E4%BD%BF%E7%94%A8%E8%AF%B4%E6%98%8E');
});

program.parse(process.argv);

if(process.argv.length == 2){
    showVersion();
}

function showVersion(){
    var version = package.version.magenta;
    var versionLen = version.length;
    var spaces = new Array(25 - versionLen + 3).join(' ');

    // console.log('');
    // console.log('  .-----------------------------.');
    // console.log('  |  ' + 'hiipack'.bold + ' ' + version + spaces + '  |');
    // console.log('  |  ' + 'author ', 'zdying@live.com'.yellow.bold + '    |');
    // console.log('  |  ' + 'github.com/zdying/hiipack'.green.underline + '  |');
    // console.log('  \'-----------------------------\'');
    // console.log('');

    console.log("");
    console.log("                ,-.");
    console.log("      _,.      /  /");
    console.log("     ; \\____,-==-._  )     " + "hiipack".bold + "/" + version);
    console.log("     //_    `----' {+>     " + "zdying@live.com".bold.yellow);
    console.log("     `  `'--/  /-'`(       " + "github.com\/zdying".green.underline);
    console.log("           /  /");
    console.log("           `='");
    console.log("");
}
<|endoftext|>


<commit_before>/*
The MIT License (MIT)

Copyright (c) 2014 Shazron Abdullah

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
//jscs:disable maximumLineLength

var path = require('path'),
    fs = require('fs'),
    help = require('./help'),
    util = require('util');
var simctl;
var bplist;
var plist;

function findFirstAvailableDevice(list) {
    /*
        // Example result:
        {
            name : 'iPhone 6',
            id : 'A1193D97-F5EE-468D-9DBA-786F403766E6',
            runtime : 'iOS 8.3'
        }
    */

    // the object to return
    var ret_obj = {
        name: null,
        id: null,
        runtime: null
    };

    var available_runtimes = {};

    list.runtimes.forEach(function(runtime) {
        if (runtime.available) {
            available_runtimes[ runtime.name ] = true;
        }
    });

    list.devices.some(function(deviceGroup) {
        deviceGroup.devices.some(function(device) {
            if (available_runtimes[deviceGroup.runtime]) {
                ret_obj = {
                    name: device.name,
                    id: device.id,
                    runtime: deviceGroup.runtime
                };
                return true;
            }
            return false;
        });
        return false;
    });

    return ret_obj;
}

function findRuntimesGroupByDeviceProperty(list, deviceProperty, availableOnly) {
    /*
        // Example result:
        {
            "iPhone 6" : [ "iOS 8.2", "iOS 8.3"],
            "iPhone 6 Plus" : [ "iOS 8.2", "iOS 8.3"]
        }
    */

    var runtimes = {};
    var available_runtimes = {};

    list.runtimes.forEach(function(runtime) {
        if (runtime.available) {
            available_runtimes[ runtime.name ] = true;
        }
    });

    list.devices.forEach(function(deviceGroup) {
        deviceGroup.devices.forEach(function(device) {
            var devicePropertyValue = device[deviceProperty];

            if (!runtimes[devicePropertyValue]) {
                runtimes[devicePropertyValue] = [];
            }
            if (availableOnly) {
                if (available_runtimes[deviceGroup.runtime]) {
                    runtimes[devicePropertyValue].push(deviceGroup.runtime);
                }
            } else {
                runtimes[devicePropertyValue].push(deviceGroup.runtime);
            }
        });
    });

    return runtimes;
}

function findAvailableRuntime(list, device_name) {

    var all_druntimes = findRuntimesGroupByDeviceProperty(list, 'name', true);
    var druntime = all_druntimes[device_name];
    var runtime_found = druntime && druntime.length > 0;

    if (!runtime_found) {
        console.error(util.format('No available runtimes could be found for "%s".', device_name));
        process.exit(1);
    }

    // return most modern runtime
    return druntime.sort().pop();
}

function getDeviceFromDeviceTypeId(devicetypeid) {
    /*
        // Example result:
        {
            name : 'iPhone 6',
            id : 'A1193D97-F5EE-468D-9DBA-786F403766E6',
            runtime : 'iOS 8.3'
        }
    */

    // the object to return
    var ret_obj = {
        name: null,
        id: null,
        runtime: null
    };

    var options = { 'silent': true };
    var list = simctl.list(options).json;

    var arr = [];
    if (devicetypeid) {
        arr = devicetypeid.split(',');
    }

    // get the devicetype from --devicetypeid
    // --devicetypeid is a string in the form "devicetype, runtime_version" (optional: runtime_version)
    var devicetype = null;
    if (arr.length < 1) {
        var dv = findFirstAvailableDevice(list);
        console.error(util.format('--devicetypeid was not specified, using first available device: %s.', dv.name));
        return dv;
    } else {
        devicetype = arr[0].trim();
        if (arr.length > 1) {
            ret_obj.runtime = arr[1].trim();
        }
    }

    // check whether devicetype has the "com.apple.CoreSimulator.SimDeviceType." prefix, if not, add it
    var prefix = 'com.apple.CoreSimulator.SimDeviceType.';
    if (devicetype.indexOf(prefix) !== 0) {
        devicetype = prefix + devicetype;
    }

    // now find the devicename from the devicetype
    var devicename_found = list.devicetypes.some(function(deviceGroup) {
        if (deviceGroup.id === devicetype) {
            ret_obj.name = deviceGroup.name;
            return true;
        }

        return false;
    });

    // device name not found, exit
    if (!devicename_found) {
        console.error(util.format('Device type "%s" could not be found.', devicetype));
        process.exit(1);
    }

    // if runtime_version was not specified, we use a default. Use first available that has the device
    if (!ret_obj.runtime) {
        ret_obj.runtime = findAvailableRuntime(list, ret_obj.name);
    }

    // prepend iOS to runtime version, if necessary
    if (ret_obj.runtime.indexOf('iOS') === -1) {
        ret_obj.runtime = util.format('iOS %s', ret_obj.runtime);
    }

    // now find the deviceid (by runtime and devicename)
    var deviceid_found = list.devices.some(function(deviceGroup) {
        // found the runtime, now find the actual device matching devicename
        if (deviceGroup.runtime === ret_obj.runtime) {
            return deviceGroup.devices.some(function(device) {
                if (device.name === ret_obj.name) {
                    ret_obj.id = device.id;
                    return true;
                }
                return false;
            });
        }
        return false;
    });

    if (!deviceid_found) {
        console.error(
            util.format('Device id for device name "%s" and runtime "%s" could not be found, or is not available.', ret_obj.name, ret_obj.runtime)
        );
        process.exit(1);
    }

    return ret_obj;
}

var lib = {

    init: function() {
        if (!simctl) {
            simctl = require('simctl');
        }
        var output = simctl.check_prerequisites();
        if (output.code !== 0) {
            console.error(output.output);
            process.exit(2);
        }

        if (!bplist) {
            bplist = require('bplist-parser');
        }
    },

    //jscs:disable disallowUnusedParams
    showsdks: function(args) {
        var options = { silent: true, runtimes: true };
        var list = simctl.list(options).json;

        console.log('Simulator SDK Roots:');
        list.runtimes.forEach(function(runtime) {
            if (runtime.available) {
                console.log(util.format('"%s" (%s)', runtime.name, runtime.build));
                console.log(util.format('\t(unknown)'));
            }
        });
    },
    //jscs:enable disallowUnusedParams

    //jscs:disable disallowUnusedParams
    getdevicetypes: function(args) {
        var options = { silent: true };
        var list = simctl.list(options).json;

        var druntimes = findRuntimesGroupByDeviceProperty(list, 'name', true);
        var name_id_map = {};

        list.devicetypes.forEach(function(device) {
            name_id_map[ device.name ] = device.id;
        });

        list = [];
        var remove = function(runtime) {
            // remove "iOS" prefix in runtime, remove prefix "com.apple.CoreSimulator.SimDeviceType." in id
            list.push(util.format('%s, %s', name_id_map[ deviceName ].replace(/^com.apple.CoreSimulator.SimDeviceType./, ''), runtime.replace(/^iOS /, '')));
        };

        for (var deviceName in druntimes) {
            var runtimes = druntimes[ deviceName ];

            if (!(deviceName in name_id_map)) {
                continue;
            }
            runtimes.forEach(remove);
        }
        return list;
    },
    //jscs:enable disallowUnusedParams

    //jscs:disable disallowUnusedParams
    showdevicetypes: function(args) {
        var options = { silent: true };
        var list = simctl.list(options).json;

        var druntimes = findRuntimesGroupByDeviceProperty(list, 'name', true);
        var name_id_map = {};

        list.devicetypes.forEach(function(device) {
            // replace hyphens in iPad Pro name which differ in 'Device Types' and 'Devices'
            if (device.name.indexOf('iPad Pro') === 0) {
                device.name = device.name.replace(/\-/g, ' ').trim();
            }
            name_id_map[ device.name ] = device.id;
        });

        var remove = function(runtime) {
            // remove "iOS" prefix in runtime, remove prefix "com.apple.CoreSimulator.SimDeviceType." in id
            console.log(util.format('%s, %s', name_id_map[ deviceName ].replace(/^com.apple.CoreSimulator.SimDeviceType./, ''), runtime.replace(/^iOS /, '')));
        };

        for (var deviceName in druntimes) {
            var runtimes = druntimes[ deviceName ];

            // replace hyphens in iPad Pro name which differ in 'Device Types' and 'Devices'
            if (deviceName.indexOf('iPad Pro') === 0) {
                deviceName = deviceName.replace(/\-/g, ' ').trim();
            }

            if (!(deviceName in name_id_map)) {
                continue;
            }
            runtimes.forEach(remove);
        }
    },
    //jscs:enable disallowUnusedParams

    launch: function(app_path, devicetypeid, log, exit, argv) {
        var wait_for_debugger = false;
        var info_plist_path;
        var app_identifier;

        info_plist_path = path.join(app_path,'Info.plist');
        if (!fs.existsSync(info_plist_path)) {
            console.error(info_plist_path + ' file not found.');
            process.exit(1);
        }

        bplist.parseFile(info_plist_path, function(err, obj) {

            if (err) {
                // try to see if a regular plist parser will work
                if (!plist) {
                    plist = require('plist');
                }
                obj = plist.parse(fs.readFileSync(info_plist_path, 'utf8'));
                if (obj) {
                    app_identifier = obj.CFBundleIdentifier;
                } else {
                    throw err;
                }
            } else {
                app_identifier = obj[0].CFBundleIdentifier;
            }

            argv = argv || [];

            // get the deviceid from --devicetypeid
            // --devicetypeid is a string in the form "devicetype, runtime_version" (optional: runtime_version)
            var device = getDeviceFromDeviceTypeId(devicetypeid);

            // so now we have the deviceid, we can proceed
            simctl.extensions.start(device.id);
            simctl.install(device.id, app_path);
            simctl.launch(wait_for_debugger, device.id, app_identifier, argv);
            simctl.extensions.log(device.id, log);
            if (log) {
                console.log(util.format('logPath: %s', path.resolve(log)));
            }
            if (exit) {
                process.exit(0);
            }
        });
    },

    install: function(app_path, devicetypeid, log, exit) {
        var wait_for_debugger = false;
        var info_plist_path;
        var app_identifier;

        info_plist_path = path.join(app_path,'Info.plist');
        if (!fs.existsSync(info_plist_path)) {
            console.error(info_plist_path + ' file not found.');
            process.exit(1);
        }

        bplist.parseFile(info_plist_path, function(err, obj) {

            if (err) {
                throw err;
            }

            app_identifier = obj[0].CFBundleIdentifier;

            // get the deviceid from --devicetypeid
            // --devicetypeid is a string in the form "devicetype, runtime_version" (optional: runtime_version)
            var device = getDeviceFromDeviceTypeId(devicetypeid);

            // so now we have the deviceid, we can proceed
            simctl.extensions.start(device.id);
            simctl.install(device.id, app_path);

            simctl.extensions.log(device.id, log);
            if (log) {
                console.log(util.format('logPath: %s', path.resolve(log)));
            }
            if (exit) {
                process.exit(0);
            }
        });
    },

    start: function(devicetypeid) {
        var device = {};
        try {
            device = getDeviceFromDeviceTypeId(devicetypeid);
        } catch (e) {
            console.error(e);
        }

        simctl.extensions.start(device.id);
    }
};

module.exports = lib;
<commit_msg>Fixes #202 - ib.js/getdevicetypes gets wrong list of devices versus showdevicetypes<commit_after>/*
The MIT License (MIT)

Copyright (c) 2014 Shazron Abdullah

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
//jscs:disable maximumLineLength

var path = require('path'),
    fs = require('fs'),
    help = require('./help'),
    util = require('util');
var simctl;
var bplist;
var plist;

function findFirstAvailableDevice(list) {
    /*
        // Example result:
        {
            name : 'iPhone 6',
            id : 'A1193D97-F5EE-468D-9DBA-786F403766E6',
            runtime : 'iOS 8.3'
        }
    */

    // the object to return
    var ret_obj = {
        name: null,
        id: null,
        runtime: null
    };

    var available_runtimes = {};

    list.runtimes.forEach(function(runtime) {
        if (runtime.available) {
            available_runtimes[ runtime.name ] = true;
        }
    });

    list.devices.some(function(deviceGroup) {
        deviceGroup.devices.some(function(device) {
            if (available_runtimes[deviceGroup.runtime]) {
                ret_obj = {
                    name: device.name,
                    id: device.id,
                    runtime: deviceGroup.runtime
                };
                return true;
            }
            return false;
        });
        return false;
    });

    return ret_obj;
}

function findRuntimesGroupByDeviceProperty(list, deviceProperty, availableOnly) {
    /*
        // Example result:
        {
            "iPhone 6" : [ "iOS 8.2", "iOS 8.3"],
            "iPhone 6 Plus" : [ "iOS 8.2", "iOS 8.3"]
        }
    */

    var runtimes = {};
    var available_runtimes = {};

    list.runtimes.forEach(function(runtime) {
        if (runtime.available) {
            available_runtimes[ runtime.name ] = true;
        }
    });

    list.devices.forEach(function(deviceGroup) {
        deviceGroup.devices.forEach(function(device) {
            var devicePropertyValue = device[deviceProperty];

            if (!runtimes[devicePropertyValue]) {
                runtimes[devicePropertyValue] = [];
            }
            if (availableOnly) {
                if (available_runtimes[deviceGroup.runtime]) {
                    runtimes[devicePropertyValue].push(deviceGroup.runtime);
                }
            } else {
                runtimes[devicePropertyValue].push(deviceGroup.runtime);
            }
        });
    });

    return runtimes;
}

function findAvailableRuntime(list, device_name) {

    var all_druntimes = findRuntimesGroupByDeviceProperty(list, 'name', true);
    var druntime = all_druntimes[device_name];
    var runtime_found = druntime && druntime.length > 0;

    if (!runtime_found) {
        console.error(util.format('No available runtimes could be found for "%s".', device_name));
        process.exit(1);
    }

    // return most modern runtime
    return druntime.sort().pop();
}

function getDeviceFromDeviceTypeId(devicetypeid) {
    /*
        // Example result:
        {
            name : 'iPhone 6',
            id : 'A1193D97-F5EE-468D-9DBA-786F403766E6',
            runtime : 'iOS 8.3'
        }
    */

    // the object to return
    var ret_obj = {
        name: null,
        id: null,
        runtime: null
    };

    var options = { 'silent': true };
    var list = simctl.list(options).json;

    var arr = [];
    if (devicetypeid) {
        arr = devicetypeid.split(',');
    }

    // get the devicetype from --devicetypeid
    // --devicetypeid is a string in the form "devicetype, runtime_version" (optional: runtime_version)
    var devicetype = null;
    if (arr.length < 1) {
        var dv = findFirstAvailableDevice(list);
        console.error(util.format('--devicetypeid was not specified, using first available device: %s.', dv.name));
        return dv;
    } else {
        devicetype = arr[0].trim();
        if (arr.length > 1) {
            ret_obj.runtime = arr[1].trim();
        }
    }

    // check whether devicetype has the "com.apple.CoreSimulator.SimDeviceType." prefix, if not, add it
    var prefix = 'com.apple.CoreSimulator.SimDeviceType.';
    if (devicetype.indexOf(prefix) !== 0) {
        devicetype = prefix + devicetype;
    }

    // now find the devicename from the devicetype
    var devicename_found = list.devicetypes.some(function(deviceGroup) {
        if (deviceGroup.id === devicetype) {
            ret_obj.name = deviceGroup.name;
            return true;
        }

        return false;
    });

    // device name not found, exit
    if (!devicename_found) {
        console.error(util.format('Device type "%s" could not be found.', devicetype));
        process.exit(1);
    }

    // if runtime_version was not specified, we use a default. Use first available that has the device
    if (!ret_obj.runtime) {
        ret_obj.runtime = findAvailableRuntime(list, ret_obj.name);
    }

    // prepend iOS to runtime version, if necessary
    if (ret_obj.runtime.indexOf('iOS') === -1) {
        ret_obj.runtime = util.format('iOS %s', ret_obj.runtime);
    }

    // now find the deviceid (by runtime and devicename)
    var deviceid_found = list.devices.some(function(deviceGroup) {
        // found the runtime, now find the actual device matching devicename
        if (deviceGroup.runtime === ret_obj.runtime) {
            return deviceGroup.devices.some(function(device) {
                if (device.name === ret_obj.name) {
                    ret_obj.id = device.id;
                    return true;
                }
                return false;
            });
        }
        return false;
    });

    if (!deviceid_found) {
        console.error(
            util.format('Device id for device name "%s" and runtime "%s" could not be found, or is not available.', ret_obj.name, ret_obj.runtime)
        );
        process.exit(1);
    }

    return ret_obj;
}

var lib = {

    init: function() {
        if (!simctl) {
            simctl = require('simctl');
        }
        var output = simctl.check_prerequisites();
        if (output.code !== 0) {
            console.error(output.output);
            process.exit(2);
        }

        if (!bplist) {
            bplist = require('bplist-parser');
        }
    },

    //jscs:disable disallowUnusedParams
    showsdks: function(args) {
        var options = { silent: true, runtimes: true };
        var list = simctl.list(options).json;

        console.log('Simulator SDK Roots:');
        list.runtimes.forEach(function(runtime) {
            if (runtime.available) {
                console.log(util.format('"%s" (%s)', runtime.name, runtime.build));
                console.log(util.format('\t(unknown)'));
            }
        });
    },
    //jscs:enable disallowUnusedParams

    //jscs:disable disallowUnusedParams
    getdevicetypes: function(args) {
        var options = { silent: true };
        var list = simctl.list(options).json;

        var druntimes = findRuntimesGroupByDeviceProperty(list, 'name', true);
        var name_id_map = {};

        list.devicetypes.forEach(function(device) {
            // replace hyphens in iPad Pro name which differ in 'Device Types' and 'Devices'
            if (device.name.indexOf('iPad Pro') === 0) {
                device.name = device.name.replace(/\-/g, ' ').trim();
            }
            name_id_map[ device.name ] = device.id;
        });

        list = [];
        var remove = function(runtime) {
            // remove "iOS" prefix in runtime, remove prefix "com.apple.CoreSimulator.SimDeviceType." in id
            list.push(util.format('%s, %s', name_id_map[ deviceName ].replace(/^com.apple.CoreSimulator.SimDeviceType./, ''), runtime.replace(/^iOS /, '')));
        };

        for (var deviceName in druntimes) {
            var runtimes = druntimes[ deviceName ];

            // replace hyphens in iPad Pro name which differ in 'Device Types' and 'Devices'
            if (deviceName.indexOf('iPad Pro') === 0) {
                deviceName = deviceName.replace(/\-/g, ' ').trim();
            }

            if (!(deviceName in name_id_map)) {
                continue;
            }
            runtimes.forEach(remove);
        }
        return list;
    },
    //jscs:enable disallowUnusedParams

    //jscs:disable disallowUnusedParams
    showdevicetypes: function(args) {
        this.getdevicetypes().forEach(function(device){
            console.log(device);
        });
    },
    //jscs:enable disallowUnusedParams

    launch: function(app_path, devicetypeid, log, exit, argv) {
        var wait_for_debugger = false;
        var info_plist_path;
        var app_identifier;

        info_plist_path = path.join(app_path,'Info.plist');
        if (!fs.existsSync(info_plist_path)) {
            console.error(info_plist_path + ' file not found.');
            process.exit(1);
        }

        bplist.parseFile(info_plist_path, function(err, obj) {

            if (err) {
                // try to see if a regular plist parser will work
                if (!plist) {
                    plist = require('plist');
                }
                obj = plist.parse(fs.readFileSync(info_plist_path, 'utf8'));
                if (obj) {
                    app_identifier = obj.CFBundleIdentifier;
                } else {
                    throw err;
                }
            } else {
                app_identifier = obj[0].CFBundleIdentifier;
            }

            argv = argv || [];

            // get the deviceid from --devicetypeid
            // --devicetypeid is a string in the form "devicetype, runtime_version" (optional: runtime_version)
            var device = getDeviceFromDeviceTypeId(devicetypeid);

            // so now we have the deviceid, we can proceed
            simctl.extensions.start(device.id);
            simctl.install(device.id, app_path);
            simctl.launch(wait_for_debugger, device.id, app_identifier, argv);
            simctl.extensions.log(device.id, log);
            if (log) {
                console.log(util.format('logPath: %s', path.resolve(log)));
            }
            if (exit) {
                process.exit(0);
            }
        });
    },

    install: function(app_path, devicetypeid, log, exit) {
        var wait_for_debugger = false;
        var info_plist_path;
        var app_identifier;

        info_plist_path = path.join(app_path,'Info.plist');
        if (!fs.existsSync(info_plist_path)) {
            console.error(info_plist_path + ' file not found.');
            process.exit(1);
        }

        bplist.parseFile(info_plist_path, function(err, obj) {

            if (err) {
                throw err;
            }

            app_identifier = obj[0].CFBundleIdentifier;

            // get the deviceid from --devicetypeid
            // --devicetypeid is a string in the form "devicetype, runtime_version" (optional: runtime_version)
            var device = getDeviceFromDeviceTypeId(devicetypeid);

            // so now we have the deviceid, we can proceed
            simctl.extensions.start(device.id);
            simctl.install(device.id, app_path);

            simctl.extensions.log(device.id, log);
            if (log) {
                console.log(util.format('logPath: %s', path.resolve(log)));
            }
            if (exit) {
                process.exit(0);
            }
        });
    },

    start: function(devicetypeid) {
        var device = {};
        try {
            device = getDeviceFromDeviceTypeId(devicetypeid);
        } catch (e) {
            console.error(e);
        }

        simctl.extensions.start(device.id);
    }
};

module.exports = lib;
<|endoftext|>


<commit_before>// Extending JS array with top methor looking up the last member
Array.prototype.top = function () {
	return this[this.length - 1];
}

var ZERO = 48,
	NINE = 57,
	CAP_A = 65,
	CAP_Z = 90

var Calculator = function () {
	this.exprParser = new ExpressionParser();
};

var ExpressionParser = function (expr) {
	this.expression = expr;
	this.operatorStack = [];
	this.valueStack = [];

	// Accessors and modifiers
	this.setExpression = function (expr) {
		this.expression = expr;
	}

	// Public Methods
	this.parse = function () {
		var expr = this.expression.split(""),
			token,
			temp;
		while (expr.length) {
			token = expr.shift();
			temp = [];
			if (token === "(") {
				this.operatorStack.push("(");
			} else if (token === ")") {
				while (this.operatorStack.top() !== "(") {
					// Push a new node on the value stack
					this.valueStack.push(new ExpressionTree(this.operatorStack.pop(), this.valueStack.pop(), this.valueStack.pop()));
				}
				// remove the opening bracket
				this.operatorStack.pop();
			} else if (token.charCodeAt(0) >= ZERO && token.charCodeAt(0) <= NINE) {
				// Token is a number
				temp.push(token);
				while (expr.length && (expr[0].charCodeAt(0) >= ZERO && expr[0].charCodeAt(0) <= NINE) || expr[0] === ".") {
					temp.push(expr.shift());
				}
				this.valueStack.push(new ExpressionTree(parseFloat(temp.join(""))));
			} else if (token.charCodeAt(0) >= CAP_A && token.charCodeAt(0) <= CAP_Z) {
				// Token is a cell pointer
				temp.push(token);
				while (expr.length && (expr[0].charCodeAt(0) >= ZERO && expr[0].charCodeAt(0) <= NINE) || (expr[0].charCodeAt(0) >= CAP_A && expr[0].charCodeAt(0) <= CAP_Z)) {
					temp.push(expr.shift());
				}
				this.valueStack.push(new ExpressionTree(temp.join("")));
			} else if (token === "+" || token === "-" || token === "*" || token === "/") {
				while (this.operatorStack.length && ((this.operatorStack.top() === "*" || this.operatorStack.top() === "/") || (token === "+" || token === "-"))) {
					this.valueStack.push(new ExpressionTree(this.operatorStack.pop(), this.valueStack.pop(), this.valueStack.pop()));
				}
				this.operatorStack.push(token);
			}
		}
		while (this.operatorStack.length) {
			this.valueStack.push(new ExpressionTree(this.operatorStack.pop(), this.valueStack.pop(), this.valueStack.pop()));
		}
	}

	this.evaluate = function () {
		return this.valueStack[0].evaluate();
	}
}

var ExpressionTree = function (token, left, right) {
	if (arguments.length === 1) {
		this.value = token;
		this.left = this.right = this.operator = null;
	} else if (arguments.length === 3) {
		this.value = null;
		this.operator = token;
		this.left = left;
		this.right = right;
	}

	this.evaluate = function () {
		if (this.left && this.left.operator) {
			this.left.evaluate();
		}
		if (this.right && this.right.operator) {
			this.right.evaluate();
		}
		switch (this.operator) {
		case "+":
			this.value = this.left.value + this.right.value;
			break;
		case "-":
			this.value = this.left.value - this.right.value;
			break;
		case "*":
			this.value = this.left.value * this.right.value;
			break;
		case "/":
			this.value = this.left.value / this.right.value;
			break;
		default:
			break;
		}
		return this.value;
	}
}

<commit_msg>Adding some TODOs<commit_after>// Extending JS array with top methor looking up the last member
Array.prototype.top = function () {
	return this[this.length - 1];
}

var ZERO = 48,
	NINE = 57,
	CAP_A = 65,
	CAP_Z = 90

var Calculator = function () {
	this.exprParser = new ExpressionParser();
};

var ExpressionParser = function (expr) {
	this.expression = expr;
	this.operatorStack = [];
	this.valueStack = [];

	// Accessors and modifiers
	this.setExpression = function (expr) {
		this.expression = expr;
	}

	// Public Methods
	// Parsing a mathematical expression
	// TODO: 1. Add unary operator support like '-123', '10!', etc.
	// 		 2. The CAP_A through CAP_Z shoudl resolve the cell ptr inside the evaluate handler of the tree
	this.parse = function () {
		var expr = this.expression.split(""),
			token,
			temp;
		while (expr.length) {
			token = expr.shift();
			temp = [];
			if (token === "(") {
				this.operatorStack.push("(");
			} else if (token === ")") {
				while (this.operatorStack.top() !== "(") {
					// Push a new node on the value stack
					this.valueStack.push(new ExpressionTree(this.operatorStack.pop(), this.valueStack.pop(), this.valueStack.pop()));
				}
				// remove the opening bracket
				this.operatorStack.pop();
			} else if (token.charCodeAt(0) >= ZERO && token.charCodeAt(0) <= NINE) {
				// Token is a number
				temp.push(token);
				while (expr.length && (expr[0].charCodeAt(0) >= ZERO && expr[0].charCodeAt(0) <= NINE) || expr[0] === ".") {
					temp.push(expr.shift());
				}
				this.valueStack.push(new ExpressionTree(parseFloat(temp.join(""))));
			} else if (token.charCodeAt(0) >= CAP_A && token.charCodeAt(0) <= CAP_Z) {
				// Token is a cell pointer
				temp.push(token);
				while (expr.length && (expr[0].charCodeAt(0) >= ZERO && expr[0].charCodeAt(0) <= NINE) || (expr[0].charCodeAt(0) >= CAP_A && expr[0].charCodeAt(0) <= CAP_Z)) {
					temp.push(expr.shift());
				}
				this.valueStack.push(new ExpressionTree(temp.join("")));
			} else if (token === "+" || token === "-" || token === "*" || token === "/") {
				while (this.operatorStack.length && ((this.operatorStack.top() === "*" || this.operatorStack.top() === "/") || (token === "+" || token === "-"))) {
					this.valueStack.push(new ExpressionTree(this.operatorStack.pop(), this.valueStack.pop(), this.valueStack.pop()));
				}
				this.operatorStack.push(token);
			}
		}
		while (this.operatorStack.length) {
			this.valueStack.push(new ExpressionTree(this.operatorStack.pop(), this.valueStack.pop(), this.valueStack.pop()));
		}
	}

	this.evaluate = function () {
		return this.valueStack[0].evaluate();
	}
}

var ExpressionTree = function (token, left, right) {
	if (arguments.length === 1) {
		this.value = token;
		this.left = this.right = this.operator = null;
	} else if (arguments.length === 3) {
		this.value = null;
		this.operator = token;
		this.left = left;
		this.right = right;
	}

	this.evaluate = function () {
		if (this.left && this.left.operator) {
			this.left.evaluate();
		}
		if (this.right && this.right.operator) {
			this.right.evaluate();
		}
		switch (this.operator) {
		case "+":
			this.value = this.left.value + this.right.value;
			break;
		case "-":
			this.value = this.left.value - this.right.value;
			break;
		case "*":
			this.value = this.left.value * this.right.value;
			break;
		case "/":
			this.value = this.left.value / this.right.value;
			break;
		default:
			break;
		}
		return this.value;
	}
}

<|endoftext|>


<commit_before>const
    qs     = require('querystring'),
    crypto = require('crypto');

module.exports = (function () {

    function IPN ({merchantId, merchantSecret, rawBodyIndex='body'}) {
        if(!merchantId || !merchantSecret) {
            throw "Merchant ID and Merchant Secret are needed";
        }
        let hmac;

        let getPrivateHeadersIPN = function (parameters) {
            let signature;

            if(typeof parameters === "object") //if no rawBody provided, fallback to original usage.
                parameters = qs.stringify(parameters).replace(/%20/g, '+');

            signature = crypto.createHmac('sha512', merchantSecret).update(parameters).digest('hex');

            return signature;
        };

        return (req,res,next) => {
            if(!req.get('HMAC') || !req.body || !req.body.ipn_mode || req.body.ipn_mode !== 'hmac' || merchantId !== req.body.merchant) {
                return next("COINPAYMENTS_INVALID_REQUEST");
            }
            hmac = getPrivateHeadersIPN(req[rawBodyIndex]);
            if(hmac !== req.get('HMAC')) {
                return next("COINPAYMENTS_INVALID_REQUEST");
            }
            res.end();
            if(req.body.status < 0) {
                this.emit('ipn_fail', req.body);
                return next();
            }
            if(req.body.status < 100){
                this.emit('ipn_pending', req.body);
                return next();
            }
            if(req.body.status == 100) {
                this.emit('ipn_complete', req.body);
                return next();
            }
        }
    }

    return IPN;

})();
<commit_msg>Newline<commit_after>const
    qs     = require('querystring'),
    crypto = require('crypto');

module.exports = (function () {

    function IPN ({merchantId, merchantSecret, rawBodyIndex='body'}) {
        if(!merchantId || !merchantSecret) {
            throw "Merchant ID and Merchant Secret are needed";
        }
        let hmac;

        let getPrivateHeadersIPN = function (parameters) {
            let signature;

            if(typeof parameters === "object") //if no rawBody provided, fallback to original usage.
                parameters = qs.stringify(parameters).replace(/%20/g, '+');

            signature = crypto.createHmac('sha512', merchantSecret).update(parameters).digest('hex');

            return signature;
        };

        return (req,res,next) => {
            if(!req.get('HMAC') || !req.body || !req.body.ipn_mode || req.body.ipn_mode !== 'hmac' || merchantId !== req.body.merchant) {
                return next("COINPAYMENTS_INVALID_REQUEST");
            }
            hmac = getPrivateHeadersIPN(req[rawBodyIndex]);
            if(hmac !== req.get('HMAC')) {
                return next("COINPAYMENTS_INVALID_REQUEST");
            }
            res.end();
            if(req.body.status < 0) {
                this.emit('ipn_fail', req.body);
                return next();
            }
            if(req.body.status < 100){
                this.emit('ipn_pending', req.body);
                return next();
            }
            if(req.body.status == 100) {
                this.emit('ipn_complete', req.body);
                return next();
            }
        }
    }

    return IPN;

})();

<|endoftext|>


<commit_before>"use strict";

module.exports = function(config) {
    var fluid = require('infusion');
    var schemaHelper = require("../../schema/lib/schema-helper")(config);
    var paging = require("../lib/paging")(config);

    var namespace = "gpii.ctr.records";
    if (config.recordType) {
        if (config.recordType.toLowerCase() === "general") {
            namespace = "gpii.ctr.terms";
        }
        else if (config.recordType.toLowerCase() === "alias") {
            namespace = "gpii.ctr.aliases";
        }
        else if (config.recordType.toLowerCase() === "transform") {
            namespace = "gpii.ctr.transforms";
        }
        else if (config.recordType.toLowerCase() === "translation") {
            namespace = "gpii.ctr.translations";
        }
        else if (config.recordType.toLowerCase() === "operator") {
            namespace = "gpii.ctr.operators";
        }
        else {
            console.error("The record lookup API was configured to return an invalid record type '" + config.recordType + "'.  Ignoring this option, all records will be returned.");
        }
    }

    var records = fluid.registerNamespace(namespace);
    records.schema="records";

    var allowedRecordTypes = ["general","alias","transform","translation","operator"];

    var children = require('../lib/children')(config, records);
    var request = require('request');

    records.parseAndValidateInput = function() {
        if (!records.req.query) {
            throw records.constructError(400,"You must provide the required query parameters to use this interface.");
        }

        if (records.req.query.updated) {
            var parsedDate =  new Date(records.req.query.updated);
            if (parsedDate.toString() === "Invalid Date") {
                throw records.constructError(400, "Invalid 'updated' date specified: '" + records.req.query.updated + "'...");
            }
            else {
                records.params.updated = parsedDate;
            }
        }

        var allowedStatuses = ["active","unreviewed","candidate","deleted"];
        if (records.req.query.status) {
            var statusesToDisplay = [];
            if (records.req.query.status instanceof Array) {
                records.req.query.status.forEach(function(status){
                    var lowerCaseStatus = status.toLowerCase();
                    if (allowedStatuses.indexOf(lowerCaseStatus) === -1){
                        throw records.constructError(400,"Invalid status '" + lowerCaseStatus + "' specified...");
                    }
                    else {
                        statusesToDisplay.push(lowerCaseStatus);
                    }
                });
            }
            else {
                var lowerCaseStatus = records.req.query.status.toLowerCase();
                if (allowedStatuses.indexOf(lowerCaseStatus) === -1){
                     throw records.constructError(400,"Invalid status '" + lowerCaseStatus + "' specified...");
                }
                else {
                    statusesToDisplay.push(lowerCaseStatus);
                }
            }

            if (statusesToDisplay.length > 0) {
                records.params.statuses = statusesToDisplay;
            }
        }

        if (records.req.query.offset) {
            var parsedOffset = parseInt(records.req.query.offset);
            if (isNaN(parsedOffset)) {
                throw records.constructError(400,"Offset must be a number.");
            }
            else {
                records.params.offset = parsedOffset;
            }
        }

        if (records.req.query.limit) {
            var parsedLimit = parseInt(records.req.query.limit);
            if (isNaN(parsedLimit)) {
                throw records.constructError(400,"Limit must be a number.");
            }
            else {
                records.params.limit = parsedLimit;
            }
        }

        if (records.req.query.children) {
            records.params.children = JSON.parse(records.req.query.children);
        }

        if (config.recordType) {
            if (records.req.query.recordType) {
                throw records.constructError(400,"The 'recordType' parameter cannot be used with this interface.");
            }
            if (config.recordType !== "general" && records.req.query.children) {
                throw records.constructError(400,"The 'children' parameter can only be use with terms.");
            }

            var lowerCaseRecordType = config.recordType.toLowerCase();
            if (allowedRecordTypes.indexOf(lowerCaseRecordType) === -1) {
                throw records.constructError(400, "Invalid record type specified.");
            }
            else {
                records.params.recordTypes = [lowerCaseRecordType];
            }
        }
        else if (records.req.query.recordType) {
            var recordTypesToDisplay = [];
            if (records.req.query.recordType instanceof Array) {
                records.req.query.recordType.forEach(function(recordType){
                    var lowerCaseRecordType = recordType.toLowerCase();
                    if (allowedRecordTypes.indexOf(lowerCaseRecordType) === -1) {
                        throw records.constructError(400, "Invalid record type specified.");
                    }
                    else {
                        recordTypesToDisplay.push(lowerCaseRecordType);
                    }
                });
            }
            else {
                var lowerCaseRecordType = records.req.query.recordType.toLowerCase();
                if (allowedRecordTypes.indexOf(lowerCaseRecordType) === -1) {
                    throw records.constructError(400, "Invalid record type specified.");
                }
                else {
                    recordTypesToDisplay.push(lowerCaseRecordType);
                }
            }

            if (recordTypesToDisplay.length > 0) {
                records.params.recordTypes = recordTypesToDisplay;
            }
        }
    };

    records.getAndKnitTerms = function(error,response, body) {
        if (error) { return records.res.send(500, JSON.stringify(error)); }
        if (!body.rows) { return records.res.send(500,"No usable result object was returned from couch."); }

        var recordsByTermId = {};
        var excludedParentIds = [];

        body.rows.forEach(function(row) {
            var record = row.value;
            var isParent = row.key[1] === 0;
            var termId = row.key[0];

            if (isParent) {
                // Exclude records that are too old, the wrong status, or the wrong record type
                if ((records.params.updated && new Date(record.updated) < records.params.updated) ||
                    (records.params.statuses && records.params.statuses.indexOf(record.status.toLowerCase()) === -1) ||
                    (records.params.recordTypes && records.params.recordTypes.indexOf(record.type.toLowerCase()) === -1)) {
                    excludedParentIds.push(termId);
                }
                else {
                    recordsByTermId[termId] = record;
                }
            }
            else {
                var parentRecord = recordsByTermId[termId];
                if (excludedParentIds.indexOf(termId) !== -1 && parentRecord) {
                    var arrayName = "aliases";

                    if (record.type.toLowerCase() === "translation") {
                        arrayName = "translations";
                    }

                    if (!parentRecord[arrayName]) { parentRecord[arrayName] = []; }
                    parentRecord[arrayName].push(record);
                }
            }
        });

        var combinedRecords = Object.keys(recordsByTermId).map(function(key) { return recordsByTermId[key]; });
        records.results.total_rows = combinedRecords.length;

        records.results.records = paging.pageArray(combinedRecords, records.results);

        schemaHelper.setHeaders(records.res, "records");
        return records.res.send(200, JSON.stringify(records.results));
    };

    records.getRecords = function(error,response,body) {
        if (error) { return records.res.send(500, JSON.stringify(error)); }
        if (!body.rows) { return records.res.send(500,"No usable result object was returned from couch."); }

        var filteredRecords = [];
        body.rows.forEach(function(row) {
            var record = row.value;
            if ((!records.params.updated || new Date(record.updated) >= records.params.updated) &&
                (!records.params.statuses    || records.params.statuses.indexOf(record.status.toLowerCase()) !== -1) &&
                (!records.params.recordTypes || records.params.recordTypes.indexOf(record.type.toLowerCase()) !== -1)) {
                filteredRecords.push(record);
            }
        });

        records.results.records = paging.pageArray(filteredRecords, records.results);

        records.results.total_rows = filteredRecords.length;

        schemaHelper.setHeaders(records.res, "records");
        return records.res.send(200, JSON.stringify(records.results));
    };

    records.constructError = function(status, message) {
        var error = new Error(message);
        error.status = status;
        error.ok = false;
        return error;
    };

    var express = require('express');
    return express.Router().get('/', function(req, res){
        // per-request variables need to be defined here, otherwise (for example) the results of the previous search will be returned if the next search has no records
        records.params = {};
        records.req = req;
        records.res = res;
        schemaHelper.setHeaders(res, "message");

        records.results = {
            "ok": true,
            "total_rows" : 0,
            "records": [],
            "offset": records.req.query.offset ? parseInt(records.req.query.offset) : 0,
            "limit": records.req.query.limit ? parseInt(records.req.query.limit) : 100,
            "params": records.params,
            "retrievedAt": new Date()
        };

        // Server config validation
        if (!config || !config['couch.url']) {
            var message = "Your instance is not configured correctly to enable record lookup.  You must have a couch.url variable configured.";
            console.log(message);
            return res.send(500,JSON.stringify({ ok:false, message: message }));
        }

        // TODO:  Add support for versions

        // User input validation
        try {
            records.parseAndValidateInput();
        }
        catch(err) {
            return res.send(err.status ? err.status : 500, JSON.stringify(err));
        }

        var urlsByRecordType = {
            "entries":     config['couch.url'] + "/_design/api/_view/entries",
            "alias":       config['couch.url'] + "/_design/api/_view/aliases",
            "transform":   config['couch.url'] + "/_design/api/_view/transforms",
            "translation": config['couch.url'] + "/_design/api/_view/translations",
            "operator":    config['couch.url'] + "/_design/api/_view/operators",
            "general":     config['couch.url'] + "/_design/api/_view/flat"
        };

        var recordType = config.recordType ? config.recordType : "entries";

        var requestConfig = {
            url: urlsByRecordType[recordType],
            json: true
        };

        if ((recordType === "general" || recordType === "entries") && records.params.children) {
            // For terms, we need to put all the records together
            request.get(requestConfig,records.getParentRecords);
        }
        else {
            // For everything else, we can just call the view for the recordType
            request.get(requestConfig,records.getRecords);
        }
    });
};
<commit_msg>Added "TODO" note for cleaning up commonly used lookup variables.<commit_after>"use strict";

module.exports = function(config) {
    var fluid = require('infusion');
    var schemaHelper = require("../../schema/lib/schema-helper")(config);
    var paging = require("../lib/paging")(config);

    var namespace = "gpii.ctr.records";

    // TODO:  Move to a global vocabulary
    if (config.recordType) {
        if (config.recordType.toLowerCase() === "general") {
            namespace = "gpii.ctr.terms";
        }
        else if (config.recordType.toLowerCase() === "alias") {
            namespace = "gpii.ctr.aliases";
        }
        else if (config.recordType.toLowerCase() === "transform") {
            namespace = "gpii.ctr.transforms";
        }
        else if (config.recordType.toLowerCase() === "translation") {
            namespace = "gpii.ctr.translations";
        }
        else if (config.recordType.toLowerCase() === "operator") {
            namespace = "gpii.ctr.operators";
        }
        else {
            console.error("The record lookup API was configured to return an invalid record type '" + config.recordType + "'.  Ignoring this option, all records will be returned.");
        }
    }

    var records = fluid.registerNamespace(namespace);
    records.schema="records";

    var allowedRecordTypes = ["general","alias","transform","translation","operator"];

    var children = require('../lib/children')(config, records);
    var request = require('request');

    records.parseAndValidateInput = function() {
        if (!records.req.query) {
            throw records.constructError(400,"You must provide the required query parameters to use this interface.");
        }

        if (records.req.query.updated) {
            var parsedDate =  new Date(records.req.query.updated);
            if (parsedDate.toString() === "Invalid Date") {
                throw records.constructError(400, "Invalid 'updated' date specified: '" + records.req.query.updated + "'...");
            }
            else {
                records.params.updated = parsedDate;
            }
        }

        var allowedStatuses = ["active","unreviewed","candidate","deleted"];
        if (records.req.query.status) {
            var statusesToDisplay = [];
            if (records.req.query.status instanceof Array) {
                records.req.query.status.forEach(function(status){
                    var lowerCaseStatus = status.toLowerCase();
                    if (allowedStatuses.indexOf(lowerCaseStatus) === -1){
                        throw records.constructError(400,"Invalid status '" + lowerCaseStatus + "' specified...");
                    }
                    else {
                        statusesToDisplay.push(lowerCaseStatus);
                    }
                });
            }
            else {
                var lowerCaseStatus = records.req.query.status.toLowerCase();
                if (allowedStatuses.indexOf(lowerCaseStatus) === -1){
                     throw records.constructError(400,"Invalid status '" + lowerCaseStatus + "' specified...");
                }
                else {
                    statusesToDisplay.push(lowerCaseStatus);
                }
            }

            if (statusesToDisplay.length > 0) {
                records.params.statuses = statusesToDisplay;
            }
        }

        if (records.req.query.offset) {
            var parsedOffset = parseInt(records.req.query.offset);
            if (isNaN(parsedOffset)) {
                throw records.constructError(400,"Offset must be a number.");
            }
            else {
                records.params.offset = parsedOffset;
            }
        }

        if (records.req.query.limit) {
            var parsedLimit = parseInt(records.req.query.limit);
            if (isNaN(parsedLimit)) {
                throw records.constructError(400,"Limit must be a number.");
            }
            else {
                records.params.limit = parsedLimit;
            }
        }

        if (records.req.query.children) {
            records.params.children = JSON.parse(records.req.query.children);
        }

        if (config.recordType) {
            if (records.req.query.recordType) {
                throw records.constructError(400,"The 'recordType' parameter cannot be used with this interface.");
            }
            if (config.recordType !== "general" && records.req.query.children) {
                throw records.constructError(400,"The 'children' parameter can only be use with terms.");
            }

            var lowerCaseRecordType = config.recordType.toLowerCase();
            if (allowedRecordTypes.indexOf(lowerCaseRecordType) === -1) {
                throw records.constructError(400, "Invalid record type specified.");
            }
            else {
                records.params.recordTypes = [lowerCaseRecordType];
            }
        }
        else if (records.req.query.recordType) {
            var recordTypesToDisplay = [];
            if (records.req.query.recordType instanceof Array) {
                records.req.query.recordType.forEach(function(recordType){
                    var lowerCaseRecordType = recordType.toLowerCase();
                    if (allowedRecordTypes.indexOf(lowerCaseRecordType) === -1) {
                        throw records.constructError(400, "Invalid record type specified.");
                    }
                    else {
                        recordTypesToDisplay.push(lowerCaseRecordType);
                    }
                });
            }
            else {
                var lowerCaseRecordType = records.req.query.recordType.toLowerCase();
                if (allowedRecordTypes.indexOf(lowerCaseRecordType) === -1) {
                    throw records.constructError(400, "Invalid record type specified.");
                }
                else {
                    recordTypesToDisplay.push(lowerCaseRecordType);
                }
            }

            if (recordTypesToDisplay.length > 0) {
                records.params.recordTypes = recordTypesToDisplay;
            }
        }
    };

    records.getAndKnitTerms = function(error,response, body) {
        if (error) { return records.res.send(500, JSON.stringify(error)); }
        if (!body.rows) { return records.res.send(500,"No usable result object was returned from couch."); }

        var recordsByTermId = {};
        var excludedParentIds = [];

        body.rows.forEach(function(row) {
            var record = row.value;
            var isParent = row.key[1] === 0;
            var termId = row.key[0];

            if (isParent) {
                // Exclude records that are too old, the wrong status, or the wrong record type
                if ((records.params.updated && new Date(record.updated) < records.params.updated) ||
                    (records.params.statuses && records.params.statuses.indexOf(record.status.toLowerCase()) === -1) ||
                    (records.params.recordTypes && records.params.recordTypes.indexOf(record.type.toLowerCase()) === -1)) {
                    excludedParentIds.push(termId);
                }
                else {
                    recordsByTermId[termId] = record;
                }
            }
            else {
                var parentRecord = recordsByTermId[termId];
                if (excludedParentIds.indexOf(termId) !== -1 && parentRecord) {
                    var arrayName = "aliases";

                    if (record.type.toLowerCase() === "translation") {
                        arrayName = "translations";
                    }

                    if (!parentRecord[arrayName]) { parentRecord[arrayName] = []; }
                    parentRecord[arrayName].push(record);
                }
            }
        });

        var combinedRecords = Object.keys(recordsByTermId).map(function(key) { return recordsByTermId[key]; });
        records.results.total_rows = combinedRecords.length;

        records.results.records = paging.pageArray(combinedRecords, records.results);

        schemaHelper.setHeaders(records.res, "records");
        return records.res.send(200, JSON.stringify(records.results));
    };

    records.getRecords = function(error,response,body) {
        if (error) { return records.res.send(500, JSON.stringify(error)); }
        if (!body.rows) { return records.res.send(500,"No usable result object was returned from couch."); }

        var filteredRecords = [];
        body.rows.forEach(function(row) {
            var record = row.value;
            if ((!records.params.updated || new Date(record.updated) >= records.params.updated) &&
                (!records.params.statuses    || records.params.statuses.indexOf(record.status.toLowerCase()) !== -1) &&
                (!records.params.recordTypes || records.params.recordTypes.indexOf(record.type.toLowerCase()) !== -1)) {
                filteredRecords.push(record);
            }
        });

        records.results.records = paging.pageArray(filteredRecords, records.results);

        records.results.total_rows = filteredRecords.length;

        schemaHelper.setHeaders(records.res, "records");
        return records.res.send(200, JSON.stringify(records.results));
    };

    records.constructError = function(status, message) {
        var error = new Error(message);
        error.status = status;
        error.ok = false;
        return error;
    };

    var express = require('express');
    return express.Router().get('/', function(req, res){
        // per-request variables need to be defined here, otherwise (for example) the results of the previous search will be returned if the next search has no records
        records.params = {};
        records.req = req;
        records.res = res;
        schemaHelper.setHeaders(res, "message");

        records.results = {
            "ok": true,
            "total_rows" : 0,
            "records": [],
            "offset": records.req.query.offset ? parseInt(records.req.query.offset) : 0,
            "limit": records.req.query.limit ? parseInt(records.req.query.limit) : 100,
            "params": records.params,
            "retrievedAt": new Date()
        };

        // Server config validation
        if (!config || !config['couch.url']) {
            var message = "Your instance is not configured correctly to enable record lookup.  You must have a couch.url variable configured.";
            console.log(message);
            return res.send(500,JSON.stringify({ ok:false, message: message }));
        }

        // TODO:  Add support for versions

        // User input validation
        try {
            records.parseAndValidateInput();
        }
        catch(err) {
            return res.send(err.status ? err.status : 500, JSON.stringify(err));
        }

        var urlsByRecordType = {
            "entries":     config['couch.url'] + "/_design/api/_view/entries",
            "alias":       config['couch.url'] + "/_design/api/_view/aliases",
            "transform":   config['couch.url'] + "/_design/api/_view/transforms",
            "translation": config['couch.url'] + "/_design/api/_view/translations",
            "operator":    config['couch.url'] + "/_design/api/_view/operators",
            "general":     config['couch.url'] + "/_design/api/_view/flat"
        };

        var recordType = config.recordType ? config.recordType : "entries";

        var requestConfig = {
            url: urlsByRecordType[recordType],
            json: true
        };

        if ((recordType === "general" || recordType === "entries") && records.params.children) {
            // For terms, we need to put all the records together
            request.get(requestConfig,records.getParentRecords);
        }
        else {
            // For everything else, we can just call the view for the recordType
            request.get(requestConfig,records.getRecords);
        }
    });
};
<|endoftext|>