<commit_before>var RECYCLED_NODE = 1
var LAZY_NODE = 2
var TEXT_NODE = 3
var EMPTY_OBJ = {}
var EMPTY_ARR = []

var map = EMPTY_ARR.map
var isArray = Array.isArray
var defer = requestAnimationFrame || setTimeout

var createClass = function(obj) {
  var out = ""

  if (typeof obj === "string") return obj

  if (isArray(obj) && obj.length > 0) {
    for (var k = 0, tmp; k < obj.length; k++) {
      if ((tmp = createClass(obj[k])) !== "") {
        out += (out && " ") + tmp
      }
    }
  } else {
    for (var k in obj) {
      if (obj[k]) {
        out += (out && " ") + k
      }
    }
  }

  return out
}

var merge = function(a, b) {
  var out = {}

  for (var k in a) out[k] = a[k]
  for (var k in b) out[k] = b[k]

  return out
}

var batch = function(list) {
  return list.reduce(function(out, item) {
    return out.concat(
      !item || item === true
        ? false
        : typeof item[0] === "function"
        ? [item]
        : batch(item)
    )
  }, EMPTY_ARR)
}

var isSameAction = function(a, b) {
  return isArray(a) && isArray(b) && a[0] === b[0] && typeof a[0] === "function"
}

var shouldRestart = function(a, b) {
  for (var k in merge(a, b)) {
    if (a[k] !== b[k] && !isSameAction(a[k], b[k])) return true
    b[k] = a[k]
  }
}

var patchSubs = function(oldSubs, newSubs, dispatch) {
  for (
    var i = 0, oldSub, newSub, subs = [];
    i < oldSubs.length || i < newSubs.length;
    i++
  ) {
    oldSub = oldSubs[i]
    newSub = newSubs[i]
    subs.push(
      newSub
        ? !oldSub ||
          newSub[0] !== oldSub[0] ||
          shouldRestart(newSub[1], oldSub[1])
          ? [
              newSub[0],
              newSub[1],
              newSub[0](dispatch, newSub[1]),
              oldSub && oldSub[2]()
            ]
          : oldSub
        : oldSub && oldSub[2]()
    )
  }
  return subs
}

var patchProperty = function(node, key, oldValue, newValue, listener, isSvg) {
  if (key === "key") {
  } else if (key === "style") {
    for (var k in merge(oldValue, newValue)) {
      oldValue = newValue == null || newValue[k] == null ? "" : newValue[k]
      if (k[0] === "-") {
        node[key].setProperty(k, oldValue)
      } else {
        node[key][k] = oldValue
      }
    }
  } else if (key[0] === "o" && key[1] === "n") {
    if (
      !((node.actions || (node.actions = {}))[
        (key = key.slice(2).toLowerCase())
      ] = newValue)
    ) {
      node.removeEventListener(key, listener)
    } else if (!oldValue) {
      node.addEventListener(key, listener)
    }
  } else if (!isSvg && key !== "list" && key in node) {
    node[key] = newValue == null ? "" : newValue
  } else if (
    newValue == null ||
    newValue === false ||
    (key === "class" && !(newValue = createClass(newValue)))
  ) {
    node.removeAttribute(key)
  } else {
    node.setAttribute(key, newValue)
  }
}

var createNode = function(vnode, listener, isSvg) {
  var node =
    vnode.type === TEXT_NODE
      ? document.createTextNode(vnode.name)
      : (isSvg = isSvg || vnode.name === "svg")
      ? document.createElementNS("http://www.w3.org/2000/svg", vnode.name)
      : document.createElement(vnode.name)
  var props = vnode.props

  for (var k in props) {
    patchProperty(node, k, null, props[k], listener, isSvg)
  }

  for (var i = 0, len = vnode.children.length; i < len; i++) {
    node.appendChild(
      createNode(
        (vnode.children[i] = getVNode(vnode.children[i])),
        listener,
        isSvg
      )
    )
  }

  return (vnode.node = node)
}

var getKey = function(vnode) {
  return vnode == null ? null : vnode.key
}

var patch = function(parent, node, oldVNode, newVNode, listener, isSvg) {
  if (oldVNode === newVNode) {
  } else if (
    oldVNode != null &&
    oldVNode.type === TEXT_NODE &&
    newVNode.type === TEXT_NODE
  ) {
    if (oldVNode.name !== newVNode.name) node.nodeValue = newVNode.name
  } else if (oldVNode == null || oldVNode.name !== newVNode.name) {
    node = parent.insertBefore(
      createNode((newVNode = getVNode(newVNode)), listener, isSvg),
      node
    )
    if (oldVNode != null) parent.removeChild(oldVNode.node)
  } else {
    var tmpVKid
    var oldVKid

    var oldKey
    var newKey

    var oldVProps = oldVNode.props
    var newVProps = newVNode.props

    var oldVKids = oldVNode.children
    var newVKids = newVNode.children

    var oldHead = 0
    var newHead = 0
    var oldTail = oldVKids.length - 1
    var newTail = newVKids.length - 1

    isSvg = isSvg || newVNode.name === "svg"

    for (var i in merge(oldVProps, newVProps)) {
      if (
        (i === "value" || i === "selected" || i === "checked"
          ? node[i]
          : oldVProps[i]) !== newVProps[i]
      ) {
        patchProperty(node, i, oldVProps[i], newVProps[i], listener, isSvg)
      }
    }

    while (newHead <= newTail && oldHead <= oldTail) {
      if (
        (oldKey = getKey(oldVKids[oldHead])) == null ||
        oldKey !== getKey(newVKids[newHead])
      ) {
        break
      }

      patch(
        node,
        oldVKids[oldHead].node,
        oldVKids[oldHead],
        (newVKids[newHead] = getVNode(
          newVKids[newHead++],
          oldVKids[oldHead++]
        )),
        listener,
        isSvg
      )
    }

    while (newHead <= newTail && oldHead <= oldTail) {
      if (
        (oldKey = getKey(oldVKids[oldTail])) == null ||
        oldKey !== getKey(newVKids[newTail])
      ) {
        break
      }

      patch(
        node,
        oldVKids[oldTail].node,
        oldVKids[oldTail],
        (newVKids[newTail] = getVNode(
          newVKids[newTail--],
          oldVKids[oldTail--]
        )),
        listener,
        isSvg
      )
    }

    if (oldHead > oldTail) {
      while (newHead <= newTail) {
        node.insertBefore(
          createNode(
            (newVKids[newHead] = getVNode(newVKids[newHead++])),
            listener,
            isSvg
          ),
          (oldVKid = oldVKids[oldHead]) && oldVKid.node
        )
      }
    } else if (newHead > newTail) {
      while (oldHead <= oldTail) {
        node.removeChild(oldVKids[oldHead++].node)
      }
    } else {
      for (var i = oldHead, keyed = {}, newKeyed = {}; i <= oldTail; i++) {
        if ((oldKey = oldVKids[i].key) != null) {
          keyed[oldKey] = oldVKids[i]
        }
      }

      while (newHead <= newTail) {
        oldKey = getKey((oldVKid = oldVKids[oldHead]))
        newKey = getKey(
          (newVKids[newHead] = getVNode(newVKids[newHead], oldVKid))
        )

        if (
          newKeyed[oldKey] ||
          (newKey != null && newKey === getKey(oldVKids[oldHead + 1]))
        ) {
          if (oldKey == null) {
            node.removeChild(oldVKid.node)
          }
          oldHead++
          continue
        }

        if (newKey == null || oldVNode.type === RECYCLED_NODE) {
          if (oldKey == null) {
            patch(
              node,
              oldVKid && oldVKid.node,
              oldVKid,
              newVKids[newHead],
              listener,
              isSvg
            )
            newHead++
          }
          oldHead++
        } else {
          if (oldKey === newKey) {
            patch(
              node,
              oldVKid.node,
              oldVKid,
              newVKids[newHead],
              listener,
              isSvg
            )
            newKeyed[newKey] = true
            oldHead++
          } else {
            if ((tmpVKid = keyed[newKey]) != null) {
              patch(
                node,
                node.insertBefore(tmpVKid.node, oldVKid && oldVKid.node),
                tmpVKid,
                newVKids[newHead],
                listener,
                isSvg
              )
              newKeyed[newKey] = true
            } else {
              patch(
                node,
                oldVKid && oldVKid.node,
                null,
                newVKids[newHead],
                listener,
                isSvg
              )
            }
          }
          newHead++
        }
      }

      while (oldHead <= oldTail) {
        if (getKey((oldVKid = oldVKids[oldHead++])) == null) {
          node.removeChild(oldVKid.node)
        }
      }

      for (var i in keyed) {
        if (newKeyed[i] == null) {
          node.removeChild(keyed[i].node)
        }
      }
    }
  }

  return (newVNode.node = node)
}

var propsChanged = function(a, b) {
  for (var k in a) if (a[k] !== b[k]) return true
  for (var k in b) if (a[k] !== b[k]) return true
}

var getVNode = function(newVNode, oldVNode) {
  return newVNode.type === LAZY_NODE
    ? ((!oldVNode || propsChanged(oldVNode.lazy, newVNode.lazy)) &&
        ((oldVNode = newVNode.lazy.view(newVNode.lazy)).lazy = newVNode.lazy),
      oldVNode)
    : newVNode
}

var createVNode = function(name, props, children, node, key, type) {
  return {
    name: name,
    props: props,
    children: children,
    node: node,
    type: type,
    key: key
  }
}

var createTextVNode = function(value, node) {
  return createVNode(value, EMPTY_OBJ, EMPTY_ARR, node, null, TEXT_NODE)
}

var recycleNode = function(node) {
  return node.nodeType === TEXT_NODE
    ? createTextVNode(node.nodeValue, node)
    : createVNode(
        node.nodeName.toLowerCase(),
        EMPTY_OBJ,
        map.call(node.childNodes, recycleNode),
        node,
        null,
        RECYCLED_NODE
      )
}

export var Lazy = function(props) {
  return {
    lazy: props,
    type: LAZY_NODE
  }
}

export var h = function(name, props) {
  for (var vnode, rest = [], children = [], i = arguments.length; i-- > 2; ) {
    rest.push(arguments[i])
  }

  while (rest.length > 0) {
    if (isArray((vnode = rest.pop()))) {
      for (var i = vnode.length; i-- > 0; ) {
        rest.push(vnode[i])
      }
    } else if (vnode === false || vnode === true || vnode == null) {
    } else {
      children.push(typeof vnode === "object" ? vnode : createTextVNode(vnode))
    }
  }

  props = props || EMPTY_OBJ

  return typeof name === "function"
    ? name(props, children)
    : createVNode(name, props, children, null, props.key)
}

export var app = function(props, enhance) {
  var state = {}
  var lock = false
  var view = props.view
  var node = props.node
  var vdom = node && recycleNode(node)
  var subscriptions = props.subscriptions
  var subs = []

  var listener = function(event) {
    dispatch(this.actions[event.type], event)
  }

  var setState = function(newState) {
    return (
      state === newState || lock || defer(render, (lock = true)),
      (state = newState)
    )
  }

  var dispatch = (enhance ||
    function(any) {
      return any
    })(function(action, props, obj) {
    return typeof action === "function"
      ? dispatch(action(state, props), obj || props)
      : isArray(action)
      ? typeof action[0] === "function"
        ? dispatch(
            action[0],
            typeof (action = action[1]) === "function" ? action(props) : action,
            props
          )
        : (batch(action.slice(1)).map(function(fx) {
            fx && fx[0](dispatch, fx[1], props)
          }, setState(action[0])),
          state)
      : setState(action)
  })

  var render = function() {
    lock = false
    if (subscriptions) {
      subs = patchSubs(subs, batch(subscriptions(state)), dispatch)
    }
    if (view) {
      node = patch(
        node.parentNode,
        node,
        vdom,
        typeof (vdom = view(state)) === "string" ? createTextVNode(vdom) : vdom,
        listener
      )
    }
  }

  dispatch(props.init)
}
<commit_msg>Subscriptions outside render loop<commit_after>var RECYCLED_NODE = 1
var LAZY_NODE = 2
var TEXT_NODE = 3
var EMPTY_OBJ = {}
var EMPTY_ARR = []

var map = EMPTY_ARR.map
var isArray = Array.isArray
var defer = requestAnimationFrame || setTimeout

var createClass = function(obj) {
  var out = ""

  if (typeof obj === "string") return obj

  if (isArray(obj) && obj.length > 0) {
    for (var k = 0, tmp; k < obj.length; k++) {
      if ((tmp = createClass(obj[k])) !== "") {
        out += (out && " ") + tmp
      }
    }
  } else {
    for (var k in obj) {
      if (obj[k]) {
        out += (out && " ") + k
      }
    }
  }

  return out
}

var merge = function(a, b) {
  var out = {}

  for (var k in a) out[k] = a[k]
  for (var k in b) out[k] = b[k]

  return out
}

var batch = function(list) {
  return list.reduce(function(out, item) {
    return out.concat(
      !item || item === true
        ? false
        : typeof item[0] === "function"
        ? [item]
        : batch(item)
    )
  }, EMPTY_ARR)
}

var isSameAction = function(a, b) {
  return isArray(a) && isArray(b) && a[0] === b[0] && typeof a[0] === "function"
}

var shouldRestart = function(a, b) {
  for (var k in merge(a, b)) {
    if (a[k] !== b[k] && !isSameAction(a[k], b[k])) return true
    b[k] = a[k]
  }
}

var patchSubs = function(oldSubs, newSubs, dispatch) {
  for (
    var i = 0, oldSub, newSub, subs = [];
    i < oldSubs.length || i < newSubs.length;
    i++
  ) {
    oldSub = oldSubs[i]
    newSub = newSubs[i]
    subs.push(
      newSub
        ? !oldSub ||
          newSub[0] !== oldSub[0] ||
          shouldRestart(newSub[1], oldSub[1])
          ? [
              newSub[0],
              newSub[1],
              newSub[0](dispatch, newSub[1]),
              oldSub && oldSub[2]()
            ]
          : oldSub
        : oldSub && oldSub[2]()
    )
  }
  return subs
}

var patchProperty = function(node, key, oldValue, newValue, listener, isSvg) {
  if (key === "key") {
  } else if (key === "style") {
    for (var k in merge(oldValue, newValue)) {
      oldValue = newValue == null || newValue[k] == null ? "" : newValue[k]
      if (k[0] === "-") {
        node[key].setProperty(k, oldValue)
      } else {
        node[key][k] = oldValue
      }
    }
  } else if (key[0] === "o" && key[1] === "n") {
    if (
      !((node.actions || (node.actions = {}))[
        (key = key.slice(2).toLowerCase())
      ] = newValue)
    ) {
      node.removeEventListener(key, listener)
    } else if (!oldValue) {
      node.addEventListener(key, listener)
    }
  } else if (!isSvg && key !== "list" && key in node) {
    node[key] = newValue == null ? "" : newValue
  } else if (
    newValue == null ||
    newValue === false ||
    (key === "class" && !(newValue = createClass(newValue)))
  ) {
    node.removeAttribute(key)
  } else {
    node.setAttribute(key, newValue)
  }
}

var createNode = function(vnode, listener, isSvg) {
  var node =
    vnode.type === TEXT_NODE
      ? document.createTextNode(vnode.name)
      : (isSvg = isSvg || vnode.name === "svg")
      ? document.createElementNS("http://www.w3.org/2000/svg", vnode.name)
      : document.createElement(vnode.name)
  var props = vnode.props

  for (var k in props) {
    patchProperty(node, k, null, props[k], listener, isSvg)
  }

  for (var i = 0, len = vnode.children.length; i < len; i++) {
    node.appendChild(
      createNode(
        (vnode.children[i] = getVNode(vnode.children[i])),
        listener,
        isSvg
      )
    )
  }

  return (vnode.node = node)
}

var getKey = function(vnode) {
  return vnode == null ? null : vnode.key
}

var patch = function(parent, node, oldVNode, newVNode, listener, isSvg) {
  if (oldVNode === newVNode) {
  } else if (
    oldVNode != null &&
    oldVNode.type === TEXT_NODE &&
    newVNode.type === TEXT_NODE
  ) {
    if (oldVNode.name !== newVNode.name) node.nodeValue = newVNode.name
  } else if (oldVNode == null || oldVNode.name !== newVNode.name) {
    node = parent.insertBefore(
      createNode((newVNode = getVNode(newVNode)), listener, isSvg),
      node
    )
    if (oldVNode != null) parent.removeChild(oldVNode.node)
  } else {
    var tmpVKid
    var oldVKid

    var oldKey
    var newKey

    var oldVProps = oldVNode.props
    var newVProps = newVNode.props

    var oldVKids = oldVNode.children
    var newVKids = newVNode.children

    var oldHead = 0
    var newHead = 0
    var oldTail = oldVKids.length - 1
    var newTail = newVKids.length - 1

    isSvg = isSvg || newVNode.name === "svg"

    for (var i in merge(oldVProps, newVProps)) {
      if (
        (i === "value" || i === "selected" || i === "checked"
          ? node[i]
          : oldVProps[i]) !== newVProps[i]
      ) {
        patchProperty(node, i, oldVProps[i], newVProps[i], listener, isSvg)
      }
    }

    while (newHead <= newTail && oldHead <= oldTail) {
      if (
        (oldKey = getKey(oldVKids[oldHead])) == null ||
        oldKey !== getKey(newVKids[newHead])
      ) {
        break
      }

      patch(
        node,
        oldVKids[oldHead].node,
        oldVKids[oldHead],
        (newVKids[newHead] = getVNode(
          newVKids[newHead++],
          oldVKids[oldHead++]
        )),
        listener,
        isSvg
      )
    }

    while (newHead <= newTail && oldHead <= oldTail) {
      if (
        (oldKey = getKey(oldVKids[oldTail])) == null ||
        oldKey !== getKey(newVKids[newTail])
      ) {
        break
      }

      patch(
        node,
        oldVKids[oldTail].node,
        oldVKids[oldTail],
        (newVKids[newTail] = getVNode(
          newVKids[newTail--],
          oldVKids[oldTail--]
        )),
        listener,
        isSvg
      )
    }

    if (oldHead > oldTail) {
      while (newHead <= newTail) {
        node.insertBefore(
          createNode(
            (newVKids[newHead] = getVNode(newVKids[newHead++])),
            listener,
            isSvg
          ),
          (oldVKid = oldVKids[oldHead]) && oldVKid.node
        )
      }
    } else if (newHead > newTail) {
      while (oldHead <= oldTail) {
        node.removeChild(oldVKids[oldHead++].node)
      }
    } else {
      for (var i = oldHead, keyed = {}, newKeyed = {}; i <= oldTail; i++) {
        if ((oldKey = oldVKids[i].key) != null) {
          keyed[oldKey] = oldVKids[i]
        }
      }

      while (newHead <= newTail) {
        oldKey = getKey((oldVKid = oldVKids[oldHead]))
        newKey = getKey(
          (newVKids[newHead] = getVNode(newVKids[newHead], oldVKid))
        )

        if (
          newKeyed[oldKey] ||
          (newKey != null && newKey === getKey(oldVKids[oldHead + 1]))
        ) {
          if (oldKey == null) {
            node.removeChild(oldVKid.node)
          }
          oldHead++
          continue
        }

        if (newKey == null || oldVNode.type === RECYCLED_NODE) {
          if (oldKey == null) {
            patch(
              node,
              oldVKid && oldVKid.node,
              oldVKid,
              newVKids[newHead],
              listener,
              isSvg
            )
            newHead++
          }
          oldHead++
        } else {
          if (oldKey === newKey) {
            patch(
              node,
              oldVKid.node,
              oldVKid,
              newVKids[newHead],
              listener,
              isSvg
            )
            newKeyed[newKey] = true
            oldHead++
          } else {
            if ((tmpVKid = keyed[newKey]) != null) {
              patch(
                node,
                node.insertBefore(tmpVKid.node, oldVKid && oldVKid.node),
                tmpVKid,
                newVKids[newHead],
                listener,
                isSvg
              )
              newKeyed[newKey] = true
            } else {
              patch(
                node,
                oldVKid && oldVKid.node,
                null,
                newVKids[newHead],
                listener,
                isSvg
              )
            }
          }
          newHead++
        }
      }

      while (oldHead <= oldTail) {
        if (getKey((oldVKid = oldVKids[oldHead++])) == null) {
          node.removeChild(oldVKid.node)
        }
      }

      for (var i in keyed) {
        if (newKeyed[i] == null) {
          node.removeChild(keyed[i].node)
        }
      }
    }
  }

  return (newVNode.node = node)
}

var propsChanged = function(a, b) {
  for (var k in a) if (a[k] !== b[k]) return true
  for (var k in b) if (a[k] !== b[k]) return true
}

var getVNode = function(newVNode, oldVNode) {
  return newVNode.type === LAZY_NODE
    ? ((!oldVNode || propsChanged(oldVNode.lazy, newVNode.lazy)) &&
        ((oldVNode = newVNode.lazy.view(newVNode.lazy)).lazy = newVNode.lazy),
      oldVNode)
    : newVNode
}

var createVNode = function(name, props, children, node, key, type) {
  return {
    name: name,
    props: props,
    children: children,
    node: node,
    type: type,
    key: key
  }
}

var createTextVNode = function(value, node) {
  return createVNode(value, EMPTY_OBJ, EMPTY_ARR, node, null, TEXT_NODE)
}

var recycleNode = function(node) {
  return node.nodeType === TEXT_NODE
    ? createTextVNode(node.nodeValue, node)
    : createVNode(
        node.nodeName.toLowerCase(),
        EMPTY_OBJ,
        map.call(node.childNodes, recycleNode),
        node,
        null,
        RECYCLED_NODE
      )
}

export var Lazy = function(props) {
  return {
    lazy: props,
    type: LAZY_NODE
  }
}

export var h = function(name, props) {
  for (var vnode, rest = [], children = [], i = arguments.length; i-- > 2; ) {
    rest.push(arguments[i])
  }

  while (rest.length > 0) {
    if (isArray((vnode = rest.pop()))) {
      for (var i = vnode.length; i-- > 0; ) {
        rest.push(vnode[i])
      }
    } else if (vnode === false || vnode === true || vnode == null) {
    } else {
      children.push(typeof vnode === "object" ? vnode : createTextVNode(vnode))
    }
  }

  props = props || EMPTY_OBJ

  return typeof name === "function"
    ? name(props, children)
    : createVNode(name, props, children, null, props.key)
}

export var app = function(props, enhance) {
  var state = {}
  var lock = false
  var view = props.view
  var node = props.node
  var vdom = node && recycleNode(node)
  var subscriptions = props.subscriptions
  var subs = []

  var listener = function(event) {
    dispatch(this.actions[event.type], event)
  }

  var setState = function(newState) {
    if (state !== newState) {
      if (subscriptions) {
        subs = patchSubs(subs, batch([subscriptions(newState)]), dispatch)
      }
      if (!lock) defer(render, (lock = true))
    }
    return (state = newState)
  }

  var dispatch = (enhance ||
    function(any) {
      return any
    })(function(action, props, obj) {
    return typeof action === "function"
      ? dispatch(action(state, props), obj || props)
      : isArray(action)
      ? typeof action[0] === "function"
        ? dispatch(
            action[0],
            typeof (action = action[1]) === "function" ? action(props) : action,
            props
          )
        : (batch(action.slice(1)).map(function(fx) {
            fx && fx[0](dispatch, fx[1], props)
          }, setState(action[0])),
          state)
      : setState(action)
  })

  var render = function() {
    lock = false
    if (view) {
      node = patch(
        node.parentNode,
        node,
        vdom,
        typeof (vdom = view(state)) === "string" ? createTextVNode(vdom) : vdom,
        listener
      )
    }
  }

  dispatch(props.init)
}
<|endoftext|>


<commit_before>
'use strict';

var extend = require('util')._extend,
	Utils = require('./Utils'),
	responsePreKey = 'imported';

/**
 *
 * @class DTOToResponseFuncConverter
 * @param {string} name
 * @param {object} dtoJson
 * @param {object} options
 * @param {Boolean} isEjs
 * @constructor
 *
 * DTO to Class converter
 */
function DTOToResponseFuncConverter(name, dtoJson, options, isEjs) {
	this.init(name, dtoJson, options, isEjs);
}

DTOToResponseFuncConverter.prototype = extend(DTOToResponseFuncConverter.prototype, Utils.prototype);
DTOToResponseFuncConverter.prototype = extend(DTOToResponseFuncConverter.prototype, {

	constructor : DTOToResponseFuncConverter,

	_defaults: {
		responseFuncRules: {}
	},

	/**
	 *
	 * @method init
	 * called by constructor
	 * @param {string} name
	 * @param {object} dtoJson
	 * @param {object} options
	 * @param {object} options.responseFuncRules
	 * @param {string} options.dirName
	 * @param {string} options.dest
	 * @param {string|undefined} options.responseFuncPath
	 * @param {boolean} isEjs
	 * @public
	 */
	init: function (name, dtoJson, options, isEjs) {

		options = extend(this._defaults, options || {});

		this._options = options;
		this._path = this._options.responseFuncPath;
		this._rules = this._options.responseFuncRules;
		this._name = name;
		this._json = undefined;
		this._result = undefined;
		this._isEjs = isEjs;

		try {
			this._json = JSON.parse(JSON.stringify(dtoJson));
		} catch (err) {}

	},

	/**
	 * @method _isValid
	 * @returns {boolean}
	 * @private
	 */
	_isValid: function () {
		return (
			this.isFilledString(this._path) &&
			this.isFilledString(this._name) &&
			typeof this._options === 'object' &&
			typeof this._json === 'object'
		);
	},

	/**
	 * @method create
	 * @returns {object} result
	 * @public
	 */
	create: function () {

		if (!this._isValid()) {
			return {};
		}

		this._result = this._mapUnknown(this._json, '', []);
		return this._result;
	},

	/**
	 * @method _mapUnknown
	 * @param {Object} data
	 * @param {String} key
	 * @param {Array} path
	 * @private
	 */
	_mapUnknown: function (data, key, path) {

		var ruleMapObj,
			ruleMapObjParent;

		if (this._rules[key]) {
			ruleMapObj = this._mapRule(this._rules[key], data, path);
			if (ruleMapObj.valid) {
				return ruleMapObj.rule;
			}
		}

		if (path.length > 1 && this._rules[path.join('.')]) {
			ruleMapObjParent = this._mapRule(this._rules[path.join('.')], data, path);
			if (ruleMapObjParent.valid) {
				return ruleMapObjParent.rule;
			}
		}

		if (data instanceof Array) {
			return this._mapArray(data, path);
		}

		if (typeof data === 'object') {
			return this._mapObject(data, path);
		}

		if (typeof data === 'string') {
			return this._mapTypeString(data, key);
		}

		return data;
	},

	/**
	 * @method _mapRule
	 * @param {*} rule
	 * @param {*} data
	 * @param {Array} path
	 * @returns {object}
	 * @private
	 */
	_mapRule: function (rule, data, path) {

		var inValid = {
				valid: false
			},
			isValid = (this.typeOf(rule) === this.typeOf(data));

		if (typeof rule !== 'object') {
			if (!isValid) {
				return inValid;
			}
			return {
				rule: rule,
				valid: (typeof rule === data)
			};
		}

		if (rule instanceof Array) {
			if (!isValid) {
				return inValid;
			}
			return {
				rule: this._mapArray(rule, path),
				valid: true
			};
		}

		if (rule.faker) {
			if (rule.fakerArgs) {
				return {
					rule: this._getFaker(rule.faker, JSON.stringify(rule.fakerArgs)),
					valid: true
				};
			}

			return {
				rule: this._getFaker(rule.faker, ''),
				valid: true
			};
		} else {
			if (!isValid) {
				return inValid;
			}
			return {
				rule: this._mapUnknown(rule, '', path),
				valid: true
			};
		}

	},

	/**
	 * @method _mapArray
	 * @param {Object} obj
	 * @param {Array} path
	 * @private
	 */
	_mapArray: function (obj, path) {

		var out = [],
			tpl = this.readFile(__dirname + '/../src/templates/func-array.tpl'),
			methodStr,
			data;

		if (!obj || !obj[0]) {
			return out;
		}

		data = JSON.stringify(this._mapUnknown(obj[0], '', path), null, 2);
		data = this._replaceWrapper(data);
		methodStr = tpl.replace('<%=data%>', data).replace(/(?:\r\n|\r|\n)/g, '').replace(/\t/g, '');

		if (this._isEjs) {
			return methodStr
				.replace(/"/g, '\'')
				.replace(/'(<%-)(require\()([^\)]*)(\))(\.[^\)]*\))([^']*')/g, 'JSON.parse($2$3$4$5)')
				.replace(/;%>'/g, '')
				.replace(/'<%-/g, '')
				.replace(/%>'/g, '');
		}

		return '<%>' + methodStr + '<%>';
	},

	/**
	 * @method _mapObject
	 * @param {Object} obj
	 * @param {Array} path
	 * @private
	 */
	_mapObject: function (obj, path) {

		var objOut = {};

		this.forIn(obj, function (key, value) {
			var newPath = path.slice();
			newPath.push(key);
			objOut[key] = this._mapUnknown(value, key, newPath);
		});

		return objOut;
	},

	/**
	 * @method _mapTypeString
	 * @param {String} value
	 * @param {String|undefined} key
	 * @private
	 */
	_mapTypeString: function (value, key) {

		if (value.search(/^\$ref-/) >= 0) {
			return this._mapReference(value);
		}

		if (value === 'number') {
			return this._mapNumber();
		}

		if (value === 'string') {
			return this._mapString(key);
		}

	},

	/**
	 * @method _mapString
	 * @param {String} key
	 * @private
	 */
	_mapString: function (key) {

		var _has;

		_has = function (search) {
			return this._isPart(key, search);
		}.bind(this);

		if (_has('name')) {

			if (_has('first')) {
				return this._getFaker('name.firstName', '');
			}
			if (_has('last')) {
				return this._getFaker('name.lastName', '');
			}
			if (_has('street')) {
				return this._getFaker('address.streetName', '');
			}
			return this._getFaker('name.findName', '');
		}

		if (_has('country')) {
			if (_has('code')) {
				return this._getFaker('random.arrayElement', '["CH","DE","AT","FR","UK","US","JP"]');
			}
			return this._getFaker('address.country', '');
		}

		if (_has('zip') || _has('postal')) {
			return this._getFaker('address.zipCode', '');
		}

		if (_has('city') || _has('town')) {
			return this._getFaker('address.city', '');
		}

		if (_has('street')) {
			if (_has('number')) {
				return this._getFaker('random.number', '');
			}
			return this._getFaker('address.streetName', '');
		}

		if (_has('phone')) {
			return this._getFaker('phone.phoneNumber', '');
		}

		if (_has('email')) {
			return this._getFaker('internet.email', '');
		}

		if (_has('userName')) {
			return this._getFaker('internet.userName', '');
		}

		if (_has('domain')) {
			return this._getFaker('internet.domainName', '');
		}

		if (_has('company')) {
			return this._getFaker('company.companyName', '');
		}

		if (_has('image')) {
			return this._getFaker('image.nature', '');
		}

		if (_has('title')) {
			if (_has('code')) {
				return this._getFaker('random.arrayElement', '["mr","ms"]');
			}
			return this._getFaker('name.prefix', '');
		}

		return this._getFaker('lorem.word', '');
	},

	/**
	 * @method _isPart
	 * @param {string} value
	 * @param {string} search
	 * @returns {boolean}
	 * @private
	 */
	_isPart: function (value, search) {
		return (value.toLowerCase().search(search) >= 0);
	},

	/**
	 * @method _mapNumber
	 * @returns {String}
	 * @private
	 */
	_mapNumber: function () {
		return this._getFaker('random.number', '');
	},

	/**
	 * @method _getFaker
	 * @param {String} path
	 * @param {String,undefined} args
	 * @returns {String}
	 * @private
	 */
	_getFaker: function (path, args) {

		if (this._isEjs) {
			return '<%-faker.' + path + '(' + args.replace(/"/g, '\'') + ')%>';
		}

		return '<%>faker.' + path + '(' + args + ')<%>';
	},

	/**
	 * @method _mapReference
	 * @param {String} refString
	 * @returns {String}
	 * @private
	 */
	_mapReference: function (refString) {
		var name = refString.replace('$ref-', '');

		if (this._isEjs) {
			return '<%-_getRef(\'' + name + '\');%>';
		}

		return '<%>_getRes(\'' + name + '\', loopArr)<%>';
	},

	/**
	 * @method _getFile
	 * @param {String} funcName
	 * @param {Object} data
	 * @returns {String}
	 * @private
	 */
	_getFile: function (funcName, data) {
		return this._replaceWrapper(this.readFile(__dirname + '/../src/templates/func.tpl')
			.replace(/<%=funcName%>/g, responsePreKey + funcName)
			.replace(/<%=data%>/g, JSON.stringify(data, null, 2))
		);
	},

	/**
	 * @method _replaceWrapper
	 * @param {String} value
	 * @returns {String}
	 * @private
	 */
	_replaceWrapper: function (value) {
		return value
			.replace(/"<%>/g, '')
			.replace(/<%>"/g, '')
			.replace(/\\"/g, '"')
			.replace(/\\"/g, '"')
			.replace(/""/g, '"')
		;
	},

	/**
	 * @method write
	 * @returns {void}
	 * @public
	 */
	write: function () {

		if (!this._isValid()) {
			return;
		}

		if (typeof this._result !== 'object') {
			this._result = {};
		}

		if (!this.existDir(this._path)) {
			this.writeDir(this._path);
		}

		this.writeFile(this._path + '/' + this._name + '.js', this._getFile(this._name, this._result));
	},

	/**
	 * @method get
	 * @returns {String}
	 * @public
	 */
	get: function () {

		if (!this._isValid()) {
			return '';
		}

		if (typeof this._result !== 'object') {
			this._result = {};
		}

		return this._result;
	}

});

module.exports = DTOToResponseFuncConverter;<commit_msg>[change] #18 overwrite DTO specific attributes<commit_after>
'use strict';

var extend = require('util')._extend,
	Utils = require('./Utils'),
	responsePreKey = 'imported';

/**
 *
 * @class DTOToResponseFuncConverter
 * @param {string} name
 * @param {object} dtoJson
 * @param {object} options
 * @param {Boolean} isEjs
 * @constructor
 *
 * DTO to Class converter
 */
function DTOToResponseFuncConverter(name, dtoJson, options, isEjs) {
	this.init(name, dtoJson, options, isEjs);
}

DTOToResponseFuncConverter.prototype = extend(DTOToResponseFuncConverter.prototype, Utils.prototype);
DTOToResponseFuncConverter.prototype = extend(DTOToResponseFuncConverter.prototype, {

	constructor : DTOToResponseFuncConverter,

	_defaults: {
		responseFuncRules: {}
	},

	/**
	 *
	 * @method init
	 * called by constructor
	 * @param {string} name
	 * @param {object} dtoJson
	 * @param {object} options
	 * @param {object} options.responseFuncRules
	 * @param {string} options.dirName
	 * @param {string} options.dest
	 * @param {string|undefined} options.responseFuncPath
	 * @param {boolean} isEjs
	 * @public
	 */
	init: function (name, dtoJson, options, isEjs) {

		options = extend(this._defaults, options || {});

		this._options = options;
		this._path = this._options.responseFuncPath;
		this._rules = this._options.responseFuncRules;
		this._name = name;
		this._json = undefined;
		this._result = undefined;
		this._isEjs = isEjs;

		try {
			this._json = JSON.parse(JSON.stringify(dtoJson));
		} catch (err) {}

	},

	/**
	 * @method _isValid
	 * @returns {boolean}
	 * @private
	 */
	_isValid: function () {
		return (
			this.isFilledString(this._path) &&
			this.isFilledString(this._name) &&
			typeof this._options === 'object' &&
			typeof this._json === 'object'
		);
	},

	/**
	 * @method create
	 * @returns {object} result
	 * @public
	 */
	create: function () {

		if (!this._isValid()) {
			return {};
		}

		this._result = this._mapUnknown(this._json, '', []);
		return this._result;
	},

	/**
	 * @method _mapUnknown
	 * @param {Object} data
	 * @param {String} key
	 * @param {Array} path
	 * @private
	 */
	_mapUnknown: function (data, key, path) {

		var ruleMapObj,
			ruleMapObjParent;

		if (this._rules[this._name] && path.length < 1) {
			this._mapRuleDTO(this._rules[this._name], data);
		}

		if (this._rules[key]) {
			ruleMapObj = this._mapRule(this._rules[key], data, path);
			if (ruleMapObj.valid) {
				return ruleMapObj.rule;
			}
		}

		if (path.length > 1 && this._rules[path.join('.')]) {
			ruleMapObjParent = this._mapRule(this._rules[path.join('.')], data, path);
			if (ruleMapObjParent.valid) {
				return ruleMapObjParent.rule;
			}
		}

		if (data instanceof Array) {
			return this._mapArray(data, path);
		}

		if (typeof data === 'object') {
			return this._mapObject(data, path);
		}

		if (typeof data === 'string') {
			return this._mapTypeString(data, key);
		}

		return data;
	},

	/**
	 * @method _mapRule
	 * @param {*} rule
	 * @param {*} data
	 * @param {Array} path
	 * @returns {object}
	 * @private
	 */
	_mapRule: function (rule, data, path) {

		var inValid = {
				valid: false
			},
			isValid = (this.typeOf(rule) === this.typeOf(data));

		if (typeof rule !== 'object') {
			if (!isValid) {
				return inValid;
			}
			return {
				rule: rule,
				valid: (typeof rule === data)
			};
		}

		if (rule instanceof Array) {
			if (!isValid) {
				return inValid;
			}
			return {
				rule: this._mapArray(rule, path),
				valid: true
			};
		}

		if (rule.faker) {
			if (rule.fakerArgs) {
				return {
					rule: this._getFaker(rule.faker, JSON.stringify(rule.fakerArgs)),
					valid: true
				};
			}

			return {
				rule: this._getFaker(rule.faker, ''),
				valid: true
			};
		} else {
			if (!isValid) {
				return inValid;
			}
			return {
				rule: this._mapUnknown(rule, '', path),
				valid: true
			};
		}

	},

	/**
	 * @method _mapRuleDTO
	 * @param {Object} rule
	 * @param {Object} data
	 * @returns {void}
	 * @private
	 */
	_mapRuleDTO: function (rule, data) {

		if (this.typeOf(rule) !== 'object' || this.typeOf(data) !== 'object') {
			return;
		}

		this.forIn(rule, function (key, value) {
			if (data[key] && this.typeOf(data[key] === this.typeOf(value))) {
				data[key] = value;
			}
		}.bind(this));
	},

	/**
	 * @method _mapArray
	 * @param {Object} obj
	 * @param {Array} path
	 * @private
	 */
	_mapArray: function (obj, path) {

		var out = [],
			tpl = this.readFile(__dirname + '/../src/templates/func-array.tpl'),
			methodStr,
			data;

		if (!obj || !obj[0]) {
			return out;
		}

		data = JSON.stringify(this._mapUnknown(obj[0], '', path), null, 2);
		data = this._replaceWrapper(data);
		methodStr = tpl.replace('<%=data%>', data).replace(/(?:\r\n|\r|\n)/g, '').replace(/\t/g, '');

		if (this._isEjs) {
			return methodStr
				.replace(/"/g, '\'')
				.replace(/'(<%-)(require\()([^\)]*)(\))(\.[^\)]*\))([^']*')/g, 'JSON.parse($2$3$4$5)')
				.replace(/;%>'/g, '')
				.replace(/'<%-/g, '')
				.replace(/%>'/g, '');
		}

		return '<%>' + methodStr + '<%>';
	},

	/**
	 * @method _mapObject
	 * @param {Object} obj
	 * @param {Array} path
	 * @private
	 */
	_mapObject: function (obj, path) {

		var objOut = {};

		this.forIn(obj, function (key, value) {
			var newPath = path.slice();
			newPath.push(key);
			objOut[key] = this._mapUnknown(value, key, newPath);
		});

		return objOut;
	},

	/**
	 * @method _mapTypeString
	 * @param {String} value
	 * @param {String|undefined} key
	 * @private
	 */
	_mapTypeString: function (value, key) {

		if (value.search(/^\$ref-/) >= 0) {
			return this._mapReference(value);
		}

		if (value === 'number') {
			return this._mapNumber();
		}

		if (value === 'string') {
			return this._mapString(key);
		}

		return value;
	},

	/**
	 * @method _mapString
	 * @param {String} key
	 * @private
	 */
	_mapString: function (key) {

		var _has;

		_has = function (search) {
			return this._isPart(key, search);
		}.bind(this);

		if (_has('name')) {

			if (_has('first')) {
				return this._getFaker('name.firstName', '');
			}
			if (_has('last')) {
				return this._getFaker('name.lastName', '');
			}
			if (_has('street')) {
				return this._getFaker('address.streetName', '');
			}
			return this._getFaker('name.findName', '');
		}

		if (_has('country')) {
			if (_has('code')) {
				return this._getFaker('random.arrayElement', '["CH","DE","AT","FR","UK","US","JP"]');
			}
			return this._getFaker('address.country', '');
		}

		if (_has('zip') || _has('postal')) {
			return this._getFaker('address.zipCode', '');
		}

		if (_has('city') || _has('town')) {
			return this._getFaker('address.city', '');
		}

		if (_has('street')) {
			if (_has('number')) {
				return this._getFaker('random.number', '');
			}
			return this._getFaker('address.streetName', '');
		}

		if (_has('phone')) {
			return this._getFaker('phone.phoneNumber', '');
		}

		if (_has('email')) {
			return this._getFaker('internet.email', '');
		}

		if (_has('userName')) {
			return this._getFaker('internet.userName', '');
		}

		if (_has('domain')) {
			return this._getFaker('internet.domainName', '');
		}

		if (_has('company')) {
			return this._getFaker('company.companyName', '');
		}

		if (_has('image')) {
			return this._getFaker('image.nature', '');
		}

		if (_has('title')) {
			if (_has('code')) {
				return this._getFaker('random.arrayElement', '["mr","ms"]');
			}
			return this._getFaker('name.prefix', '');
		}

		return this._getFaker('lorem.word', '');
	},

	/**
	 * @method _isPart
	 * @param {string} value
	 * @param {string} search
	 * @returns {boolean}
	 * @private
	 */
	_isPart: function (value, search) {
		return (value.toLowerCase().search(search) >= 0);
	},

	/**
	 * @method _mapNumber
	 * @returns {String}
	 * @private
	 */
	_mapNumber: function () {
		return this._getFaker('random.number', '');
	},

	/**
	 * @method _getFaker
	 * @param {String} path
	 * @param {String,undefined} args
	 * @returns {String}
	 * @private
	 */
	_getFaker: function (path, args) {

		if (this._isEjs) {
			return '<%-faker.' + path + '(' + args.replace(/"/g, '\'') + ')%>';
		}

		return '<%>faker.' + path + '(' + args + ')<%>';
	},

	/**
	 * @method _mapReference
	 * @param {String} refString
	 * @returns {String}
	 * @private
	 */
	_mapReference: function (refString) {
		var name = refString.replace('$ref-', '');

		if (this._isEjs) {
			return '<%-_getRef(\'' + name + '\');%>';
		}

		return '<%>_getRes(\'' + name + '\', loopArr)<%>';
	},

	/**
	 * @method _getFile
	 * @param {String} funcName
	 * @param {Object} data
	 * @returns {String}
	 * @private
	 */
	_getFile: function (funcName, data) {
		return this._replaceWrapper(this.readFile(__dirname + '/../src/templates/func.tpl')
			.replace(/<%=funcName%>/g, responsePreKey + funcName)
			.replace(/<%=data%>/g, JSON.stringify(data, null, 2))
		);
	},

	/**
	 * @method _replaceWrapper
	 * @param {String} value
	 * @returns {String}
	 * @private
	 */
	_replaceWrapper: function (value) {
		return value
			.replace(/"<%>/g, '')
			.replace(/<%>"/g, '')
			.replace(/\\"/g, '"')
			.replace(/\\"/g, '"')
			.replace(/""/g, '"')
		;
	},

	/**
	 * @method write
	 * @returns {void}
	 * @public
	 */
	write: function () {

		if (!this._isValid()) {
			return;
		}

		if (typeof this._result !== 'object') {
			this._result = {};
		}

		if (!this.existDir(this._path)) {
			this.writeDir(this._path);
		}

		this.writeFile(this._path + '/' + this._name + '.js', this._getFile(this._name, this._result));
	},

	/**
	 * @method get
	 * @returns {String}
	 * @public
	 */
	get: function () {

		if (!this._isValid()) {
			return '';
		}

		if (typeof this._result !== 'object') {
			this._result = {};
		}

		return this._result;
	}

});

module.exports = DTOToResponseFuncConverter;<|endoftext|>


<commit_before>import pathToRegexp from 'path-to-regexp'
import React from 'react'
import {parse} from 'url'
import NextLink from 'next/link'
import NextRouter from 'next/router'

module.exports = opts => new Routes(opts)

const nextPaths = [
  '/_next',
  '/_webpack/',
  '/__webpack_hmr',
  '/static/'
]

class Routes {
  constructor ({
    Link = NextLink,
    Router = NextRouter
  } = {}) {
    this.routes = []
    this.Link = this.getLink(Link)
    this.Router = this.getRouter(Router)
  }

  add (...args) {
    this.routes.push(new Route(...args))
    return this
  }

  findByName (name) {
    const route = this.routes.find(route => route.name === name)
    if (!route) {
      throw new Error(`Unknown route: ${name}`)
    }
    return route
  }

  match (path) {
    let params
    const route = this.routes.find(route => (params = route.match(path)))
    return {route, params}
  }

  isNextPath (url) {
    return nextPaths.some(path => url.startsWith(path))
  }

  getRequestHandler (app) {
    const nextHandler = app.getRequestHandler()

    return (req, res) => {
      const parsedUrl = parse(req.url, true)
      const {pathname, query} = parsedUrl

      if (this.isNextPath(pathname)) {
        nextHandler(req, res, parsedUrl)
      } else {
        const {route, params} = this.match(pathname)

        if (route) {
          app.render(req, res, route.page, {...query, ...params})
        } else {
          nextHandler(req, res, parsedUrl)
        }
      }
    }
  }

  getLink (Link) {
    return props => {
      const {route, params, ...newProps} = props

      if (route) {
        Object.assign(newProps, this.findByName(route).getLinkProps(params))
      }

      return <Link {...newProps} />
    }
  }

  getRouter (Router) {
    const pushRoute = (name, params = {}) => {
      const {href, as} = this.findByName(name).getLinkProps(params)
      return Router.push(href, as)
    }

    const replaceRoute = (name, params = {}) => {
      const {href, as} = this.findByName(name).getLinkProps(params)
      return Router.replace(href, as)
    }

    return Object.assign(Object.create(Router), {pushRoute, replaceRoute})
  }
}

class Route {
  constructor (name, pattern, page = name) {
    this.name = name
    this.pattern = pattern || `/${name}`
    this.page = page.replace(/^\/?(.*)/, '/$1')
    this.regex = pathToRegexp(this.pattern, this.keys = [])
    this.getAs = pathToRegexp.compile(this.pattern)
  }

  match (path) {
    const values = this.regex.exec(path)
    if (values) {
      return this.valuesToParams(values.slice(1))
    }
  }

  valuesToParams (values) {
    return values.reduce((params, val, i) => (
      Object.assign(params, {[this.keys[i].name]: val})
    ), {})
  }

  getHref (params = {}) {
    const qs = Object.keys(params).map(key => {
      let value = params[key]
      if (Array.isArray(value)) {
        value = value.join('/')
      }
      return [
        encodeURIComponent(key),
        encodeURIComponent(value)
      ].join('=')
    }).join('&')

    return `${this.page}?${qs}`
  }

  getLinkProps (params = {}) {
    const as = this.getAs(params)
    const href = this.getHref(params)
    return {as, href}
  }
}
<commit_msg>Use unknown route params as querystring<commit_after>import pathToRegexp from 'path-to-regexp'
import React from 'react'
import {parse} from 'url'
import NextLink from 'next/link'
import NextRouter from 'next/router'

module.exports = opts => new Routes(opts)

const nextPaths = [
  '/_next',
  '/_webpack/',
  '/__webpack_hmr',
  '/static/'
]

class Routes {
  constructor ({
    Link = NextLink,
    Router = NextRouter
  } = {}) {
    this.routes = []
    this.Link = this.getLink(Link)
    this.Router = this.getRouter(Router)
  }

  add (...args) {
    this.routes.push(new Route(...args))
    return this
  }

  findByName (name) {
    const route = this.routes.find(route => route.name === name)
    if (!route) {
      throw new Error(`Unknown route: ${name}`)
    }
    return route
  }

  match (path) {
    let params
    const route = this.routes.find(route => (params = route.match(path)))
    return {route, params}
  }

  isNextPath (url) {
    return nextPaths.some(path => url.startsWith(path))
  }

  getRequestHandler (app) {
    const nextHandler = app.getRequestHandler()

    return (req, res) => {
      const parsedUrl = parse(req.url, true)
      const {pathname, query} = parsedUrl

      if (this.isNextPath(pathname)) {
        nextHandler(req, res, parsedUrl)
      } else {
        const {route, params} = this.match(pathname)

        if (route) {
          app.render(req, res, route.page, {...query, ...params})
        } else {
          nextHandler(req, res, parsedUrl)
        }
      }
    }
  }

  getLink (Link) {
    return props => {
      const {route, params, ...newProps} = props

      if (route) {
        Object.assign(newProps, this.findByName(route).getLinkProps(params))
      }

      return <Link {...newProps} />
    }
  }

  getRouter (Router) {
    const pushRoute = (name, params = {}) => {
      const {href, as} = this.findByName(name).getLinkProps(params)
      return Router.push(href, as)
    }

    const replaceRoute = (name, params = {}) => {
      const {href, as} = this.findByName(name).getLinkProps(params)
      return Router.replace(href, as)
    }

    return Object.assign(Object.create(Router), {pushRoute, replaceRoute})
  }
}

class Route {
  constructor (name, pattern, page = name) {
    this.name = name
    this.pattern = pattern || `/${name}`
    this.page = page.replace(/^\/?(.*)/, '/$1')
    this.regex = pathToRegexp(this.pattern, this.keys = [])
    this.keyNames = this.keys.map(key => key.name)
    this.toPath = pathToRegexp.compile(this.pattern)
  }

  match (path) {
    const values = this.regex.exec(path)
    if (values) {
      return this.valuesToParams(values.slice(1))
    }
  }

  valuesToParams (values) {
    return values.reduce((params, val, i) => Object.assign(params, {
      [this.keys[i].name]: val
    }), {})
  }

  getHref (params = {}) {
    return `${this.page}?${toQuerystring(params)}`
  }

  getAs (params = {}) {
    const as = this.toPath(params)
    const keys = Object.keys(params)
    const qsKeys = keys.filter(key => !this.keyNames.includes(key))

    if (!qsKeys.length) return as

    const qsParams = qsKeys.reduce((qs, key) => Object.assign(qs, {
      [key]: params[key]
    }), {})

    return `${as}?${toQuerystring(qsParams)}`
  }

  getLinkProps (params = {}) {
    const as = this.getAs(params)
    const href = this.getHref(params)
    return {as, href}
  }
}

const toQuerystring = (obj = {}) => Object.keys(obj).map(key => {
  let value = obj[key]
  if (Array.isArray(value)) {
    value = value.join('/')
  }
  return [
    encodeURIComponent(key),
    encodeURIComponent(value)
  ].join('=')
}).join('&')
<|endoftext|>


<commit_before>/**
 * @class Ds.createjs.display.GalleyModel=GalleyModel;
 * @classdesc: [画廊类 Lammer使用过]
 * @param       {[Object]} opts [配置]
 * opts.sceneWidth   场景宽
 * opts.sceneHeight  场景高
 * opts.viewWidth    视觉画布宽，默认开启opts.autoReSize  自动来计算
 * opts.autoReSize  是否自动算自适应
 * opts.loop        是否前后衔接
 * opts.speedCut    是否滑动减速度  默认减速 0.05
 * opts.maxSpeed    最大运动速度
 * opts.scenes      初始化传入场景列表  也可以之后通过 AddSceneList与AddScene方法来
 * opts.debug      是否进行debug
 * @event
 * e.type='update' 场景进行更新
 * e.scenes   更新的场景列表
 * e.scenes[0].progress 场景相对画布 进行显示的百分比
 *                   <_SceneWidth progress 30%----------------------------------|
 *                                     |          |           |
 *                                     |<----_ViewWidth------>|
 *                                     |          |           |
 *                                     <_SceneWidth progress  0%----------------------------------|                   |
 *                                     |<----_ViewWidth------>|
 *                                     |          |           |
 * <_SceneWidth progress 30%----------------------------------|
 *                                     |<----_ViewWidth------>|
 * @extends
 * @example: 举例
 * @author: maksim email:maksim.lin@foxmail.com
 * @copyright: Ds是累积平时项目工作的经验代码库，不属于职位任务与项目的内容。里面代码大部分理念来至曾经flash 前端时代，尽力减小类之间耦合，通过webpack按需request使用。Ds库里内容多来至网络与参考其他开源代码库。Ds库也开源开放，随意使用在所属的职位任务与项目中。
 * @constructor
 **/
!(function (factory) {
    var root = (typeof self == 'object' && self.self == self && self) ||
        (typeof global == 'object' && global.global == global && global);

    if (typeof define === 'function' && define.amd) {
        define(['exports'], function (exports) {
            require('ds/gemo/SliderHVDistance');
            module.exports= factory(root, exports);
        });
    } else if (typeof exports !== 'undefined') {
        module.exports=factory(root, exports);
    } else {
         factory(root, {});
    }

}(function (root, modelObj) {
  root.Ds = root.Ds || {};
  root.Ds.createjs=root.Ds.createjs ||{};
  root.Ds.createjs.display = root.Ds.createjs.display || {};
  root.Ds.createjs.display.GalleyModel=GalleyModel;
  function GalleyModel(opts){
    var _Self=this;
    //配置
    opts=opts||{};
    //事件继承
    Ds.Extend(this, new Ds.EventDispatcher());
    //场景列表
    var _SceneList=[];
    Object.defineProperty(this, "Scenes", {get: function() {return _SceneList;},});
    //场景宽
    var _SceneWidth = opts.sceneWidth||2969;
    //场景高
    var _SceneHeight = opts.sceneHeight||1140;
    //视觉画布宽
    var _ViewWidth=opts.viewWidth||640;
    //画布区域
    var _ViewRect=new createjs.Rectangle(0, 0,_ViewWidth, _SceneHeight);;
    //是否自动计算自适应
    var _AutoReSize=opts.autoReSize!==undefined?opts.autoReSize:true;
    //进行debug测试
    var _Debug=opts.debug!==undefined?opts.debug:true;
    //是否循环
    var _Loop=opts.loop!==undefined?opts.loop:true;
    //计算屏幕补差的矩形区域
    var _MovieInViewRect=new createjs.Rectangle(-(_ViewWidth*3-_ViewWidth)/2, 0,_ViewWidth*3, _SceneHeight);
    //当前距离
    var _Distance=0;
    Object.defineProperty(this, "Distance", {
        get: function() {
            return _Distance;
        },
        set: function(value) {
          _Distance=value;
          UpDate();
        }
    });
    //总场景距离  _SceneWidth*(_SceneList.length);
    var _AllDistance=0;
    //var _AllDistance=_SceneWidth*(_SceneList.length);
    //平滑拖动管理对象
    var _SliderDistance = new Ds.gemo.SliderHVDistance(_Self, 'Distance', {
      touchDom:$('#screen'),
      interval:640,
      hasAutoSpeed:true,
      speedCut:opts.speedCut!==undefined?opts.speedCut:0.05,
      isLoop:_Loop,
      isVerticalTouch:false,
      touchDirection:false,
      maxSpeed:opts.maxSpeed!==undefined?opts.maxSpeed:15,
      minSpeed:0,
      min:0,
      max:_AllDistance,
    });
    //是否锁定
    Object.defineProperty(this, "Lock", {
        get: function() {
            return _SliderDistance.Lock;
        },
        set: function(value) {
          _SliderDistance.Lock=value;
        }
    });

    //主要容器
    var _View=new createjs.Container();
    Object.defineProperty(this, "View", {get: function() {return _View;},});
    //滚动容器
    var _Box=new createjs.Container();
    _View.addChild(_Box);
    //======================测试代码=================
    if(_Debug){
      _View.scaleX=_View.scaleY=0.25;
      _View.x=(640-640*_View.scaleX)/2;
      var shape=new createjs.Shape();
      shape.graphics.beginFill("red").drawRect(0, 0, 640, _MovieInViewRect.height);
      shape.alpha=0.5;
      _View.addChild(shape);
      var _readShape=new createjs.Shape();
      _readShape.graphics.beginFill("greed").drawRect(_MovieInViewRect.x, _MovieInViewRect.y, _MovieInViewRect.width, _MovieInViewRect.height);
      _readShape.alpha=0.5;
      _View.addChild(_readShape);
    }
    //======================测试代码=================

    /**
     * 添加场景列表
     * @param  {[type]} scenes [description]
     * @return {[type]}        [description]
     */
    this.AddSceneList=function(scenes){
      for (var i = 0; i < scenes.length; i++) {
        this.AddScene(scenes[i]);
      }
      ReSize();
    }
    /**
     * 添加一个场景
     * @param  {[type]} scene [description]
     * @return {[type]}       [description]
     */
    this.AddScene=function(scene){
      _SceneList.push(scene);
      scene.x=_SceneWidth*(_SceneList.length-1);
      scene.rect=new createjs.Rectangle(0, 0, _SceneWidth, _SceneHeight);
      _Box.addChild(scene);
      _AllDistance=_Loop?_SceneWidth*(_SceneList.length):_SceneWidth*(_SceneList.length)-_ViewWidth;
      _SliderDistance.MaxDistance=_AllDistance;
      scene.upChildList=[];
    };
    //如果有场景列表就进行场景列表的添加
    if(opts.scenes){this.AddSceneList(opts.scenes);}
    /**
     * [添加子对象更新数据]
     * @param  {[type]} child [子对象]
     * @param  {[type]} opts [子对象配置 可以只是一个数字，代表偏移量]
     * @param  {[type]} scene [对应的场景对象]
     * @return {[type]}       [description]
     */
    this.AddChildUpData=function (child,opts,scene) {
      if(!scene)scene=child.parent;
      var _childs=scene.upChildList;
      // console.log('AddChildUpData:',_childs.length);
      child.ox=child.x;
      child.oy=child.y;
      opts=opts||{};
      var _speed=Math.random()>0.5?_SceneWidth/8:-_SceneWidth/8;
      _speed=_speed/2+(_speed/2)*Math.random();
      if(typeof(opts)==='number')_speed=opts;
      else{
        if(opts.speed!==undefined)_speed=opts.speed;
      }
      child.speed=_speed;
      if(_childs.indexOf(child)===-1)_childs.push(child);
    }
    /**
     * 场景更新
     * @constructor
     */
    function UpDate() {
      //计算场景视觉补差  第一个场景补差
      var _sceneStart=_SceneList[0];
      if(_Distance>=_AllDistance-_ViewWidth*2)_sceneStart.x=_SceneWidth*_SceneList.length;
      else  _sceneStart.x=0;
      //计算场景视觉补差  最后一个场景补差
      var _sceneEnd=_SceneList[_SceneList.length-1];
      if(_Distance>=0&&_Distance<=_SceneWidth)_sceneEnd.x=-_SceneWidth;
      else _sceneEnd.x=_SceneWidth*(_SceneList.length-1);
      _Box.x=-_Distance;

      var _upList=[];
      //进行显示对象剔除算法
      var _scene;
      for (var i = 0; i < _SceneList.length; i++) {
        _scene=_SceneList[i];
        var _pt=_scene.localToLocal(0,0,_View);
        var _rect=_scene.rect;
        _rect.x=_pt.x;
        _rect.y=_pt.y;
        var _bool=_MovieInViewRect.intersects(_rect);
        _scene.visible=_bool;

        //计算显示的场景的进度百分百
        //_bool=_ViewRect.intersects(_rect)
        if(_bool){
          var _progress=0;
          var _w=_SceneWidth-_ViewWidth;
          _progress=-_pt.x/_w;
          _progress=Math.min(Math.max(_progress,0),1);
          _scene.progress=_progress;
          // if(i===0)console.log('_progress:',_progress);
          _upList.push(_scene);
          //对子对象进行更新处理
          ChildUpDate(_scene);
        }
      }

      _Self.ds({
        type:'update',
        scenes:_upList,//这里只会放需要显示的元素，相对场景上 当前移动进度比
      });
    }
    /**
     * 对子对象进行更新处理
     * @param       {[type]} scene [description]
     * @constructor
     */
    function ChildUpDate(scene) {

      var _progress=scene.progress;
      var _childs=scene.upChildList;
      // console.log('ChildUpDate:',_childs.length);
      for (var i = 0; i < _childs.length; i++) {
        var _child=_childs[i];
        _child.x=(_child.ox-_child.speed/2)+_progress*_child.speed;
      }
    }

    //自适应
    window.addEventListener("resize", function() {
      ReSize();
      setTimeout(function() {ReSize();}, 100);
    });
    //计算自适应 _PopLayerContainer设置宽高
    function ReSize() {
      if(!_AutoReSize)return;
      var _width, _height, _pageScale, _actualH, _horizontal = false,
        _isInputState = false;
      _width = window.innerWidth;
      _height = window.innerHeight;
      //计算是否横屏
      if (_width > _height) _horizontal = true;
      else _horizontal = false;
      if (_width / _height > 3) {
        //算出竖屏幕下输入框状态下比例
        _isInputState = true;
      } else if (_width / _height < 12 / 7 && _width / _height > 1) {
        //算出竖屏幕下输入框状态下比例
        _isInputState = true;
        //说明这时候不会是横屏
        _horizontal = false;
      } else {
        //非输入状态
        _isInputState = false;
      }
      if (_horizontal) _screenWidth = 1138;
      else _screenWidth = 640;
      //计算缩放比例
      _pageScale = _width / _screenWidth;
      //计算实际高度
      _actualH = _height / _pageScale;
      if(_isInputState)return;
      //按高来自动适应
      var _s=_actualH/_SceneHeight;
      _View.scaleX=_View.scaleY=_s;
      //按高自适应后 视觉画布宽重新计算
      _s=_SceneHeight/_actualH;
      var _viewWidth=_screenWidth*_s;
      _ViewRect.width=_viewWidth;
      //视觉画布宽
      _ViewWidth=_viewWidth;
      //计算屏幕补差的矩形区域
      _MovieInViewRect.x=-(_ViewWidth*3-_ViewWidth)/2;
      _MovieInViewRect.y=0;
      _MovieInViewRect.width=_ViewWidth*3;
      _MovieInViewRect.height=_SceneHeight;
      //计算大的距离长度
      _AllDistance=_Loop?_SceneWidth*(_SceneList.length):_SceneWidth*(_SceneList.length)-_ViewWidth;
      _SliderDistance.MaxDistance=_AllDistance;
    }
    ReSize();
  }

  return root.Ds.createjs.display.GalleyModel;
}));
<commit_msg>update<commit_after>/**
 * @class Ds.createjs.display.GalleyModel=GalleyModel;
 * @classdesc: [画廊类 Lammer使用过]
 * @param       {[Object]} opts [配置]
 * opts.sceneWidth   场景宽
 * opts.sceneHeight  场景高
 * opts.viewWidth    视觉画布宽，默认开启opts.autoReSize  自动来计算
 * opts.autoReSize  是否自动算自适应
 * opts.loop        是否前后衔接
 * opts.speedCut    是否滑动减速度  默认减速 0.05
 * opts.maxSpeed    最大运动速度
 * opts.scenes      初始化传入场景列表  也可以之后通过 AddSceneList与AddScene方法来
 * opts.debug      是否进行debug
 * @event
 * e.type='update' 场景进行更新
 * e.sceneID        当前在第几个场景
 * e.inViewScenes  在视图内的场景
 * e.scenes[0].inRect   场景与视图相交的区域大小
 * e.scenes   更新的场景列表
 * e.scenes[0].progress 场景相对画布 进行显示的百分比
 *                   <_SceneWidth progress 30%----------------------------------|
 *                                     |          |           |
 *                                     |<----_ViewWidth------>|
 *                                     |          |           |
 *                                     <_SceneWidth progress  0%----------------------------------|                   |
 *                                     |<----_ViewWidth------>|
 *                                     |          |           |
 * <_SceneWidth progress 30%----------------------------------|
 *                                     |<----_ViewWidth------>|
 * @extends
 * @example: 举例
 * @author: maksim email:maksim.lin@foxmail.com
 * @copyright: Ds是累积平时项目工作的经验代码库，不属于职位任务与项目的内容。里面代码大部分理念来至曾经flash 前端时代，尽力减小类之间耦合，通过webpack按需request使用。Ds库里内容多来至网络与参考其他开源代码库。Ds库也开源开放，随意使用在所属的职位任务与项目中。
 * @constructor
 **/
!(function (factory) {
    var root = (typeof self == 'object' && self.self == self && self) ||
        (typeof global == 'object' && global.global == global && global);

    if (typeof define === 'function' && define.amd) {
        define(['exports'], function (exports) {
            require('ds/gemo/SliderHVDistance');
            module.exports= factory(root, exports);
        });
    } else if (typeof exports !== 'undefined') {
        module.exports=factory(root, exports);
    } else {
         factory(root, {});
    }

}(function (root, modelObj) {
  root.Ds = root.Ds || {};
  root.Ds.createjs=root.Ds.createjs ||{};
  root.Ds.createjs.display = root.Ds.createjs.display || {};
  root.Ds.createjs.display.GalleyModel=GalleyModel;
  function GalleyModel(opts){
    var _Self=this;
    //配置
    opts=opts||{};
    //事件继承
    Ds.Extend(this, new Ds.EventDispatcher());
    //场景列表
    var _SceneList=[];
    Object.defineProperty(this, "Scenes", {get: function() {return _SceneList;},});
    //场景宽
    var _SceneWidth = opts.sceneWidth||2969;
    //场景高
    var _SceneHeight = opts.sceneHeight||1140;
    //视觉画布宽
    var _ViewWidth=opts.viewWidth||640;
    //画布区域
    var _ViewRect=new createjs.Rectangle(0, 0,_ViewWidth, _SceneHeight);;
    //是否自动计算自适应
    var _AutoReSize=opts.autoReSize!==undefined?opts.autoReSize:true;
    //进行debug测试
    var _Debug=opts.debug!==undefined?opts.debug:true;
    //是否循环
    var _Loop=opts.loop!==undefined?opts.loop:true;
    //计算屏幕补差的矩形区域
    var _MovieInViewRect=new createjs.Rectangle(-(_ViewWidth*3-_ViewWidth)/2, 0,_ViewWidth*3, _SceneHeight);
    //当前距离
    var _Distance=0;
    Object.defineProperty(this, "Distance", {
        get: function() {
            return _Distance;
        },
        set: function(value) {
          _Distance=value;
          UpDate();
        }
    });
    //总场景距离  _SceneWidth*(_SceneList.length);
    var _AllDistance=0;
    //var _AllDistance=_SceneWidth*(_SceneList.length);
    //平滑拖动管理对象
    var _SliderDistance = new Ds.gemo.SliderHVDistance(_Self, 'Distance', {
      touchDom:$('#screen'),
      interval:640,
      hasAutoSpeed:true,
      speedCut:opts.speedCut!==undefined?opts.speedCut:0.05,
      isLoop:_Loop,
      isVerticalTouch:false,
      touchDirection:false,
      maxSpeed:opts.maxSpeed!==undefined?opts.maxSpeed:15,
      minSpeed:0,
      min:0,
      max:_AllDistance,
    });
    //是否锁定
    Object.defineProperty(this, "Lock", {
        get: function() {
            return _SliderDistance.Lock;
        },
        set: function(value) {
          _SliderDistance.Lock=value;
        }
    });

    //主要容器
    var _View=new createjs.Container();
    Object.defineProperty(this, "View", {get: function() {return _View;},});
    //滚动容器
    var _Box=new createjs.Container();
    _View.addChild(_Box);
    //======================测试代码=================
    if(_Debug){
      _View.scaleX=_View.scaleY=0.25;
      _View.x=(640-640*_View.scaleX)/2;
      var shape=new createjs.Shape();
      shape.graphics.beginFill("red").drawRect(0, 0, 640, _MovieInViewRect.height);
      shape.alpha=0.5;
      _View.addChild(shape);
      var _readShape=new createjs.Shape();
      _readShape.graphics.beginFill("greed").drawRect(_MovieInViewRect.x, _MovieInViewRect.y, _MovieInViewRect.width, _MovieInViewRect.height);
      _readShape.alpha=0.5;
      _View.addChild(_readShape);
    }
    //======================测试代码=================

    /**
     * 添加场景列表
     * @param  {[type]} scenes [description]
     * @return {[type]}        [description]
     */
    this.AddSceneList=function(scenes){
      for (var i = 0; i < scenes.length; i++) {
        this.AddScene(scenes[i]);
      }
      ReSize();
    }
    /**
     * 添加一个场景
     * @param  {[type]} scene [description]
     * @return {[type]}       [description]
     */
    this.AddScene=function(scene){
      _SceneList.push(scene);
      scene.x=_SceneWidth*(_SceneList.length-1);
      scene.rect=new createjs.Rectangle(0, 0, _SceneWidth, _SceneHeight);
      _Box.addChild(scene);
      _AllDistance=_Loop?_SceneWidth*(_SceneList.length):_SceneWidth*(_SceneList.length)-_ViewWidth;
      _SliderDistance.MaxDistance=_AllDistance;
      scene.sceneID=_SceneList.length-1;//记录场景的编号
      scene.upChildList=[];
    };
    //如果有场景列表就进行场景列表的添加
    if(opts.scenes){this.AddSceneList(opts.scenes);}
    /**
     * [添加子对象更新数据]
     * @param  {[type]} child [子对象]
     * @param  {[type]} opts [子对象配置 可以只是一个数字，代表偏移量]
     * @param  {[type]} scene [对应的场景对象]
     * @return {[type]}       [description]
     */
    this.AddChildUpData=function (child,opts,scene) {
      if(!scene)scene=child.parent;
      var _childs=scene.upChildList;
      // console.log('AddChildUpData:',_childs.length);
      child.ox=child.x;
      child.oy=child.y;
      opts=opts||{};
      var _speed=Math.random()>0.5?_SceneWidth/8:-_SceneWidth/8;
      _speed=_speed/2+(_speed/2)*Math.random();
      if(typeof(opts)==='number')_speed=opts;
      else{
        if(opts.speed!==undefined)_speed=opts.speed;
      }
      child.speed=_speed;
      if(_childs.indexOf(child)===-1)_childs.push(child);
    }
    /**
     * 场景更新
     * @constructor
     */
    function UpDate() {
      //计算场景视觉补差  第一个场景补差
      var _sceneStart=_SceneList[0];
      if(_Distance>=_AllDistance-_ViewWidth*2)_sceneStart.x=_SceneWidth*_SceneList.length;
      else  _sceneStart.x=0;
      //计算场景视觉补差  最后一个场景补差
      var _sceneEnd=_SceneList[_SceneList.length-1];
      if(_Distance>=0&&_Distance<=_SceneWidth)_sceneEnd.x=-_SceneWidth;
      else _sceneEnd.x=_SceneWidth*(_SceneList.length-1);
      _Box.x=-_Distance;
      //进行显示的列表
      var _upList=[];
      //在场景里面的列表
      var _inViewList=[];
      //进行显示对象剔除算法
      var _scene;
      for (var i = 0; i < _SceneList.length; i++) {
        _scene=_SceneList[i];
        var _pt=_scene.localToLocal(0,0,_View);
        var _rect=_scene.rect;
        _rect.x=_pt.x;
        _rect.y=_pt.y;
        var _bool=_MovieInViewRect.intersects(_rect);
        _scene.visible=_bool;

        //计算显示的场景的进度百分百
        //_bool=_ViewRect.intersects(_rect)
        if(_bool){
          var _progress=0;
          var _w=_SceneWidth-_ViewWidth;
          _progress=-_pt.x/_w;
          _progress=Math.min(Math.max(_progress,0),1);
          _scene.progress=_progress;
          // if(i===0)console.log('_progress:',_progress);
          _upList.push(_scene);
          //对子对象进行更新处理
          ChildUpDate(_scene);
        }
        //计算在显示视图内的场景
        var _inRect=_ViewRect.intersection(_rect);
        _scene.inRect=_inRect;
        if(_inRect){
          _scene.inRectWidth=_inRect.width;
          _inViewList.push(_scene);
        }
      }
      var _sceneID=0;
      var _inViewList2=_inViewList.concat();
      // console.log('_inViewList2',_inViewList2);
      if(_inViewList2.length>=1){
        ArraySort(_inViewList2,'inRectWidth');
        _scene=_inViewList2[_inViewList2.length-1];
        _sceneID=_scene.sceneID;
      }
      _Self.ds({
        type:'update',
        scenes:_upList,//这里只会放需要显示的元素，相对场景上 当前移动进度比
        inViewScenes:_inViewList,//在视图内的场景
        sceneID:_sceneID,//当前在第几个场景
      });
    }
    /**
     * 对子对象进行更新处理
     * @param       {[type]} scene [description]
     * @constructor
     */
    function ChildUpDate(scene) {

      var _progress=scene.progress;
      var _childs=scene.upChildList;
      // console.log('ChildUpDate:',_childs.length);
      for (var i = 0; i < _childs.length; i++) {
        var _child=_childs[i];
        _child.x=(_child.ox-_child.speed/2)+_progress*_child.speed;
      }
    }
    /**
     * 按数组内指定参数升续排列
     * @param       {[type]} arr   [description]
     * @param       {[type]} value [description]
     * @constructor
     */
    function ArraySort(arr, value) {
      var compare = function(prop) {
        return function(obj1, obj2) {
          var val1 = obj1[prop];
          var val2 = obj2[prop];
          if (val1 < val2) {
            return -1;
          } else if (val1 > val2) {
            return 1;
          } else {
            return 0;
          }
        };
      };
      return arr.sort(compare(value));
    };
    //自适应
    window.addEventListener("resize", function() {
      ReSize();
      setTimeout(function() {ReSize();}, 100);
    });
    //计算自适应 _PopLayerContainer设置宽高
    function ReSize() {
      if(!_AutoReSize)return;
      var _width, _height, _pageScale, _actualH, _horizontal = false,
        _isInputState = false;
      _width = window.innerWidth;
      _height = window.innerHeight;
      //计算是否横屏
      if (_width > _height) _horizontal = true;
      else _horizontal = false;
      if (_width / _height > 3) {
        //算出竖屏幕下输入框状态下比例
        _isInputState = true;
      } else if (_width / _height < 12 / 7 && _width / _height > 1) {
        //算出竖屏幕下输入框状态下比例
        _isInputState = true;
        //说明这时候不会是横屏
        _horizontal = false;
      } else {
        //非输入状态
        _isInputState = false;
      }
      if (_horizontal) _screenWidth = 1138;
      else _screenWidth = 640;
      //计算缩放比例
      _pageScale = _width / _screenWidth;
      //计算实际高度
      _actualH = _height / _pageScale;
      if(_isInputState)return;
      //按高来自动适应
      var _s=_actualH/_SceneHeight;
      _View.scaleX=_View.scaleY=_s;
      //按高自适应后 视觉画布宽重新计算
      _s=_SceneHeight/_actualH;
      var _viewWidth=_screenWidth*_s;
      _ViewRect.width=_viewWidth;
      //视觉画布宽
      _ViewWidth=_viewWidth;
      //计算屏幕补差的矩形区域
      _MovieInViewRect.x=-(_ViewWidth*3-_ViewWidth)/2;
      _MovieInViewRect.y=0;
      _MovieInViewRect.width=_ViewWidth*3;
      _MovieInViewRect.height=_SceneHeight;
      //计算大的距离长度
      _AllDistance=_Loop?_SceneWidth*(_SceneList.length):_SceneWidth*(_SceneList.length)-_ViewWidth;
      _SliderDistance.MaxDistance=_AllDistance;
    }
    ReSize();
  }

  return root.Ds.createjs.display.GalleyModel;
}));
<|endoftext|>


<commit_before>/**
 * Client to connect to a darkwallet gateway.
 *
 * @param {String}   connect_uri Gateway websocket URI
 * @param {Function} handle_connect Callback to run when connected
 */
function GatewayClient(connect_uri, handle_connect) {
    var self = this;
    this.handler_map = {};
    this.websocket = new WebSocket(connect_uri);
    this.websocket.onopen = function(evt) {
        handle_connect();
    };
    this.websocket.onclose = function(evt) {
        self.on_close(evt);
    };
    this.websocket.onerror = function(evt) {
        self.on_error(evt);
    };
    this.websocket.onmessage = function(evt) {
        self._on_message(evt);
    };
}

/**
 * Get last height
 *
 * @param {Function} handle_fetch Callback to handle the returned height
 */
GatewayClient.prototype.fetch_last_height = function(handle_fetch) {
    GatewayClient._check_function(handle_fetch);

    this.make_request("fetch_last_height", [], function(response) {
        handle_fetch(response["error"], response["result"][0]);
    });
};

/**
 * Fetch transaction
 *
 * @param {String}   tx_hash Transaction identifier hash
 * @param {Function} handle_fetch Callback to handle the JSON object
 * representing the transaction
 */
GatewayClient.prototype.fetch_transaction = function(tx_hash, handle_fetch) {
    GatewayClient._check_function(handle_fetch);

    this.make_request("fetch_transaction", [tx_hash], function(response) {
        handle_fetch(response["error"], response["result"][0]);
    });
};

/**
 * Fetch history
 *
 * @param {String}   address
 * @param {Function} handle_fetch Callback to handle the JSON object
 * representing the history of the address
 */
GatewayClient.prototype.fetch_history = function(address, handle_fetch) {
    GatewayClient._check_function(handle_fetch);

    this.make_request("fetch_history", [address], function(response) {
        handle_fetch(response["error"], response["result"][0]);
    });
};

GatewayClient.prototype.fetch_stealth = function(
    prefix, handle_fetch, from_height)
{
    GatewayClient._check_function(handle_fetch);

    this.make_request("fetch_stealth", [prefix, from_height],
        function(response) {
            handle_fetch(response["error"], response["result"][0]);
        });
};

/**
 * Subscribe
 *
 * @param {String}   address
 * @param {Function} handle_fetch Callback to handle subscription result
 * @param {Function} handle_update Callback to handle the JSON object
 * representing for updates
 */
GatewayClient.prototype.subscribe = function(
    address, handle_fetch, handle_update)
{
    var self = this;
    this.make_request("subscribe_address", [address], function(response) {
        handle_fetch(response["error"], response["result"][0]);
        if (handle_update) {
            self.handler_map["update." + address] = handle_update;
        }
    });
}

GatewayClient.prototype.fetch_block_header = function(index, handle_fetch) {
    GatewayClient._check_function(handle_fetch);

    this.make_request("fetch_block_header", [index], function(response) {
        handle_fetch(response["error"], response["result"][0]);
    });
};

GatewayClient.prototype.fetch_block_transaction_hashes = function(
    index, handle_fetch)
{
    GatewayClient._check_function(handle_fetch);

    this.make_request("fetch_block_transaction_hashes", [index],
        function(response) {
            handle_fetch(response["error"], response["result"][0]);
        });
};

GatewayClient.prototype.fetch_spend = function(outpoint, handle_fetch) {
    GatewayClient._check_function(handle_fetch);

    this.make_request("fetch_spend", [outpoint], function(response) {
        handle_fetch(response["error"], response["result"][0]);
    });
};

GatewayClient.prototype.fetch_transaction_index = function(
    tx_hash, handle_fetch)
{
    GatewayClient._check_function(handle_fetch);

    this.make_request("fetch_transaction_index", [tx_hash],
        function(response) {
            result = response["result"];
            handle_fetch(response["error"], result[0], result[1]);
        });
};

GatewayClient.prototype.fetch_block_height = function(blk_hash, handle_fetch)
{
    GatewayClient._check_function(handle_fetch);

    this.make_request("fetch_block_height", [blk_hash], function(response) {
        handle_fetch(response["error"], response["result"][0]);
    });
};

GatewayClient.prototype.broadcast_transaction = function(
    raw_tx, handle_fetch)
{
    GatewayClient._check_function(handle_fetch);

    this.make_request("broadcast_transaction", [raw_tx], function(response) {
        handle_fetch(response["error"], response["result"][0]);
    });
};

/**
 * Renew
 *
 * @param {String}   address
 * @param {Function} handle_fetch Callback to handle subscription result
 * @param {Function} handle_update Callback to handle the JSON object
 * representing for updates
 */
GatewayClient.prototype.renew = function(address, handle_fetch, handle_update)
{
    var self = this;
    this.make_request("renew_address", [address], function(response) {
        handle_fetch(response["error"], response["result"][0]);
        if (handle_update) {
            self.handler_map["update."+address] = handle_update;
        }
    });
}

/**
 * Chan functionality
 */
GatewayClient.prototype.chan_post = function(section_name, thread_id, data, handle_fetch) {
    GatewayClient._check_function(handle_fetch);

    this.make_request("chan_post", [section_name, thread_id, data], function(response) {
        if (handle_fetch)
            console.log("raw chan post", response["result"]);
            handle_fetch(response["error"], response["result"]);
    });
};

GatewayClient.prototype.chan_list = function(section_name, handle_fetch) {
    GatewayClient._check_function(handle_fetch);

    this.make_request("chan_list", [section_name], function(response) {
        if (handle_fetch)
            handle_fetch(response["error"], response["result"]);
    });
};

GatewayClient.prototype.chan_get = function(section_name, thread_id, handle_fetch) {
    GatewayClient._check_function(handle_fetch);

    this.make_request("chan_get", [section_name, thread_id], function(response) {
        if (handle_fetch)
            handle_fetch(response["error"], response["result"]);
    });
};

GatewayClient.prototype.chan_subscribe = function(section_name, thread_id, handle_fetch, handle_update) {
    GatewayClient._check_function(handle_fetch);
    var self = this;
    this.make_request("chan_subscribe", [section_name, thread_id], function(response) {
        if (handle_fetch)
            handle_fetch(response["error"], response["result"]);
        if (handle_update) {
            self.handler_map["chan.update." + thread_id] = handle_update;
        }

    });
};

/**
 * Make requests to the server
 *
 * @param {String} command
 * @param {Array} params
 * @param {Function} handler
 */
GatewayClient.prototype.make_request = function(command, params, handler) {
    GatewayClient._check_function(handler);

    var id = GatewayClient._random_integer();
    var request = {
        "id": id,
        "command": command,
        "params": params
    };
    var message = JSON.stringify(request);
    this.websocket.send(message);
    this.handler_map[id] = handler;
};

/**
 * Close event handler
 *
 * @param {Object} evt event
 */
GatewayClient.prototype.on_close = function(evt) {
};

/**
 * Error event handler
 *
 * @param {Object} evt event
 *
 * @throws {Object}
 */
GatewayClient.prototype.on_error = function(evt) {
    throw evt;
};

/**
 * After triggering message event, calls to the handler of the petition
 *
 * @param {Object} evt event
 * @private
 */
GatewayClient.prototype._on_message = function(evt) {
    this.on_message(evt)
    response = JSON.parse(evt.data);
    id = response.id;
    // Should be a separate map entirely. This is a hack.
    if (response.type == "update")
        id = "update." + response.address;
    if (response.type == "chan_update")
        id = "chan.update." + response.thread;
    // Prefer flat code over nested.
    if (!this.handler_map[id]) {
        console.log("Handler not found", id);
        return;
    }
    handler = this.handler_map[id];
    handler(response);
};

/**
 * Message event handler
 *
 * @param {Object} evt event
 */
GatewayClient.prototype.on_message = function(evt) {
}

/**
 * (Pseudo-)Random integer generator
 *
 * @return {Number} Random integer
 * @private
 */
GatewayClient._random_integer = function() {
    return Math.floor((Math.random() * 4294967296));
};

/**
 * Checks if param can be executed
 *
 * @param {Function} Function to be checked
 *
 * @throws {String} Parameter is not a function
 * @protected
 */
GatewayClient._check_function = function(func) {
    if (typeof func !== 'function') {
        throw "Parameter is not a function";
    }
};

<commit_msg>set connected.<commit_after>/**
 * Client to connect to a darkwallet gateway.
 *
 * @param {String}   connect_uri Gateway websocket URI
 * @param {Function} handle_connect Callback to run when connected
 */
function GatewayClient(connect_uri, handle_connect) {
    var self = this;
    this.handler_map = {};
    this.connected = false;
    this.websocket = new WebSocket(connect_uri);
    this.websocket.onopen = function(evt) {
        self.connected = true;
        handle_connect();
    };
    this.websocket.onclose = function(evt) {
        self.connected = false;
        self.on_close(evt);
    };
    this.websocket.onerror = function(evt) {
        self.on_error(evt);
    };
    this.websocket.onmessage = function(evt) {
        self._on_message(evt);
    };
}

/**
 * Get last height
 *
 * @param {Function} handle_fetch Callback to handle the returned height
 */
GatewayClient.prototype.fetch_last_height = function(handle_fetch) {
    GatewayClient._check_function(handle_fetch);

    this.make_request("fetch_last_height", [], function(response) {
        handle_fetch(response["error"], response["result"][0]);
    });
};

/**
 * Fetch transaction
 *
 * @param {String}   tx_hash Transaction identifier hash
 * @param {Function} handle_fetch Callback to handle the JSON object
 * representing the transaction
 */
GatewayClient.prototype.fetch_transaction = function(tx_hash, handle_fetch) {
    GatewayClient._check_function(handle_fetch);

    this.make_request("fetch_transaction", [tx_hash], function(response) {
        handle_fetch(response["error"], response["result"][0]);
    });
};

/**
 * Fetch history
 *
 * @param {String}   address
 * @param {Function} handle_fetch Callback to handle the JSON object
 * representing the history of the address
 */
GatewayClient.prototype.fetch_history = function(address, handle_fetch) {
    GatewayClient._check_function(handle_fetch);

    this.make_request("fetch_history", [address], function(response) {
        handle_fetch(response["error"], response["result"][0]);
    });
};

GatewayClient.prototype.fetch_stealth = function(
    prefix, handle_fetch, from_height)
{
    GatewayClient._check_function(handle_fetch);

    this.make_request("fetch_stealth", [prefix, from_height],
        function(response) {
            handle_fetch(response["error"], response["result"][0]);
        });
};

/**
 * Subscribe
 *
 * @param {String}   address
 * @param {Function} handle_fetch Callback to handle subscription result
 * @param {Function} handle_update Callback to handle the JSON object
 * representing for updates
 */
GatewayClient.prototype.subscribe = function(
    address, handle_fetch, handle_update)
{
    var self = this;
    this.make_request("subscribe_address", [address], function(response) {
        handle_fetch(response["error"], response["result"][0]);
        if (handle_update) {
            self.handler_map["update." + address] = handle_update;
        }
    });
}

GatewayClient.prototype.fetch_block_header = function(index, handle_fetch) {
    GatewayClient._check_function(handle_fetch);

    this.make_request("fetch_block_header", [index], function(response) {
        handle_fetch(response["error"], response["result"][0]);
    });
};

GatewayClient.prototype.fetch_block_transaction_hashes = function(
    index, handle_fetch)
{
    GatewayClient._check_function(handle_fetch);

    this.make_request("fetch_block_transaction_hashes", [index],
        function(response) {
            handle_fetch(response["error"], response["result"][0]);
        });
};

GatewayClient.prototype.fetch_spend = function(outpoint, handle_fetch) {
    GatewayClient._check_function(handle_fetch);

    this.make_request("fetch_spend", [outpoint], function(response) {
        handle_fetch(response["error"], response["result"][0]);
    });
};

GatewayClient.prototype.fetch_transaction_index = function(
    tx_hash, handle_fetch)
{
    GatewayClient._check_function(handle_fetch);

    this.make_request("fetch_transaction_index", [tx_hash],
        function(response) {
            result = response["result"];
            handle_fetch(response["error"], result[0], result[1]);
        });
};

GatewayClient.prototype.fetch_block_height = function(blk_hash, handle_fetch)
{
    GatewayClient._check_function(handle_fetch);

    this.make_request("fetch_block_height", [blk_hash], function(response) {
        handle_fetch(response["error"], response["result"][0]);
    });
};

GatewayClient.prototype.broadcast_transaction = function(
    raw_tx, handle_fetch)
{
    GatewayClient._check_function(handle_fetch);

    this.make_request("broadcast_transaction", [raw_tx], function(response) {
        handle_fetch(response["error"], response["result"][0]);
    });
};

/**
 * Renew
 *
 * @param {String}   address
 * @param {Function} handle_fetch Callback to handle subscription result
 * @param {Function} handle_update Callback to handle the JSON object
 * representing for updates
 */
GatewayClient.prototype.renew = function(address, handle_fetch, handle_update)
{
    var self = this;
    this.make_request("renew_address", [address], function(response) {
        handle_fetch(response["error"], response["result"][0]);
        if (handle_update) {
            self.handler_map["update."+address] = handle_update;
        }
    });
}

/**
 * Chan functionality
 */
GatewayClient.prototype.chan_post = function(section_name, thread_id, data, handle_fetch) {
    GatewayClient._check_function(handle_fetch);

    this.make_request("chan_post", [section_name, thread_id, data], function(response) {
        if (handle_fetch)
            console.log("raw chan post", response["result"]);
            handle_fetch(response["error"], response["result"]);
    });
};

GatewayClient.prototype.chan_list = function(section_name, handle_fetch) {
    GatewayClient._check_function(handle_fetch);

    this.make_request("chan_list", [section_name], function(response) {
        if (handle_fetch)
            handle_fetch(response["error"], response["result"]);
    });
};

GatewayClient.prototype.chan_get = function(section_name, thread_id, handle_fetch) {
    GatewayClient._check_function(handle_fetch);

    this.make_request("chan_get", [section_name, thread_id], function(response) {
        if (handle_fetch)
            handle_fetch(response["error"], response["result"]);
    });
};

GatewayClient.prototype.chan_subscribe = function(section_name, thread_id, handle_fetch, handle_update) {
    GatewayClient._check_function(handle_fetch);
    var self = this;
    this.make_request("chan_subscribe", [section_name, thread_id], function(response) {
        if (handle_fetch)
            handle_fetch(response["error"], response["result"]);
        if (handle_update) {
            self.handler_map["chan.update." + thread_id] = handle_update;
        }

    });
};

/**
 * Make requests to the server
 *
 * @param {String} command
 * @param {Array} params
 * @param {Function} handler
 */
GatewayClient.prototype.make_request = function(command, params, handler) {
    GatewayClient._check_function(handler);

    var id = GatewayClient._random_integer();
    var request = {
        "id": id,
        "command": command,
        "params": params
    };
    var message = JSON.stringify(request);
    this.websocket.send(message);
    this.handler_map[id] = handler;
};

/**
 * Close event handler
 *
 * @param {Object} evt event
 */
GatewayClient.prototype.on_close = function(evt) {
};

/**
 * Error event handler
 *
 * @param {Object} evt event
 *
 * @throws {Object}
 */
GatewayClient.prototype.on_error = function(evt) {
    throw evt;
};

/**
 * After triggering message event, calls to the handler of the petition
 *
 * @param {Object} evt event
 * @private
 */
GatewayClient.prototype._on_message = function(evt) {
    this.on_message(evt)
    response = JSON.parse(evt.data);
    id = response.id;
    // Should be a separate map entirely. This is a hack.
    if (response.type == "update")
        id = "update." + response.address;
    if (response.type == "chan_update")
        id = "chan.update." + response.thread;
    // Prefer flat code over nested.
    if (!this.handler_map[id]) {
        console.log("Handler not found", id);
        return;
    }
    handler = this.handler_map[id];
    handler(response);
};

/**
 * Message event handler
 *
 * @param {Object} evt event
 */
GatewayClient.prototype.on_message = function(evt) {
}

/**
 * (Pseudo-)Random integer generator
 *
 * @return {Number} Random integer
 * @private
 */
GatewayClient._random_integer = function() {
    return Math.floor((Math.random() * 4294967296));
};

/**
 * Checks if param can be executed
 *
 * @param {Function} Function to be checked
 *
 * @throws {String} Parameter is not a function
 * @protected
 */
GatewayClient._check_function = function(func) {
    if (typeof func !== 'function') {
        throw "Parameter is not a function";
    }
};

<|endoftext|>


<commit_before>var shortcode = require('shortcode-parser'),
    each      = require('lodash.forEach'),
    merge     = require('lodash.merge'),
    plugin;

plugin = function(opts) {
    // loop through all the registered shortcodes
    each(opts.shortcodes, (fn, name) => {
        shortcode.add(name, fn);
    });

    return (files, metalsmith, done) => {
        each(files, (file, path) => {
            if (!file.shortcodes) { return; }
            var cnt = file.contents.toString(),
                data = merge({}, file, metalsmith.metadata());

            if (opts.clean) {
                // clean possible <p> tags around
                // the shortcodes that the markdown parser creates
                cnt = cnt.replace(/(<p>)(\[.*?\])(<\/p>)/gi, (all, p, code) => {
                    return code;
                });
            }

            file.contents = new Buffer(shortcode.parse(cnt, data));
        });
        done();
    };
};

module.exports = plugin;

<commit_msg>Removing camel casing for case-sensitive systems<commit_after>var shortcode = require('shortcode-parser'),
    each      = require('lodash.foreach'),
    merge     = require('lodash.merge'),
    plugin;

plugin = function(opts) {
    // loop through all the registered shortcodes
    each(opts.shortcodes, (fn, name) => {
        shortcode.add(name, fn);
    });

    return (files, metalsmith, done) => {
        each(files, (file, path) => {
            if (!file.shortcodes) { return; }
            var cnt = file.contents.toString(),
                data = merge({}, file, metalsmith.metadata());

            if (opts.clean) {
                // clean possible <p> tags around
                // the shortcodes that the markdown parser creates
                cnt = cnt.replace(/(<p>)(\[.*?\])(<\/p>)/gi, (all, p, code) => {
                    return code;
                });
            }

            file.contents = new Buffer(shortcode.parse(cnt, data));
        });
        done();
    };
};

module.exports = plugin;

<|endoftext|>


<commit_before>mgoAdmin.controller('mgoAdminMenu', function($scope, $just, $state) {

    $scope.User = null;
    // check if the user is logged in or not
    Just.auth_check().then(
        function (data) {

            $scope.User = data;
            if (data.login) {

            } else {
                $state.go("login");
            }
        }, function () {
            $state.go("login");
        }
    );

    $scope.handleLogout = function() {
        $just.auth_logout().then(function() {
            $state.go("login");
        });
    }
});
<commit_msg>fix Just renaming bug<commit_after>mgoAdmin.controller('mgoAdminMenu', function($scope, $just, $state) {

    $scope.User = null;
    // check if the user is logged in or not
    just.auth_check().then(
        function (data) {

            $scope.User = data;
            if (data.login) {

            } else {
                $state.go("login");
            }
        }, function () {
            $state.go("login");
        }
    );

    $scope.handleLogout = function() {
        $just.auth_logout().then(function() {
            $state.go("login");
        });
    }
});
<|endoftext|>