<commit_before>;(function(){
// windows: running "npm blah" in this folder will invoke WSH, not node.
if (typeof WScript !== "undefined") {
  WScript.echo("npm does not work when run\n"
              +"with the Windows Scripting Host\n\n"
              +"'cd' to a different directory,\n"
              +"or type 'npm.cmd <args>',\n"
              +"or type 'node npm <args>'.")
  WScript.quit(1)
  return
}

// FIXME there really ought to be a path.split in node core
require("path").SPLIT_CHAR = process.platform === "win32" ? "\\" : "/"

var EventEmitter = require("events").EventEmitter
  , npm = module.exports = new EventEmitter
  , config = require("./config.js")
  , set = require("./utils/set.js")
  , get = require("./utils/get.js")
  , ini = require("./utils/ini.js")
  , log = require("./utils/log.js")
  , fs = require("graceful-fs")
  , path = require("path")
  , abbrev = require("abbrev")
  , which = require("which")
  , semver = require("semver")
  , findPrefix = require("./utils/find-prefix.js")
  , getUid = require("./utils/uid-number.js")
  , mkdir = require("./utils/mkdir-p.js")
  , slide = require("slide")
  , chain = slide.chain

npm.commands = {}
npm.ELIFECYCLE = {}
npm.E404 = {}
npm.EPUBLISHCONFLICT = {}
npm.EJSONPARSE = {}
npm.EISGIT = {}
npm.ECYCLE = {}
npm.ENOTSUP = {}

// HACK for windows
if (process.platform === "win32") {
  // stub in unavailable methods from process and fs binding
  if (!process.getuid) process.getuid = function() {}
  if (!process.getgid) process.getgid = function() {}
  var fsBinding = process.binding("fs")
  if (!fsBinding.chown) fsBinding.chown = function() {
    var cb = arguments[arguments.length - 1]
    if (typeof cb == "function") cb()
  }

  // patch rename/renameSync, but this should really be fixed in node
  var _fsRename = fs.rename
    , _fsPathPatch
  _fsPathPatch = function(p) {
    return p && p.replace(/\\/g, "/") || p;
  }
  fs.rename = function(p1, p2) {
    arguments[0] = _fsPathPatch(p1)
    arguments[1] = _fsPathPatch(p2)
    return _fsRename.apply(fs, arguments);
  }
}

try {
  // startup, ok to do this synchronously
  var j = JSON.parse(fs.readFileSync(
    path.join(__dirname, "../package.json"))+"")
  npm.version = j.version
  npm.nodeVersionRequired = j.engines.node
  if (!semver.satisfies(process.version, j.engines.node)) {
    log.error([""
              ,"npm requires node version: "+j.engines.node
              ,"And you have: "+process.version
              ,"which is not satisfactory."
              ,""
              ,"Bad things will likely happen.  You have been warned."
              ,""].join("\n"), "unsupported version")
  }
} catch (ex) {
  try {
    log(ex, "error reading version")
  } catch (er) {}
  npm.version = ex
}

var commandCache = {}
  // short names for common things
  , aliases = { "rm" : "uninstall"
              , "r" : "uninstall"
              , "un" : "uninstall"
              , "unlink" : "uninstall"
              , "remove" : "uninstall"
              , "rb" : "rebuild"
              , "list" : "ls"
              , "la" : "ls"
              , "ll" : "ls"
              , "ln" : "link"
              , "i" : "install"
              , "up" : "update"
              , "c" : "config"
              , "info" : "view"
              , "show" : "view"
              , "find" : "search"
              , "s" : "search"
              , "se" : "search"
              , "author" : "owner"
              , "home" : "docs"
              , "unstar": "star" // same function
              , "apihelp" : "help"
              , "login": "adduser"
              }

  , aliasNames = Object.keys(aliases)
  // these are filenames in .
  , cmdList = [ "install"
              , "uninstall"
              , "cache"
              , "config"
              , "set"
              , "get"
              , "update"
              , "outdated"
              , "prune"
              , "submodule"
              , "pack"

              , "rebuild"
              , "link"

              , "publish"
              , "star"
              , "tag"
              , "adduser"
              , "unpublish"
              , "owner"
              , "deprecate"
              , "shrinkwrap"

              , "help"
              , "help-search"
              , "ls"
              , "search"
              , "view"
              , "init"
              , "version"
              , "edit"
              , "explore"
              , "docs"
              , "bugs"
              , "faq"
              , "root"
              , "prefix"
              , "bin"
              , "whoami"

              , "test"
              , "stop"
              , "start"
              , "restart"
              , "run-script"
              , "completion"
              ]
  , plumbing = [ "build"
               , "unbuild"
               , "xmas"
               , "substack"
               ]
  , fullList = npm.fullList = cmdList.concat(aliasNames).filter(function (c) {
      return plumbing.indexOf(c) === -1
    })
  , abbrevs = abbrev(fullList)

Object.keys(abbrevs).concat(plumbing).forEach(function addCommand (c) {
  Object.defineProperty(npm.commands, c, { get : function () {
    if (!loaded) throw new Error(
      "Call npm.load(conf, cb) before using this command.\n"+
      "See the README.md or cli.js for example usage.")
    var a = npm.deref(c)
    if (c === "la" || c === "ll") {
      npm.config.set("long", true)
    }
    npm.command = c
    if (commandCache[a]) return commandCache[a]
    var cmd = require(__dirname+"/"+a+".js")
    commandCache[a] = function () {
      var args = Array.prototype.slice.call(arguments, 0)
      if (typeof args[args.length - 1] !== "function") {
        args.push(defaultCb)
      }
      if (args.length === 1) args.unshift([])
      cmd.apply(npm, args)
    }
    Object.keys(cmd).forEach(function (k) {
      commandCache[a][k] = cmd[k]
    })
    return commandCache[a]
  }, enumerable: fullList.indexOf(c) !== -1 })

  // make css-case commands callable via camelCase as well
  if (c.match(/\-([a-z])/)) {
    addCommand(c.replace(/\-([a-z])/g, function (a, b) {
      return b.toUpperCase()
    }))
  }
})

function defaultCb (er, data) {
  if (er) console.error(er.stack || er.message)
  else console.log(data)
}

npm.deref = function (c) {
  if (!c) return ""
  if (c.match(/[A-Z]/)) c = c.replace(/([A-Z])/g, function (m) {
    return "-" + m.toLowerCase()
  })
  if (plumbing.indexOf(c) !== -1) return c
  var a = abbrevs[c]
  if (aliases[a]) a = aliases[a]
  return a
}

var loaded = false
  , loading = false
  , loadErr = null
  , loadListeners = []

function loadCb (er) {
  loadListeners.forEach(function (cb) {
    process.nextTick(cb.bind(npm, er, npm))
  })
  loadListeners.length = 0
}

npm.load = function (conf, cb_) {
  if (!cb_ && typeof conf === "function") cb_ = conf , conf = {}
  if (!cb_) cb_ = function () {}
  if (!conf) conf = {}
  loadListeners.push(cb_)
  if (loaded || loadErr) return cb(loadErr)
  if (loading) return
  loading = true
  var onload = true

  function cb (er) {
    if (loadErr) return
    loaded = true
    loadCb(loadErr = er)
    if (onload = onload && npm.config.get("onload-script")) {
      require(onload)
      onload = false
    }
  }

  log.waitForConfig()

  load(npm, conf, cb)
}

function load (npm, conf, cb) {
  which(process.argv[0], function (er, node) {
    if (!er && node.toUpperCase() !== process.execPath.toUpperCase()) {
      log.verbose("node symlink", node)
      process.execPath = node
      process.installPrefix = path.resolve(node, "..", "..")
    }

    // look up configs
    //console.error("about to look up configs")

    ini.resolveConfigs(conf, function (er) {
      //console.error("back from config lookup", er && er.stack)
      if (er) return cb(er)

      var umask = parseInt(conf.umask, 8)
      npm.modes = { exec: 0777 & (~umask)
                  , file: 0666 & (~umask)
                  , umask: umask }

      chain([ [ loadPrefix, npm, conf ]
            , [ setUser, ini.configList, ini.defaultConfig ]
            , [ loadUid, npm, conf ]
            ], cb)
    })
  })
}

function loadPrefix (npm, conf, cb) {
  // try to guess at a good node_modules location.
  var p
    , gp
  if (!conf.hasOwnProperty("prefix")) {
    p = process.cwd()
  } else {
    p = npm.config.get("prefix")
  }
  gp = npm.config.get("prefix")

  findPrefix(p, function (er, p) {
    Object.defineProperty(npm, "localPrefix",
      { get : function () { return p }
      , set : function (r) { return p = r }
      , enumerable : true
      })
    // the prefix MUST exist, or else nothing works.
    if (!npm.config.get("global")) {
      mkdir(p, npm.modes.exec, null, null, true, next)
    } else {
      next(er)
    }
  })

  findPrefix(gp, function (er, gp) {
    Object.defineProperty(npm, "globalPrefix",
      { get : function () { return gp }
      , set : function (r) { return gp = r }
      , enumerable : true
      })
    // the prefix MUST exist, or else nothing works.
    mkdir(gp, npm.modes.exec, null, null, true, next)
  })

  var i = 2
    , errState = null
  function next (er) {
    if (errState) return
    if (er) return cb(errState = er)
    if (--i === 0) return cb()
  }
}

function loadUid (npm, conf, cb) {
  // if we're not in unsafe-perm mode, then figure out who
  // to run stuff as.  Do this first, to support `npm update npm -g`
  if (!npm.config.get("unsafe-perm")) {
    getUid(npm.config.get("user"), npm.config.get("group"), cb)
  } else {
    process.nextTick(cb)
  }
}

function setUser (cl, dc, cb) {
  // If global, leave it as-is.
  // If not global, then set the user to the owner of the prefix folder.
  // Just set the default, so it can be overridden.
  if (cl.get("global")) return cb()
  if (process.env.SUDO_UID) {
    dc.user = +(process.env.SUDO_UID)
    return cb()
  }

  var prefix = path.resolve(cl.get("prefix"))
  mkdir(prefix, function (er) {
    if (er) {
      log.error(prefix, "could not create prefix directory")
      return cb(er)
    }
    fs.stat(prefix, function (er, st) {
      dc.user = st && st.uid
      return cb(er)
    })
  })
}

npm.config =
  { get : function (key) { return ini.get(key) }
  , set : function (key, val) { return ini.set(key, val, "cli") }
  , del : function (key, val) { return ini.del(key, val, "cli") }
  }

Object.defineProperty(npm, "prefix",
  { get : function () {
      return npm.config.get("global") ? npm.globalPrefix : npm.localPrefix
    }
  , set : function (r) {
      var k = npm.config.get("global") ? "globalPrefix" : "localPrefix"
      return npm[k] = r
    }
  , enumerable : true
  })

Object.defineProperty(npm, "bin",
  { get : function () {
      if (npm.config.get("global")) return npm.globalBin
      return path.resolve(npm.root, ".bin")
    }
  , enumerable : true
  })

Object.defineProperty(npm, "globalBin",
  { get : function () {
      var b = npm.globalPrefix
      if (process.platform !== "win32") b = path.resolve(b, "bin")
      return b
    }
  })

Object.defineProperty(npm, "dir",
  { get : function () {
      if (npm.config.get("global")) return npm.globalDir
      return path.resolve(npm.prefix, "node_modules")
    }
  , enumerable : true
  })

Object.defineProperty(npm, "globalDir",
  { get : function () {
      return (process.platform !== "win32")
           ? path.resolve(npm.globalPrefix, "lib", "node_modules")
           : path.resolve(npm.globalPrefix, "node_modules")
    }
  , enumerable : true
  })

Object.defineProperty(npm, "root",
  { get : function () { return npm.dir } })

Object.defineProperty(npm, "cache",
  { get : function () { return npm.config.get("cache") }
  , set : function (r) { return npm.config.set("cache", r) }
  , enumerable : true
  })

var tmpFolder
Object.defineProperty(npm, "tmp",
  { get : function () {
      if (!tmpFolder) tmpFolder = "npm-"+Date.now()
      return path.resolve(npm.config.get("tmp"), tmpFolder)
    }
  , enumerable : true
  })

// the better to repl you with
Object.getOwnPropertyNames(npm.commands).forEach(function (n) {
  if (npm.hasOwnProperty(n)) return

  Object.defineProperty(npm, n, { get: function () {
    return function () {
      var args = Array.prototype.slice.call(arguments, 0)
        , cb = defaultCb

      if (args.length === 1 && Array.isArray(args[0])) {
        args = args[0]
      }

      if (typeof args[args.length - 1] === "function") {
        cb = args.pop()
      }

      npm.commands[n](args, cb)
    }
  }, enumerable: false, configurable: true })
})

if (require.main === module) {
  require("../bin/npm-cli.js")
}
})()
<commit_msg>Alias adduser to add-user<commit_after>;(function(){
// windows: running "npm blah" in this folder will invoke WSH, not node.
if (typeof WScript !== "undefined") {
  WScript.echo("npm does not work when run\n"
              +"with the Windows Scripting Host\n\n"
              +"'cd' to a different directory,\n"
              +"or type 'npm.cmd <args>',\n"
              +"or type 'node npm <args>'.")
  WScript.quit(1)
  return
}

// FIXME there really ought to be a path.split in node core
require("path").SPLIT_CHAR = process.platform === "win32" ? "\\" : "/"

var EventEmitter = require("events").EventEmitter
  , npm = module.exports = new EventEmitter
  , config = require("./config.js")
  , set = require("./utils/set.js")
  , get = require("./utils/get.js")
  , ini = require("./utils/ini.js")
  , log = require("./utils/log.js")
  , fs = require("graceful-fs")
  , path = require("path")
  , abbrev = require("abbrev")
  , which = require("which")
  , semver = require("semver")
  , findPrefix = require("./utils/find-prefix.js")
  , getUid = require("./utils/uid-number.js")
  , mkdir = require("./utils/mkdir-p.js")
  , slide = require("slide")
  , chain = slide.chain

npm.commands = {}
npm.ELIFECYCLE = {}
npm.E404 = {}
npm.EPUBLISHCONFLICT = {}
npm.EJSONPARSE = {}
npm.EISGIT = {}
npm.ECYCLE = {}
npm.ENOTSUP = {}

// HACK for windows
if (process.platform === "win32") {
  // stub in unavailable methods from process and fs binding
  if (!process.getuid) process.getuid = function() {}
  if (!process.getgid) process.getgid = function() {}
  var fsBinding = process.binding("fs")
  if (!fsBinding.chown) fsBinding.chown = function() {
    var cb = arguments[arguments.length - 1]
    if (typeof cb == "function") cb()
  }

  // patch rename/renameSync, but this should really be fixed in node
  var _fsRename = fs.rename
    , _fsPathPatch
  _fsPathPatch = function(p) {
    return p && p.replace(/\\/g, "/") || p;
  }
  fs.rename = function(p1, p2) {
    arguments[0] = _fsPathPatch(p1)
    arguments[1] = _fsPathPatch(p2)
    return _fsRename.apply(fs, arguments);
  }
}

try {
  // startup, ok to do this synchronously
  var j = JSON.parse(fs.readFileSync(
    path.join(__dirname, "../package.json"))+"")
  npm.version = j.version
  npm.nodeVersionRequired = j.engines.node
  if (!semver.satisfies(process.version, j.engines.node)) {
    log.error([""
              ,"npm requires node version: "+j.engines.node
              ,"And you have: "+process.version
              ,"which is not satisfactory."
              ,""
              ,"Bad things will likely happen.  You have been warned."
              ,""].join("\n"), "unsupported version")
  }
} catch (ex) {
  try {
    log(ex, "error reading version")
  } catch (er) {}
  npm.version = ex
}

var commandCache = {}
  // short names for common things
  , aliases = { "rm" : "uninstall"
              , "r" : "uninstall"
              , "un" : "uninstall"
              , "unlink" : "uninstall"
              , "remove" : "uninstall"
              , "rb" : "rebuild"
              , "list" : "ls"
              , "la" : "ls"
              , "ll" : "ls"
              , "ln" : "link"
              , "i" : "install"
              , "up" : "update"
              , "c" : "config"
              , "info" : "view"
              , "show" : "view"
              , "find" : "search"
              , "s" : "search"
              , "se" : "search"
              , "author" : "owner"
              , "home" : "docs"
              , "unstar": "star" // same function
              , "apihelp" : "help"
              , "login": "adduser"
              , "add-user": "adduser"
              }

  , aliasNames = Object.keys(aliases)
  // these are filenames in .
  , cmdList = [ "install"
              , "uninstall"
              , "cache"
              , "config"
              , "set"
              , "get"
              , "update"
              , "outdated"
              , "prune"
              , "submodule"
              , "pack"

              , "rebuild"
              , "link"

              , "publish"
              , "star"
              , "tag"
              , "adduser"
              , "unpublish"
              , "owner"
              , "deprecate"
              , "shrinkwrap"

              , "help"
              , "help-search"
              , "ls"
              , "search"
              , "view"
              , "init"
              , "version"
              , "edit"
              , "explore"
              , "docs"
              , "bugs"
              , "faq"
              , "root"
              , "prefix"
              , "bin"
              , "whoami"

              , "test"
              , "stop"
              , "start"
              , "restart"
              , "run-script"
              , "completion"
              ]
  , plumbing = [ "build"
               , "unbuild"
               , "xmas"
               , "substack"
               ]
  , fullList = npm.fullList = cmdList.concat(aliasNames).filter(function (c) {
      return plumbing.indexOf(c) === -1
    })
  , abbrevs = abbrev(fullList)

Object.keys(abbrevs).concat(plumbing).forEach(function addCommand (c) {
  Object.defineProperty(npm.commands, c, { get : function () {
    if (!loaded) throw new Error(
      "Call npm.load(conf, cb) before using this command.\n"+
      "See the README.md or cli.js for example usage.")
    var a = npm.deref(c)
    if (c === "la" || c === "ll") {
      npm.config.set("long", true)
    }
    npm.command = c
    if (commandCache[a]) return commandCache[a]
    var cmd = require(__dirname+"/"+a+".js")
    commandCache[a] = function () {
      var args = Array.prototype.slice.call(arguments, 0)
      if (typeof args[args.length - 1] !== "function") {
        args.push(defaultCb)
      }
      if (args.length === 1) args.unshift([])
      cmd.apply(npm, args)
    }
    Object.keys(cmd).forEach(function (k) {
      commandCache[a][k] = cmd[k]
    })
    return commandCache[a]
  }, enumerable: fullList.indexOf(c) !== -1 })

  // make css-case commands callable via camelCase as well
  if (c.match(/\-([a-z])/)) {
    addCommand(c.replace(/\-([a-z])/g, function (a, b) {
      return b.toUpperCase()
    }))
  }
})

function defaultCb (er, data) {
  if (er) console.error(er.stack || er.message)
  else console.log(data)
}

npm.deref = function (c) {
  if (!c) return ""
  if (c.match(/[A-Z]/)) c = c.replace(/([A-Z])/g, function (m) {
    return "-" + m.toLowerCase()
  })
  if (plumbing.indexOf(c) !== -1) return c
  var a = abbrevs[c]
  if (aliases[a]) a = aliases[a]
  return a
}

var loaded = false
  , loading = false
  , loadErr = null
  , loadListeners = []

function loadCb (er) {
  loadListeners.forEach(function (cb) {
    process.nextTick(cb.bind(npm, er, npm))
  })
  loadListeners.length = 0
}

npm.load = function (conf, cb_) {
  if (!cb_ && typeof conf === "function") cb_ = conf , conf = {}
  if (!cb_) cb_ = function () {}
  if (!conf) conf = {}
  loadListeners.push(cb_)
  if (loaded || loadErr) return cb(loadErr)
  if (loading) return
  loading = true
  var onload = true

  function cb (er) {
    if (loadErr) return
    loaded = true
    loadCb(loadErr = er)
    if (onload = onload && npm.config.get("onload-script")) {
      require(onload)
      onload = false
    }
  }

  log.waitForConfig()

  load(npm, conf, cb)
}

function load (npm, conf, cb) {
  which(process.argv[0], function (er, node) {
    if (!er && node.toUpperCase() !== process.execPath.toUpperCase()) {
      log.verbose("node symlink", node)
      process.execPath = node
      process.installPrefix = path.resolve(node, "..", "..")
    }

    // look up configs
    //console.error("about to look up configs")

    ini.resolveConfigs(conf, function (er) {
      //console.error("back from config lookup", er && er.stack)
      if (er) return cb(er)

      var umask = parseInt(conf.umask, 8)
      npm.modes = { exec: 0777 & (~umask)
                  , file: 0666 & (~umask)
                  , umask: umask }

      chain([ [ loadPrefix, npm, conf ]
            , [ setUser, ini.configList, ini.defaultConfig ]
            , [ loadUid, npm, conf ]
            ], cb)
    })
  })
}

function loadPrefix (npm, conf, cb) {
  // try to guess at a good node_modules location.
  var p
    , gp
  if (!conf.hasOwnProperty("prefix")) {
    p = process.cwd()
  } else {
    p = npm.config.get("prefix")
  }
  gp = npm.config.get("prefix")

  findPrefix(p, function (er, p) {
    Object.defineProperty(npm, "localPrefix",
      { get : function () { return p }
      , set : function (r) { return p = r }
      , enumerable : true
      })
    // the prefix MUST exist, or else nothing works.
    if (!npm.config.get("global")) {
      mkdir(p, npm.modes.exec, null, null, true, next)
    } else {
      next(er)
    }
  })

  findPrefix(gp, function (er, gp) {
    Object.defineProperty(npm, "globalPrefix",
      { get : function () { return gp }
      , set : function (r) { return gp = r }
      , enumerable : true
      })
    // the prefix MUST exist, or else nothing works.
    mkdir(gp, npm.modes.exec, null, null, true, next)
  })

  var i = 2
    , errState = null
  function next (er) {
    if (errState) return
    if (er) return cb(errState = er)
    if (--i === 0) return cb()
  }
}

function loadUid (npm, conf, cb) {
  // if we're not in unsafe-perm mode, then figure out who
  // to run stuff as.  Do this first, to support `npm update npm -g`
  if (!npm.config.get("unsafe-perm")) {
    getUid(npm.config.get("user"), npm.config.get("group"), cb)
  } else {
    process.nextTick(cb)
  }
}

function setUser (cl, dc, cb) {
  // If global, leave it as-is.
  // If not global, then set the user to the owner of the prefix folder.
  // Just set the default, so it can be overridden.
  if (cl.get("global")) return cb()
  if (process.env.SUDO_UID) {
    dc.user = +(process.env.SUDO_UID)
    return cb()
  }

  var prefix = path.resolve(cl.get("prefix"))
  mkdir(prefix, function (er) {
    if (er) {
      log.error(prefix, "could not create prefix directory")
      return cb(er)
    }
    fs.stat(prefix, function (er, st) {
      dc.user = st && st.uid
      return cb(er)
    })
  })
}

npm.config =
  { get : function (key) { return ini.get(key) }
  , set : function (key, val) { return ini.set(key, val, "cli") }
  , del : function (key, val) { return ini.del(key, val, "cli") }
  }

Object.defineProperty(npm, "prefix",
  { get : function () {
      return npm.config.get("global") ? npm.globalPrefix : npm.localPrefix
    }
  , set : function (r) {
      var k = npm.config.get("global") ? "globalPrefix" : "localPrefix"
      return npm[k] = r
    }
  , enumerable : true
  })

Object.defineProperty(npm, "bin",
  { get : function () {
      if (npm.config.get("global")) return npm.globalBin
      return path.resolve(npm.root, ".bin")
    }
  , enumerable : true
  })

Object.defineProperty(npm, "globalBin",
  { get : function () {
      var b = npm.globalPrefix
      if (process.platform !== "win32") b = path.resolve(b, "bin")
      return b
    }
  })

Object.defineProperty(npm, "dir",
  { get : function () {
      if (npm.config.get("global")) return npm.globalDir
      return path.resolve(npm.prefix, "node_modules")
    }
  , enumerable : true
  })

Object.defineProperty(npm, "globalDir",
  { get : function () {
      return (process.platform !== "win32")
           ? path.resolve(npm.globalPrefix, "lib", "node_modules")
           : path.resolve(npm.globalPrefix, "node_modules")
    }
  , enumerable : true
  })

Object.defineProperty(npm, "root",
  { get : function () { return npm.dir } })

Object.defineProperty(npm, "cache",
  { get : function () { return npm.config.get("cache") }
  , set : function (r) { return npm.config.set("cache", r) }
  , enumerable : true
  })

var tmpFolder
Object.defineProperty(npm, "tmp",
  { get : function () {
      if (!tmpFolder) tmpFolder = "npm-"+Date.now()
      return path.resolve(npm.config.get("tmp"), tmpFolder)
    }
  , enumerable : true
  })

// the better to repl you with
Object.getOwnPropertyNames(npm.commands).forEach(function (n) {
  if (npm.hasOwnProperty(n)) return

  Object.defineProperty(npm, n, { get: function () {
    return function () {
      var args = Array.prototype.slice.call(arguments, 0)
        , cb = defaultCb

      if (args.length === 1 && Array.isArray(args[0])) {
        args = args[0]
      }

      if (typeof args[args.length - 1] === "function") {
        cb = args.pop()
      }

      npm.commands[n](args, cb)
    }
  }, enumerable: false, configurable: true })
})

if (require.main === module) {
  require("../bin/npm-cli.js")
}
})()
<|endoftext|>


<commit_before>;(function() {

function o_O() {};

(function(exports) {
	var methods	= {
		on	: function(event, fct){
			this._events = this._events || {};
			this._events[event] = this._events[event]	|| [];
			this._events[event].push(fct);
		},
		off	: function(event, fct){
			this._events = this._events || {};
			if( event in this._events === false  )	return;
			this._events[event].splice(this._events[event].indexOf(fct), 1);
		},
		once: function(event, fct) {
		  var fn = function() {
		    fct.apply(this, arguments)
		    this.off(event, fn)
		  }
		  this.on(event, fn)
		},
		emit	: function(event /* , args... */){
			this._events = this._events || {};
			if( event in this._events === false  )	return;
			for(var i = 0; i < this._events[event].length; i++){
				this._events[event][i].apply(this, Array.prototype.slice.call(arguments, 1))
			}
		}
	}

	o_O.eventize = function(o) {
		o.on = methods.on
		o.off = methods.off
		o.emit = methods.emit
		o.once = methods.once
	}
})()

Function.prototype.observe = function(observer) {
	observer.on('set', this)
	return this
}

/**
 *  o_O.bind will proxy to any method on a $ object
 *  but sometimes you want something more
 */

o_O.exten$ions = {
  /* set the class
   * usage: bind='class: myClass'
   */
  'class': function(klass) {
    $(this).attr('class', klass)
  },
  /* Two-way binding to a form element
   * usage: bind='value: myObserver'
   */
  value: function(observer) {
		var self = this;

		observer.on('set', function(val) {
			$(self).val(val)
		})

    $(this).change(function(e) {
      observer( $(e.srcElement).val(), e)
    })
  }
}

function trim(s) {
	return s.replace(/^s+|s+$/, "")
}

o_O.bind = function(el, context) {
  var $el = $(el)
	context.el = $el[0]
	context.$ = $el

	var els = $el.find("[bind]").add($el.filter("[bind]"))

	els.each(function(k, v) {
   	var $$ = $(this)
		var rules = trim($$.attr("bind")).split(";")
		for(var i=0; i< rules.length; i++) {
      var rule = rules[i]
			if(!rule) continue // for trailing ;

			var  bits = trim(rule).split(":"),
	    		attr = trim(bits.shift()),
					param = trim(bits.join(":"))

			var deps = o_O.deps(param, context)

			function run() {
				var x = o_O.expression(param).call(context)
				var fn = $$[attr] || o_O.exten$ions[attr]
        if(!fn) throw new Error("Could not find attr '" + attr + "' in $ or o_O.exten$ions")
				fn.call($$, x)
			}
			run()

			deps.forEach(function(dep) {
				dep.on('set', run)
			})
	  }

		$$.attr("bind",null)
	})

	return $el
}

// probably don't need/want this cache
o_O.expression = function(expr) {
	return new Function('with(this) { return (' + expr + ')}')
}

// converts a DOM event from an element with a value into it's value
// useful for setting properties based on form events
o_O.val = function(fn) {
  return function(e) { fn( $(e.srcElement).val(), e) }
}

/**
 *  Our workhorse
 *  property returns an observable
 *  which can be set like prop(val) and got like prop()
 *  it trigger's set events
 *  it also automatically figures out it's deps on other o_O.properties
 *  a function can also be passed in for computed properties
 */
o_O.property = function(value) {
	if(typeof value == 'function') return o_O.computed(value)

	function prop(v) {
		if(arguments.length) {
			prop.val = v
	    prop.emit('set', v, prop)
		} else {
		  o_O.deps.emit('get', prop)
			return prop.val
		}
  }

	o_O.eventize(prop)
  prop.val = value
	prop.deps = []
  return prop
}

o_O.computed = function(getset) {
	function prop(value) {
		if(arguments.length) {
			prop.val = getset(value)
		} else {
			prop.val = getset()
			return prop.val
		}
	}

	o_O.eventize(prop)
	prop.deps = o_O.deps(getset)
	prop.val = o_O.deps.lastResult
	return prop
}

o_O.deps = function(expr, context) {
	if(typeof expr == 'string') expr = o_O.expression(expr)

	var deps = []
	var collector = function(dep) {
		if(deps.indexOf(dep) < 0 && expr != dep) deps.push(dep)
	}
	// capture deps
	o_O.deps.on('get', collector)
	o_O.deps.lastResult = expr.call(context)
	o_O.deps.off('get', collector)
	return deps
}

o_O.eventize(o_O.deps)

typeof module != 'undefined' ? module.exports = o_O : window.o_O = o_O;
})();<commit_msg>value extension now reads<commit_after>;(function() {

function o_O() {};

(function(exports) {
	var methods	= {
		on	: function(event, fct){
			this._events = this._events || {};
			this._events[event] = this._events[event]	|| [];
			this._events[event].push(fct);
		},
		off	: function(event, fct){
			this._events = this._events || {};
			if( event in this._events === false  )	return;
			this._events[event].splice(this._events[event].indexOf(fct), 1);
		},
		once: function(event, fct) {
		  var fn = function() {
		    fct.apply(this, arguments)
		    this.off(event, fn)
		  }
		  this.on(event, fn)
		},
		emit	: function(event /* , args... */){
			this._events = this._events || {};
			if( event in this._events === false  )	return;
			for(var i = 0; i < this._events[event].length; i++){
				this._events[event][i].apply(this, Array.prototype.slice.call(arguments, 1))
			}
		}
	}

	o_O.eventize = function(o) {
		o.on = methods.on
		o.off = methods.off
		o.emit = methods.emit
		o.once = methods.once
	}
})()

// Function.prototype.observe = function(observer) {
// 	observer.on('set', this)
// 	return this
// }

/**
 *  o_O.bind will proxy to any method on a $ object
 *  but sometimes you want something more
 */

o_O.exten$ions = {
  /* set the class
   * usage: bind='class: myClass'
   */
  'class': function(klass) {
    $(this).attr('class', klass)
  },
  /* Two-way binding to a form element
   * usage: bind='value: myProperty'
   */
  value: function(property) {
		var self = this;

		property.on('set', function(val) {
			$(self).val(val)
		})

    $(this).change(function(e) {
      property( $(e.srcElement).val(), e)
    })

		property.rewrite()
  }
}

function trim(s) {
	return s.replace(/^s+|s+$/, "")
}

o_O.bind = function(el, context) {
  var $el = $(el)
	context.el = $el[0]
	context.$ = $el

	var els = $el.find("[bind]").add($el.filter("[bind]"))

	els.each(function(k, v) {
   	var $$ = $(this)
		var rules = trim($$.attr("bind")).split(";")
		for(var i=0; i< rules.length; i++) {
      var rule = rules[i]
			if(!rule) continue // for trailing ;

			var  bits = trim(rule).split(":"),
	    		attr = trim(bits.shift()),
					param = trim(bits.join(":"))

			var deps = o_O.deps(param, context)

			function run() {
				var x = o_O.expression(param).call(context)
				var fn = $$[attr] || o_O.exten$ions[attr]
        if(!fn) throw new Error("Could not find attr '" + attr + "' in $ or o_O.exten$ions")
				fn.call($$, x)
			}
			run()

			deps.forEach(function(dep) {
				dep.on('set', run)
			})
	  }

		$$.attr("bind",null)
	})

	return $el
}

// probably don't need/want this cache
o_O.expression = function(expr) {
	return new Function('with(this) { return (' + expr + ')}')
}

// converts a DOM event from an element with a value into it's value
// useful for setting properties based on form events
o_O.val = function(fn) {
  return function(e) { fn( $(e.srcElement).val(), e) }
}

/**
 *  Our workhorse
 *  property returns an observable
 *  which can be set like prop(val) and got like prop()
 *  it trigger's set events
 *  it also automatically figures out it's deps on other o_O.properties
 *  a function can also be passed in for computed properties
 */
o_O.property = function(value) {
	if(typeof value == 'function') return o_O.computed(value)

	function prop(v) {
		if(arguments.length) {
			prop.val = v
	    prop.emit('set', v, prop)
		} else {
		  o_O.deps.emit('get', prop)
			return prop.val
		}
  }

	o_O.eventize(prop)
  prop.val = value
	prop.deps = []
	prop.rewrite = function() { prop(prop()) }
  return prop
}

o_O.computed = function(getset) {
	function prop(value) {
		if(arguments.length) {
			prop.val = getset(value)
		} else {
			prop.val = getset()
			return prop.val
		}
	}

	o_O.eventize(prop)
	prop.deps = o_O.deps(getset)
	prop.val = o_O.deps.lastResult
	prop.rewrite = function() { prop(prop())}
	return prop
}

o_O.deps = function(expr, context) {
	if(typeof expr == 'string') expr = o_O.expression(expr)

	var deps = []
	var collector = function(dep) {
		if(deps.indexOf(dep) < 0 && expr != dep) deps.push(dep)
	}
	// capture deps
	o_O.deps.on('get', collector)
	o_O.deps.lastResult = expr.call(context)
	o_O.deps.off('get', collector)
	return deps
}

o_O.eventize(o_O.deps)

typeof module != 'undefined' ? module.exports = o_O : window.o_O = o_O;

})();<|endoftext|>


<commit_before>// Copyright (c) 2012 Kuba Niegowski
//
// 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.

'use strict';

var util = require('util'),
    Parser = require('./parser');

var PNG = exports.PNG = function(options) {
    Parser.call(this, options);

    this.width = options.width || 0;
    this.height = options.height || 0;

    this.data = this.width > 0 && this.height > 0
            ? new Buffer(4 * this.width * this.height) : null;

    this.on('metadata', this._metadata.bind(this));

    this.readable = this.writable = true;
    this._buffers = [];
    this._buffLen = 0;

    this.on('parsed', function(data) {
        this.data = data;
    }.bind(this));
};
util.inherits(PNG, Parser);

PNG.prototype.pack = function() {
    this._pack(this.width, this.height, this.data);
};

PNG.prototype.parse = function(data, callback) {

    if (callback) {
        var onParsed = null, onError = null;

        this.once('parsed', onParsed = function(data) {
            this.removeListener('error', onError);

            this.data = data;
            callback(null, this);

        }.bind(this));

        this.once('error', onError = function(err) {
            this.removeListener('parsed', onParsed);

            callback(err, null);
        }.bind(this));
    }

    this._parse(data);
};

PNG.prototype.write = function(data) {
    this._buffers.push(data);
    this._buffLen += data.length;
};

PNG.prototype.end = function(data) {
    if (data) this.write(data);
    this._parse(Buffer.concat(this._buffers, this._buffLen));
    this._buffers = [];
    this._buffLen = 0;
};

PNG.prototype._metadata = function(width, height) {
    this.width = width;
    this.height = height;
    this.data = null;
};
<commit_msg>bitblt<commit_after>// Copyright (c) 2012 Kuba Niegowski
//
// 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.

'use strict';

var util = require('util'),
    Parser = require('./parser');

var PNG = exports.PNG = function(options) {
    Parser.call(this, options);

    this.width = options.width || 0;
    this.height = options.height || 0;

    this.data = this.width > 0 && this.height > 0
            ? new Buffer(4 * this.width * this.height) : null;

    this.on('metadata', this._metadata.bind(this));

    this.readable = this.writable = true;
    this._buffers = [];
    this._buffLen = 0;

    this.on('parsed', function(data) {
        this.data = data;
    }.bind(this));
};
util.inherits(PNG, Parser);

PNG.prototype.pack = function() {
    this._pack(this.width, this.height, this.data);
};

PNG.prototype.parse = function(data, callback) {

    if (callback) {
        var onParsed = null, onError = null;

        this.once('parsed', onParsed = function(data) {
            this.removeListener('error', onError);

            this.data = data;
            callback(null, this);

        }.bind(this));

        this.once('error', onError = function(err) {
            this.removeListener('parsed', onParsed);

            callback(err, null);
        }.bind(this));
    }

    this._parse(data);
};

PNG.prototype.write = function(data) {
    this._buffers.push(data);
    this._buffLen += data.length;
};

PNG.prototype.end = function(data) {
    if (data) this.write(data);
    this._parse(Buffer.concat(this._buffers, this._buffLen));
    this._buffers = [];
    this._buffLen = 0;
};

PNG.prototype._metadata = function(width, height) {
    this.width = width;
    this.height = height;
    this.data = null;
};

PNG.prototype.bitblt = function(dst, sx, sy, w, h, dx, dy) {

    var src = this;

    if (sx > src.width || sy > src.height
            || sx + w > src.width || sy + h > src.height)
        throw new Error('bitblt reading outside image');
    if (dy > dst.width || dy > dst.height
            || dx + w > dst.width || dy + h > dst.height)
        throw new Error('bitblt writing outside image');

    for (var y = 0; y < h; y++) {
        src.data.copy(dst.data,
            ((dy + y) * dst.width + dx) << 2,
            ((sy + y) * src.width + sx) << 2,
            ((sy + y) * src.width + sx + w) << 2
        );
    }

    return this;
};
<|endoftext|>


<commit_before>/*
 * Requests
 *
 */

// Dependencies
var url = require('url');

// Create module object
var request = {};

request.process = function(req,res){
	req = typeof(req) == 'object' ? req : false;
	res = typeof(res) == 'object' ? res : false;
	if(!req || !res){
		app.lib.res.send(req,res,500);
		return false;
	}
	var tmp = false;
	// Get request data from req object
	var data = request.getData(req);

	// Check for CORS/preflight requests
	tmp = request.checkCors(app.config.cors,data);
	if(typeof(tmp) == 'number'){
		app.lib.res.send(req,res,tmp);
		return true;
	}

	// Check for valid url
	tmp = request.checkUrl(data);
	if(typeof(tmp) == 'number'){
		app.lib.res.send(req,res,tmp);
		return false;
	}

	// Check for valid http headers
	tmp = request.checkHeaders(data);
	if(typeof(tmp) == 'number'){
		app.lib.res.send(req,res,tmp);
		return false;
	}

	// Check for valid http method
	tmp = request.checkMethod(data);
	if(typeof(tmp) == 'number'){
		app.lib.res.send(req,res,tmp);
		return false;
	}

	// Route to the correct controller based on method
	try{
		app.lib.controllers.set[data.method](data,function(statusCode,payload){
			// Trigger the response
			app.lib.res.send(req,res,statusCode,payload);
		});
	}catch(e){
		// Send a 500 error because the controller threw an exception
		app.lib.res.send(req,res,500);
	}
	return true;

};

// Required headers
request.requiredHeaders = [];

// Add a required header
request.setRequiredHeader = function(key, pattern){
	// Add key and pattern to request.requiredHeaders array
	if(typeof(key) == 'string' && key.length > 0 && typeof(pattern) == 'string' && pattern.length > 0){
		try{
			var tmp = new RegExp(pattern);
			var tmpObj = {
				'key' : key,
				'value' : pattern
			};
			request.requiredHeaders.push(tmpObj);
			return true;
		}catch(e){
			return false;
		}
	} else {
		return false;
	}

};

// Check that the headers meet the requirements
request.checkHeaders = function(data){
	data = typeof(data) == 'object' ? data : {};
	if(typeof(data.headers) == 'object' && data.headers !== null){
		if(request.requiredHeaders.length > 0){
			var headerCheckPassed = true;
			request.requiredHeaders.forEach(function(tmpObj){
				var requiredKey = tmpObj.key;
				var requiredValue = tmpObj.value;
				// Check that the header key exists
				if(typeof(data.headers[requiredKey]) == 'string'){
					// Check that the header value matches the regex requirements
					var tmpRegex = new RegExp(requiredValue);
					if(!(tmpRegex.test(data.headers[requiredKey]))) {
						headerCheckPassed = false;
					}
				} else {
					headerCheckPassed = false;
				}
			});
			if(headerCheckPassed){
				return;
			} else {
				return 406;
			}
		} else {
			return;
		}
	} else {
		return 406;
	}
};

// Url requirements
request.requiredUrls = [];

// Set url requirements
request.setRequiredUrl = function(pattern){
	// Add pattern to request.requiredUrls array
	if(typeof(pattern) == 'string' && pattern.length > 0){
		try{
			var tmp = new RegExp(pattern);
			request.requiredUrls.push(pattern);
			return true;
		}catch(e){
			return false;
		}
	} else {
		return false;
	}
};

// Disallowed urls
request.disallowedUrls = [];

// Set disallowed urls
request.setDisallowedUrl = function(pattern){
	// Add pattern to request.disallowedUrls array
	if(typeof(pattern) == 'string' && pattern.length > 0){
		try{
			var tmp = new RegExp(pattern);
			request.disallowedUrls.push(pattern);
			return true;
		}catch(e){
			return false;
		}
	} else {
		return false;
	}
};

// Check that the url is valid
request.checkUrl = function(data){
	data = typeof(data) == 'object' ? data : {};

	if(typeof(data.path) == 'string' || (typeof(data.path) == 'object' && data.path === null)){

		if(data.path === null){
			data.path = '';
		}

		// Check it against required patterns
		var requiredOutcome = false;
		if(request.requiredUrls.length > 0){
			request.requiredUrls.forEach(function(pattern){
				var tmpRegex = new RegExp(pattern);
				if(tmpRegex.test(data.path)){
					requiredOutcome = true;
				}
			});
		} else {
			// If there are no required patterns, skip this check
			requiredOutcome = true;
		}

		// Check it against disallowed patterns
		if(requiredOutcome){

			var disallowedOutcome = true;
			if(request.disallowedUrls.length > 0){
				request.disallowedUrls.forEach(function(pattern){
					tmpRegex = new RegExp(pattern);
					if(tmpRegex.test(data.path)){
						disallowedOutcome = false;
					}
				});
			}

			if(disallowedOutcome){
				return;
			} else {
				return 404;
			}
		} else {
			return 404;
		}
	} else {
		return 404;
	}
};

// Check for an OPTIONS request (if CORS is enabled)
request.checkCors = function(cors,data){
	cors = typeof(cors) == 'boolean' && cors ? true : false;
	data = typeof(data) == 'object' ? data : {};
	if(cors){
		if(typeof(data.method) == 'string' && data.method == 'options'){
			return 200;
		} else {
			return;
		}
	} else {
		return;
	}
};

// Check that the HTTP method is valid
request.checkMethod = function(data){
	data = typeof(data) == 'object' ? data : {};
	if(typeof(data.method) == 'string' && typeof(app.lib.controllers.set[data.method]) == 'function'){
		return;
	} else {
		return 405;
	}

};

// Extract the pertinent data from the req object
request.getData = function(req){
	req = typeof(req) == 'object' ? req : false;
	var data = {
		params : {},
		path : null,
		pathArray : [],
		headers : {},
		payload : {},
		method : null
	};
	if(req){
		// Get url related data
		if(typeof(req.url) == 'string'){

			var fullUrl = req.url;
			var parsedUrl = url.parse(fullUrl, true);
			// Get params
			data.params = typeof(parsedUrl.query) == 'object' && parsedUrl.query !== null ? parsedUrl.query : {};

			// Get path
			data.path = typeof(parsedUrl.pathname) == 'string' && parsedUrl.pathname.trim().length > null ? parsedUrl.pathname.replace(/^\/+|\/+$/g, '') : null;
			data.path = typeof(data.path) == 'string' ? data.path.trim() : null;
			data.path = typeof(data.path) == 'string' && data.path.length > 0 ? data.path : null;

			// Get path array
			data.pathArray = typeof(data.path) == 'string' ? data.path.split('/') : [];

		}

		// Get method
		data.method = typeof(req.method) == 'string' && req.method.trim().length > 0 ? req.method.toLowerCase().trim() : null;

		// Get headers
		data.headers = (typeof(req.headers) == 'object' && req.headers !== null) ? req.headers : {};

		// Get payload
		if(typeof(req.body) == 'string'){
			data.payload = app.lib.util.getParsedJson(req.body);
		}
	}
	return data;

};

// Export the module
module.exports = request;<commit_msg>Added console logging for URL and header errors<commit_after>/*
 * Requests
 *
 */

// Dependencies
var url = require('url');

// Create module object
var request = {};

request.process = function(req, res) {
  req = typeof(req) == 'object' ? req : false;
  res = typeof(res) == 'object' ? res : false;
  if (!req || !res) {
    app.lib.res.send(req, res, 500);
    return false;
  }
  var tmp = false;
  // Get request data from req object
  var data = request.getData(req);

  // Check for CORS/preflight requests
  tmp = request.checkCors(app.config.cors, data);
  if (typeof(tmp) == 'number') {
    app.lib.res.send(req, res, tmp);
    return true;
  }

  // Check for valid url
  tmp = request.checkUrl(data);
  if (typeof(tmp) == 'number') {
    console.log('URL error:', data);
    app.lib.res.send(req, res, tmp);
    return false;
  }

  // Check for valid http headers
  tmp = request.checkHeaders(data);
  if (typeof(tmp) == 'number') {
    console.log('Check Header error:', data);
    app.lib.res.send(req, res, tmp);
    return false;
  }

  // Check for valid http method
  tmp = request.checkMethod(data);
  if (typeof(tmp) == 'number') {
    app.lib.res.send(req, res, tmp);
    return false;
  }

  // Route to the correct controller based on method
  try {
    app.lib.controllers.set[data.method](data, function(statusCode, payload) {
      // Trigger the response
      app.lib.res.send(req, res, statusCode, payload);
    });
  } catch (e) {
    // Send a 500 error because the controller threw an exception
    app.lib.res.send(req, res, 500);
  }
  return true;

};

// Required headers
request.requiredHeaders = [];

// Add a required header
request.setRequiredHeader = function(key, pattern) {
  // Add key and pattern to request.requiredHeaders array
  if (typeof(key) == 'string' && key.length > 0 && typeof(pattern) == 'string' && pattern.length > 0) {
    try {
      var tmp = new RegExp(pattern);
      var tmpObj = {
        'key': key,
        'value': pattern
      };
      request.requiredHeaders.push(tmpObj);
      return true;
    } catch (e) {
      return false;
    }
  } else {
    return false;
  }

};

// Check that the headers meet the requirements
request.checkHeaders = function(data) {
  data = typeof(data) == 'object' ? data : {};
  if (typeof(data.headers) == 'object' && data.headers !== null) {
    if (request.requiredHeaders.length > 0) {
      var headerCheckPassed = true;
      request.requiredHeaders.forEach(function(tmpObj) {
        var requiredKey = tmpObj.key;
        var requiredValue = tmpObj.value;
        // Check that the header key exists
        if (typeof(data.headers[requiredKey]) == 'string') {
          // Check that the header value matches the regex requirements
          var tmpRegex = new RegExp(requiredValue);
          if (!(tmpRegex.test(data.headers[requiredKey]))) {
            headerCheckPassed = false;
          }
        } else {
          headerCheckPassed = false;
        }
      });
      if (headerCheckPassed) {
        return;
      } else {
        return 406;
      }
    } else {
      return;
    }
  } else {
    return 406;
  }
};

// Url requirements
request.requiredUrls = [];

// Set url requirements
request.setRequiredUrl = function(pattern) {
  // Add pattern to request.requiredUrls array
  if (typeof(pattern) == 'string' && pattern.length > 0) {
    try {
      var tmp = new RegExp(pattern);
      request.requiredUrls.push(pattern);
      return true;
    } catch (e) {
      return false;
    }
  } else {
    return false;
  }
};

// Disallowed urls
request.disallowedUrls = [];

// Set disallowed urls
request.setDisallowedUrl = function(pattern) {
  // Add pattern to request.disallowedUrls array
  if (typeof(pattern) == 'string' && pattern.length > 0) {
    try {
      var tmp = new RegExp(pattern);
      request.disallowedUrls.push(pattern);
      return true;
    } catch (e) {
      return false;
    }
  } else {
    return false;
  }
};

// Check that the url is valid
request.checkUrl = function(data) {
  data = typeof(data) == 'object' ? data : {};

  if (typeof(data.path) == 'string' || (typeof(data.path) == 'object' && data.path === null)) {

    if (data.path === null) {
      data.path = '';
    }

    // Check it against required patterns
    var requiredOutcome = false;
    if (request.requiredUrls.length > 0) {
      request.requiredUrls.forEach(function(pattern) {
        var tmpRegex = new RegExp(pattern);
        if (tmpRegex.test(data.path)) {
          requiredOutcome = true;
        }
      });
    } else {
      // If there are no required patterns, skip this check
      requiredOutcome = true;
    }

    // Check it against disallowed patterns
    if (requiredOutcome) {

      var disallowedOutcome = true;
      if (request.disallowedUrls.length > 0) {
        request.disallowedUrls.forEach(function(pattern) {
          tmpRegex = new RegExp(pattern);
          if (tmpRegex.test(data.path)) {
            disallowedOutcome = false;
          }
        });
      }

      if (disallowedOutcome) {
        return;
      } else {
        return 404;
      }
    } else {
      return 404;
    }
  } else {
    return 404;
  }
};

// Check for an OPTIONS request (if CORS is enabled)
request.checkCors = function(cors, data) {
  cors = typeof(cors) == 'boolean' && cors ? true : false;
  data = typeof(data) == 'object' ? data : {};
  if (cors) {
    if (typeof(data.method) == 'string' && data.method == 'options') {
      return 200;
    } else {
      return;
    }
  } else {
    return;
  }
};

// Check that the HTTP method is valid
request.checkMethod = function(data) {
  data = typeof(data) == 'object' ? data : {};
  if (typeof(data.method) == 'string' && typeof(app.lib.controllers.set[data.method]) == 'function') {
    return;
  } else {
    return 405;
  }

};

// Extract the pertinent data from the req object
request.getData = function(req) {
  req = typeof(req) == 'object' ? req : false;
  var data = {
    params: {},
    path: null,
    pathArray: [],
    headers: {},
    payload: {},
    method: null
  };
  if (req) {
    // Get url related data
    if (typeof(req.url) == 'string') {

      var fullUrl = req.url;
      var parsedUrl = url.parse(fullUrl, true);
      // Get params
      data.params = typeof(parsedUrl.query) == 'object' && parsedUrl.query !== null ? parsedUrl.query : {};

      // Get path
      data.path = typeof(parsedUrl.pathname) == 'string' && parsedUrl.pathname.trim().length > null ? parsedUrl.pathname.replace(/^\/+|\/+$/g, '') : null;
      data.path = typeof(data.path) == 'string' ? data.path.trim() : null;
      data.path = typeof(data.path) == 'string' && data.path.length > 0 ? data.path : null;

      // Get path array
      data.pathArray = typeof(data.path) == 'string' ? data.path.split('/') : [];

    }

    // Get method
    data.method = typeof(req.method) == 'string' && req.method.trim().length > 0 ? req.method.toLowerCase().trim() : null;

    // Get headers
    data.headers = (typeof(req.headers) == 'object' && req.headers !== null) ? req.headers : {};

    // Get payload
    if (typeof(req.body) == 'string') {
      data.payload = app.lib.util.getParsedJson(req.body);
    }
  }
  return data;

};

// Export the module
module.exports = request;
<|endoftext|>


<commit_before>const sourceWords = [
  // Variations on fur
  'fur',
  'furry',
  'furre',
  'furries',
  'fursona',
  '\'sona',
  'alt',
  'character',

  // Conventions
  'con',
  'convention',
  'anthrocon',
  'AC',
  'Further Confusion',
  'FC',
  'Midwest Fur Fest',
  'MFF',

  // Fursuiting
  'fursuit',
  'suiter',
  'headless',
  'ruining the magic',
  'poodling',

  // Body parts
  'booper',
  'snoot',
  'scruff',
  'paws',
  'pawbs',
  'beans',
  'maws',
  'tail',

  // Art
  'commission',
  'stream',
  'sketch',
  'sketch stream',
  'icon',

  // Chat
  'furnet',
  'anthrochat',
  'FurryMUCK',
  'SPR',
  'taps',
  'tapestries',
  'furcadia',

  // Websites
  'furnation',
  'Yerf!',
  'VCL',
  'FA',
  'FurAffinity',
  'SoFurry',
  'Weasyl',
  'InkBunny',
  'Wikifur',

  // Species
  'sergal',
  'fox',
  'wolf',
  'husky',
  'cat',
  'ott',
  'otter',
  'sparkledog',

  // Noises
  'yap',
  'yip',
  'bark',
  'mew',
  'meow',
  'growl',
  'murr',
  'reh',
  'squeak',
  'awoo',
  'awooooo',
  'awoooooooooo',

  // Verbs
  'wiggle',
  'scritch',
  'pet',
  'boop',
  'whiskerflick',
  'tailswish',
  'swish',
  'wag',
  'nuzzle',
  'fluff',
  'glomp',
  'clop',
  'snuggle',
  'snug',
  'noodle',

  // Etc.
  'graymuzzle',
  'owo',
  'uwu',
  'popufur',
  'feesh',
];

function toUpperFirst(s) {
  return s.charAt(0).toUpperCase() + s.slice(1);
}

function gen() {
  let words = 0;
  let finished = false;
  let result = '';

  const wordCount = parseInt($('#wordcount').val()) > 1
    ? parseInt($('#wordcount').val())
    : 500;
  const chapterCount = parseInt($('#chaptercount').val()) > 1
    ? parseInt($('#chaptercount').val())
    : 1;
  const paragraphsPerChapter = Math.ceil(wordCount / chapterCount / 100);

  _(chapterCount).times(chapter => {
    if (finished) {
      return;
    }

    if (chapterCount > 1) {
      result += `<h2>Chapter ${chapter + 1} — ${toUpperFirst(_(3).times(f => _.sample(sourceWords)).join (' '))}</h2>`
    }
    _(paragraphsPerChapter).times(paragraph => {
      if (finished) {
        return;
      }

      result += '
';
      _(Math.floor(Math.random() * 7) + 1).times(sentence => {
        if (finished) {
          return;
        }

        _(Math.floor((Math.random() * 10) / 3) + 1).times(phrase => {

          _(Math.floor(Math.random() * 10) + 1).times(word => {
            let sourceWord = _.sample(sourceWords);
            if (phrase === 0 && word === 0) {
              sourceWord = toUpperFirst(sourceWord);
            }

            result += sourceWord + ' ';
            words++;
          });

          result = result.slice(0, result.length - 1) + ', ';
        });

        result = result.slice(0, result.length - 2) + '.  ';
        if (words > wordCount) {
          finished = true;
        }
      });

      result += '
';
    });
  });

  $('#yipsum').html(result);
}

gen();
<commit_msg>More words<commit_after>const sourceWords = [
  // Variations on fur
  'fur',
  'furry',
  'furre',
  'furries',
  'fursona',
  '\'sona',
  'alt',
  'character',

  // Conventions
  'con',
  'convention',
  'anthrocon',
  'AC',
  'Further Confusion',
  'FC',
  'Midwest Fur Fest',
  'MFF',

  // Fursuiting
  'fursuit',
  'suiter',
  'headless',
  'ruining the magic',
  'poodling',

  // Body parts
  'booper',
  'snoot',
  'scruff',
  'paws',
  'pawbs',
  'beans',
  'maws',
  'tail',

  // Art
  'commission',
  'stream',
  'sketch',
  'sketch stream',
  'icon',

  // Chat
  'furnet',
  'anthrochat',
  'FurryMUCK',
  'SPR',
  'taps',
  'tapestries',
  'furcadia',

  // Websites
  'furnation',
  'Yerf!',
  'VCL',
  'FA',
  'FurAffinity',
  'SoFurry',
  'Weasyl',
  'InkBunny',
  'Wikifur',

  // Species
  'sergal',
  'fox',
  'wolf',
  'husky',
  'cat',
  'ott',
  'otter',
  'sparkledog',
  'birb',
  'fops',
  'bunny',
  'bunneh',

  // Noises
  'yap',
  'yip',
  'bark',
  'mew',
  'meow',
  'growl',
  'murr',
  'reh',
  'squeak',
  'awoo',
  'awooooo',
  'awoooooooooo',

  // Verbs
  'wiggle',
  'scritch',
  'pet',
  'boop',
  'whiskerflick',
  'tailswish',
  'swish',
  'wag',
  'nuzzle',
  'fluff',
  'glomp',
  'clop',
  'snuggle',
  'snug',
  'noodle',
  'floof',
  'fuzzle',

  // Etc.
  'graymuzzle',
  'owo',
  'uwu',
  'popufur',
  'feesh',
  'after dark',
];

function toUpperFirst(s) {
  return s.charAt(0).toUpperCase() + s.slice(1);
}

function gen() {
  let words = 0;
  let finished = false;
  let result = '';

  const wordCount = parseInt($('#wordcount').val()) > 1
    ? parseInt($('#wordcount').val())
    : 500;
  const chapterCount = parseInt($('#chaptercount').val()) > 1
    ? parseInt($('#chaptercount').val())
    : 1;
  const paragraphsPerChapter = Math.ceil(wordCount / chapterCount / 100);

  _(chapterCount).times(chapter => {
    if (finished) {
      return;
    }

    if (chapterCount > 1) {
      result += `<h2>Chapter ${chapter + 1} — ${toUpperFirst(_(3).times(f => _.sample(sourceWords)).join (' '))}</h2>`
    }
    _(paragraphsPerChapter).times(paragraph => {
      if (finished) {
        return;
      }

      result += '
';
      _(Math.floor(Math.random() * 7) + 1).times(sentence => {
        if (finished) {
          return;
        }

        _(Math.floor((Math.random() * 10) / 3) + 1).times(phrase => {

          _(Math.floor(Math.random() * 10) + 1).times(word => {
            let sourceWord = _.sample(sourceWords);
            if (phrase === 0 && word === 0) {
              sourceWord = toUpperFirst(sourceWord);
            }

            result += sourceWord + ' ';
            words++;
          });

          result = result.slice(0, result.length - 1) + ', ';
        });

        result = result.slice(0, result.length - 2) + '.  ';
        if (words > wordCount) {
          finished = true;
        }
      });

      result += '
';
    });
  });

  $('#yipsum').html(result);
}

gen();
<|endoftext|>


<commit_before>/**
 * The main file of node-rfr.
 *
 * @author Su Su <s@warmsea.net>
 */

/**
 * Trim a root and add tailing slash if not exists.
 * @param {String} root A root.
 * @returns {String} The coerced root.
 * @private
 */
function coerceRoot(root) {
  var coerced = root.toString().trim();
  var len = coerced.length;
  if (len > 0 && coerced[len - 1] !== '/') {
    coerced = coerced + '/';
  }
  return coerced;
}

/**
 * Return a module id which can be used by the builtin `require()`.
 * @param {String} idFromRoot A RFR module id.
 * @param {String} root The root.
 * @returns {String} A standard module id.
 * @private
 */
function normalizeId(idFromRoot, root) {
  var id = idFromRoot.toString().trim();
  if (root && id.length > 0 && id[0] === '/') {
    id = id.substring(1);
  }
  id = root + id;
  return id;
}

/**
 * Create a new version of rfr with a function.
 * @param {Function} callable The rfr require function.
 * @param {String} root The root for rfr require.
 * @private
 */
var createRfr = function(callable, root) {
  rfr = callable.bind(callable);

  rfr.setRoot = function(root) {
    callable.root = coerceRoot(root);
  };

  rfr.setRoot(root);
  return rfr;
};

/**
 * Create a new version of rfr.
 * @param {{root:String}} config config of this version.
 * @returns {rfr} a new rfr version.
 * @private
 */
function createVersion(config) {
  if (!(config || (typeof config.root !== 'string'))) {
    throw new Error('"config.root" is required and must be a string');
  }

  return createRfr(function(idFromRoot) {
    if (typeof idFromRoot !== 'string') {
      throw new Error('A string is required for the argument of ' +
          'a user created RFR version.');
    }
    return require(normalizeId(idFromRoot, this.root));
  }, config.root);
}

/**
 * Do the RFR require action, or create a new version of RFR.
 * If a string is passed as the argument, this function will do the RFR require
 * action. Else, this function will create a new version of RFR with the
 * argument as config.
 * @function
 * @param {String|Object} idFromRoot Module id or RFR config.
 * @returns {Module|RFR} A module or a RFR version.
 */
var rfr = createRfr(function(idFromRoot) {
  if (typeof idFromRoot === 'string') {
    return require(normalizeId(idFromRoot, this.root));
  } else {
    return createVersion(idFromRoot);
  }
}, process.env.RFR_ROOT || process.env.PWD || process.cwd() || '/');

module.exports = rfr;
<commit_msg>Add #root and #resolve().<commit_after>/**
 * The main file of node-rfr.
 *
 * @author Su Su <s@warmsea.net>
 */

/**
 * Trim a root and add tailing slash if not exists.
 * @param {String} root A root.
 * @returns {String} The coerced root.
 * @private
 */
function coerceRoot(root) {
  var coerced = root.substring().trim();
  var len = coerced.length;
  if (len > 0 && coerced[len - 1] !== '/') {
    coerced = coerced + '/';
  }
  return coerced;
}

/**
 * Return a module id which can be used by the builtin `require()`.
 * @param {String} idFromRoot A RFR module id.
 * @param {String} root The root.
 * @returns {String} A standard module id.
 * @private
 */
function normalizeId(idFromRoot, root) {
  var id = idFromRoot.substring().trim();
  if (root && id.length > 0 && id[0] === '/') {
    id = id.substring(1);
  }
  id = root + id;
  return id;
}

/**
 * Create a new version of rfr with a function.
 * @param {Function} callable The rfr require function.
 * @param {String} root The root for rfr require.
 * @private
 */
var createRfr = function(callable, root) {
  rfr = callable.bind(callable);

  /**
   * The root of a rfr instance.
   * @type {String}
   */
  Object.defineProperty(rfr, 'root', {
    get: function() {
      return callable.root;
    },
    set: function(root) {
      callable.root = coerceRoot(root);
    }
  });

  /**
   * Set the root.
   * @param {String} root The new root.
   */
  rfr.setRoot = function(root) {
    this.root = root;
  };

  /**
   * Get the filename that will be loaded when this rfr is called.
   * @returns {String} module filename.
   */
  rfr.resolve = function(idFromRoot) {
    return require.resolve(normalizeId(idFromRoot, this.root));
  };

  rfr.root = root;
  return rfr;
};

/**
 * Create a new version of rfr.
 * @param {{root:String}} config config of this version.
 * @returns {rfr} a new rfr version.
 * @private
 */
function createVersion(config) {
  if (!(config || (typeof config.root !== 'string'))) {
    throw new Error('"config.root" is required and must be a string');
  }

  return createRfr(function(idFromRoot) {
    if (typeof idFromRoot !== 'string') {
      throw new Error('A string is required for the argument of ' +
          'a user created RFR version.');
    }
    return require(normalizeId(idFromRoot, this.root));
  }, config.root);
}

/**
 * Do the RFR require action, or create a new version of RFR.
 * If a string is passed as the argument, this function will do the RFR require
 * action. Else, this function will create a new version of RFR with the
 * argument as config.
 * @function
 * @param {String|Object} idFromRoot Module id or RFR config.
 * @returns {Module|RFR} A module or a RFR version.
 */
var rfr = createRfr(function(idFromRoot) {
  if (typeof idFromRoot === 'string') {
    return require(normalizeId(idFromRoot, this.root));
  } else {
    return createVersion(idFromRoot);
  }
}, process.env.RFR_ROOT || process.env.PWD || process.cwd() || '/');

module.exports = rfr;
<|endoftext|>


<commit_before>'use strict';

var http = require('http');
var querystring = require('querystring');
var BufferList = require('bl');

function Rpc(agent, options) {
  this.agent = agent;
  this.host = options.host;
  this.port = options.port;
}

Rpc.prototype.void = function (callback) {
  this._call('void', undefined, {}, callback);
};

Rpc.prototype.echo = function (params, callback) {
  this._call('echo', params, {}, callback);
};

Rpc.prototype.report = function (callback) {
  this._call('report', undefined, {}, callback);
};

// Rpc.prototype.playScript = function (options, callback) {};
// Rpc.prototype.tuneReplication = function (options, callback) {};

Rpc.prototype.status = function (options, callback) {
  var cb, opt = {}, params = {};

  if (typeof options === 'function') {
    opt = {};
    cb = options;
  } else {
    opt = options;
    cb = callback;
  }

  if (typeof opt.db !== 'undefined') {
    params.DB = opt.db;
  }

  this._call('status', params, {}, cb);
};

Rpc.prototype.clear = function (options, callback) {
  var cb, opt = {}, params = {};

  if (typeof options === 'function') {
    opt = {};
    cb = options;
  } else {
    opt = options;
    cb = callback;
  }

  if (typeof opt.db !== 'undefined') {
    params.DB = opt.db;
  }

  this._call('clear', params, {}, cb);
};

// Rpc.prototype.synchronize = function (options, callback) {};

Rpc.prototype.append = function (key, value, options, callback) {
  var cb, opt = {}, params = {};

  if (typeof options === 'function') {
    opt = {};
    cb = options;
  } else {
    opt = options;
    cb = callback;
  }

  params.key = key;
  params.value = value;

  if (typeof opt.db !== 'undefined') {
    params.DB = opt.db;
  }

  if (typeof opt.expire !== 'undefined') {
    params.xt = opt.expire;
  }

  this._call('append', params, {}, cb);
};

Rpc.prototype.increment = function (key, num, options, callback) {
  var cb, opt = {}, params = {};

  if (typeof options === 'function') {
    opt = {};
    cb = options;
  } else {
    opt = options;
    cb = callback;
  }

  params.key = key;
  params.num = num;

  if (typeof opt.db !== 'undefined') {
    params.DB = opt.db;
  }

  if (typeof opt.expire !== 'undefined') {
    params.xt = opt.expire;
  }

  if (typeof opt.orig !== 'undefined') {
    params.orig = opt.orig;
  }

  this._call('append', params, {}, cb);
};

// Rpc.prototype.incrementDouble = function (options, callback) {};
// Rpc.prototype.cas = function (options, callback) {};

Rpc.prototype.check = function (key, options, callback) {
  var cb, opt = {}, params = {};

  if (typeof options === 'function') {
    opt = {};
    cb = options;
  } else {
    opt = options;
    cb = callback;
  }

  params.key = key;

  if (typeof opt.db !== 'undefined') {
    params.DB = opt.db;
  }

  this._call('check', params, {}, function (error, ret) {
    var size, expire;

    if (typeof error !== 'undefined') {
      cb(error);
      return;
    }

    if (typeof ret.vsiz !== 'undefined') {
      size = Number(ret.vsiz);
    }

    if (typeof ret.xt !== 'undefined') {
      expire = new Date(ret.xt);
    }

    cb(error, size, expire);
  });
};

Rpc.prototype.seize = function (key, options, callback) {
  var cb, opt = {}, params = {};

  if (typeof options === 'function') {
    opt = {};
    cb = options;
  } else {
    opt = options;
    cb = callback;
  }

  params.key = key;

  if (typeof opt.db !== 'undefined') {
    params.DB = opt.db;
  }

  this._call('seize', params, {}, function (error, ret) {
    var value, expire;

    if (typeof error !== 'undefined') {
      cb(error);
      return;
    }

    if (typeof ret.value !== 'undefined') {
      value = ret.value;
    }

    if (typeof ret.xt !== 'undefined') {
      expire = new Date(ret.xt);
    }

    cb(error, value, expire);
  });
};

// Rpc.prototype.setBulk = function (options, callback) {};
// Rpc.prototype.removeBulk = function (options, callback) {};
// Rpc.prototype.getBulk = function (options, callback) {};

Rpc.prototype.vacuum = function (options, callback) {
  var cb, opt = {}, params = {};

  if (typeof options === 'function') {
    opt = {};
    cb = options;
  } else {
    opt = options;
    cb = callback;
  }

  if (typeof opt.step !== 'undefined') {
    params.step = opt.step;
  }

  if (typeof opt.db !== 'undefined') {
    params.DB = opt.db;
  }

  this._call('vacuum', params, {}, cb);
};

Rpc.prototype.matchPrefix = function (prefix, options, callback) {
  var cb, opt = {}, params = {};

  if (typeof options === 'function') {
    opt = {};
    cb = options;
  } else {
    opt = options;
    cb = callback;
  }

  params.prefix = prefix;

  if (typeof opt.db !== 'undefined') {
    params.DB = opt.db;
  }

  if (typeof opt.max !== 'undefined') {
    params.max = opt.max;
  }

  this._call('match_prefix', params, {}, function (error, ret) {
    var data = [];

    if (typeof error !== 'undefined') {
      cb(error);
      return;
    }

    for (var key in ret) {
      if (ret.hasOwnProperty(key) && key[0] === '_') {
        data.push(key.substr(1));
      }
    }
    cb(undefined, data);
  });
};

Rpc.prototype.matchRegex = function (regex, options, callback) {
  var cb, opt = {}, params = {};

  if (typeof options === 'function') {
    opt = {};
    cb = options;
  } else {
    opt = options;
    cb = callback;
  }

  params.regex = regex;

  if (typeof opt.db !== 'undefined') {
    params.DB = opt.db;
  }

  if (typeof opt.max !== 'undefined') {
    params.max = opt.max;
  }

  this._call('match_regex', params, {}, function (error, ret) {
    var data = [];

    if (typeof error !== 'undefined') {
      cb(error);
      return;
    }

    for (var key in ret) {
      if (ret.hasOwnProperty(key) && key[0] === '_') {
        data.push(key.substr(1));
      }
    }
    cb(undefined, data);
  });
};

// Rpc.prototype.matchSimilar = function (options, callback) {};
// Rpc.prototype.curJump = function (options, callback) {};
// Rpc.prototype.curJumpBack = function (options, callback) {};
// Rpc.prototype.curStep = function (options, callback) {};
// Rpc.prototype.curStepBack = function (options, callback) {};
// Rpc.prototype.curSetValue = function (options, callback) {};
// Rpc.prototype.curRemove = function (options, callback) {};
// Rpc.prototype.curGetGey = function (options, callback) {};
// Rpc.prototype.curGetValue = function (options, callback) {};
// Rpc.prototype.curGet = function (options, callback) {};
// Rpc.prototype.curSeize = function (options, callback) {};
// Rpc.prototype.curDelete = function (options, callback) {};

Rpc.prototype._call = function (method, params, options, callback) {
  var _this = this, paramStr = '';
  if (typeof params !== 'undefined') {
    paramStr = '?' + querystring.stringify(params);
  }
  var requestOptions = {
    hostname: this.host,
    port: this.port,
    path: '/rpc/' + method + paramStr,
    method: 'GET',
    agent: this.agent
  };

  http.request(requestOptions, function (res) {
    var buf = new BufferList(), str = '';

    res.on('data', function (chunk) {
      if (Buffer.isBuffer(chunk)) {
        buf.append(chunk);
      } else {
        str += chunk;
      }
    });

    res.on('end', function () {
      var ret;

      if (res.statusCode === 200) {
        if (buf.length) {
          // TSV-RPC response is string only
          ret = buf.toString();
        } else {
          ret = str;
        }

        if (typeof res.headers['Content-Type'] !== 'string') {
          callback(undefined, _this._parse(ret));
        } else if (res.headers['Content-Type'].indexOf('colenc=B')) {
          callback(undefined, _this._parseBase64Encode(ret, options.encode));
        } else if (res.headers['Content-Type'].indexOf('colenc=U')) {
          callback(undefined, _this._parseURLEncode(ret));
        } else {
          callback(undefined, _this._parse(ret));
        }
      } else if (res.statusCode === 404) {
        callback('No record was found');
      } else if (res.statusCode === 400) {
        callback('Bad request');
      } else {
        callback('Connection error');
      }
    });
  }).on('error', function () {
    callback('Connection error');
  }).end();
};

Rpc.prototype._parse = function (tsv) {
  var lines = [], kv = [], ret = {};

  if (typeof tsv === 'string' && tsv.length > 0) {
    lines = tsv.replace(/\n$/, '').split('\n');

    for (var i = 0; i < lines.length; ++i) {
      kv = lines[i].split('\t');
      ret[kv[0]] = kv[1];
    }
  }

  return ret;
};

Rpc.prototype._parseBase64Encode = function (tsv, encode) {
  var lines = [], kv = [], ret = {}, i = 0;

  if (typeof tsv === 'string' && tsv.length > 0) {
    lines = tsv.replace(/\n$/, '').split('\n');

    if (typeof encode === 'undefined' || encode === null) {
      for (; i < lines.length; ++i) {
        kv = lines[i].split('\t');
        ret[new Buffer(kv[0], 'base64').toString()] =
        new Buffer(kv[1], 'base64').toString();
      }
    } else if (encode === 'binary') {
      for (; i < lines.length; ++i) {
        kv = lines[i].split('\t');
        ret[new Buffer(kv[0], 'base64').toString()] = new Buffer(kv[1], 'base64');
      }
    } else {
      for (; i < lines.length; ++i) {
        kv = lines[i].split('\t');
        ret[new Buffer(kv[0], 'base64').toString(encode)] =
        new Buffer(kv[1], 'base64').toString(encode);
      }
    }
  }

  return ret;
};

Rpc.prototype._parseURLEncode = function (tsv) {
  var lines = [], kv = [], ret = {};

  if (typeof tsv === 'string' && tsv.length > 0) {
    lines = tsv.replace(/\n$/, '').split('\n');

    for (var i = 0; i < lines.length; ++i) {
      kv = lines[i].split('\t');
      ret[decodeURIComponent(kv[0])] = decodeURIComponent(kv[1]);
    }
  }

  return ret;
};

module.exports = Rpc;
<commit_msg>Fixed bug<commit_after>'use strict';

var http = require('http');
var querystring = require('querystring');
var BufferList = require('bl');

function Rpc(agent, options) {
  this.agent = agent;
  this.host = options.host;
  this.port = options.port;
}

Rpc.prototype.void = function (callback) {
  this._call('void', undefined, {}, callback);
};

Rpc.prototype.echo = function (params, callback) {
  this._call('echo', params, {}, callback);
};

Rpc.prototype.report = function (callback) {
  this._call('report', undefined, {}, callback);
};

// Rpc.prototype.playScript = function (options, callback) {};
// Rpc.prototype.tuneReplication = function (options, callback) {};

Rpc.prototype.status = function (options, callback) {
  var cb, opt = {}, params = {};

  if (typeof options === 'function') {
    opt = {};
    cb = options;
  } else {
    opt = options;
    cb = callback;
  }

  if (typeof opt.db !== 'undefined') {
    params.DB = opt.db;
  }

  this._call('status', params, {}, cb);
};

Rpc.prototype.clear = function (options, callback) {
  var cb, opt = {}, params = {};

  if (typeof options === 'function') {
    opt = {};
    cb = options;
  } else {
    opt = options;
    cb = callback;
  }

  if (typeof opt.db !== 'undefined') {
    params.DB = opt.db;
  }

  this._call('clear', params, {}, cb);
};

// Rpc.prototype.synchronize = function (options, callback) {};

Rpc.prototype.append = function (key, value, options, callback) {
  var cb, opt = {}, params = {};

  if (typeof options === 'function') {
    opt = {};
    cb = options;
  } else {
    opt = options;
    cb = callback;
  }

  params.key = key;
  params.value = value;

  if (typeof opt.db !== 'undefined') {
    params.DB = opt.db;
  }

  if (typeof opt.expire !== 'undefined') {
    params.xt = opt.expire;
  }

  this._call('append', params, {}, cb);
};

Rpc.prototype.increment = function (key, num, options, callback) {
  var cb, opt = {}, params = {};

  if (typeof options === 'function') {
    opt = {};
    cb = options;
  } else {
    opt = options;
    cb = callback;
  }

  params.key = key;
  params.num = num;

  if (typeof opt.db !== 'undefined') {
    params.DB = opt.db;
  }

  if (typeof opt.expire !== 'undefined') {
    params.xt = opt.expire;
  }

  if (typeof opt.orig !== 'undefined') {
    params.orig = opt.orig;
  }

  this._call('increment', params, {}, cb);
};

// Rpc.prototype.incrementDouble = function (options, callback) {};
// Rpc.prototype.cas = function (options, callback) {};

Rpc.prototype.check = function (key, options, callback) {
  var cb, opt = {}, params = {};

  if (typeof options === 'function') {
    opt = {};
    cb = options;
  } else {
    opt = options;
    cb = callback;
  }

  params.key = key;

  if (typeof opt.db !== 'undefined') {
    params.DB = opt.db;
  }

  this._call('check', params, {}, function (error, ret) {
    var size, expire;

    if (typeof error !== 'undefined') {
      cb(error);
      return;
    }

    if (typeof ret.vsiz !== 'undefined') {
      size = Number(ret.vsiz);
    }

    if (typeof ret.xt !== 'undefined') {
      expire = new Date(ret.xt);
    }

    cb(error, size, expire);
  });
};

Rpc.prototype.seize = function (key, options, callback) {
  var cb, opt = {}, params = {};

  if (typeof options === 'function') {
    opt = {};
    cb = options;
  } else {
    opt = options;
    cb = callback;
  }

  params.key = key;

  if (typeof opt.db !== 'undefined') {
    params.DB = opt.db;
  }

  this._call('seize', params, {}, function (error, ret) {
    var value, expire;

    if (typeof error !== 'undefined') {
      cb(error);
      return;
    }

    if (typeof ret.value !== 'undefined') {
      value = ret.value;
    }

    if (typeof ret.xt !== 'undefined') {
      expire = new Date(ret.xt);
    }

    cb(error, value, expire);
  });
};

// Rpc.prototype.setBulk = function (options, callback) {};
// Rpc.prototype.removeBulk = function (options, callback) {};
// Rpc.prototype.getBulk = function (options, callback) {};

Rpc.prototype.vacuum = function (options, callback) {
  var cb, opt = {}, params = {};

  if (typeof options === 'function') {
    opt = {};
    cb = options;
  } else {
    opt = options;
    cb = callback;
  }

  if (typeof opt.step !== 'undefined') {
    params.step = opt.step;
  }

  if (typeof opt.db !== 'undefined') {
    params.DB = opt.db;
  }

  this._call('vacuum', params, {}, cb);
};

Rpc.prototype.matchPrefix = function (prefix, options, callback) {
  var cb, opt = {}, params = {};

  if (typeof options === 'function') {
    opt = {};
    cb = options;
  } else {
    opt = options;
    cb = callback;
  }

  params.prefix = prefix;

  if (typeof opt.db !== 'undefined') {
    params.DB = opt.db;
  }

  if (typeof opt.max !== 'undefined') {
    params.max = opt.max;
  }

  this._call('match_prefix', params, {}, function (error, ret) {
    var data = [];

    if (typeof error !== 'undefined') {
      cb(error);
      return;
    }

    for (var key in ret) {
      if (ret.hasOwnProperty(key) && key[0] === '_') {
        data.push(key.substr(1));
      }
    }
    cb(undefined, data);
  });
};

Rpc.prototype.matchRegex = function (regex, options, callback) {
  var cb, opt = {}, params = {};

  if (typeof options === 'function') {
    opt = {};
    cb = options;
  } else {
    opt = options;
    cb = callback;
  }

  params.regex = regex;

  if (typeof opt.db !== 'undefined') {
    params.DB = opt.db;
  }

  if (typeof opt.max !== 'undefined') {
    params.max = opt.max;
  }

  this._call('match_regex', params, {}, function (error, ret) {
    var data = [];

    if (typeof error !== 'undefined') {
      cb(error);
      return;
    }

    for (var key in ret) {
      if (ret.hasOwnProperty(key) && key[0] === '_') {
        data.push(key.substr(1));
      }
    }
    cb(undefined, data);
  });
};

// Rpc.prototype.matchSimilar = function (options, callback) {};
// Rpc.prototype.curJump = function (options, callback) {};
// Rpc.prototype.curJumpBack = function (options, callback) {};
// Rpc.prototype.curStep = function (options, callback) {};
// Rpc.prototype.curStepBack = function (options, callback) {};
// Rpc.prototype.curSetValue = function (options, callback) {};
// Rpc.prototype.curRemove = function (options, callback) {};
// Rpc.prototype.curGetGey = function (options, callback) {};
// Rpc.prototype.curGetValue = function (options, callback) {};
// Rpc.prototype.curGet = function (options, callback) {};
// Rpc.prototype.curSeize = function (options, callback) {};
// Rpc.prototype.curDelete = function (options, callback) {};

Rpc.prototype._call = function (method, params, options, callback) {
  var _this = this, paramStr = '';
  if (typeof params !== 'undefined') {
    paramStr = '?' + querystring.stringify(params);
  }
  var requestOptions = {
    hostname: this.host,
    port: this.port,
    path: '/rpc/' + method + paramStr,
    method: 'GET',
    agent: this.agent
  };

  http.request(requestOptions, function (res) {
    var buf = new BufferList(), str = '';

    res.on('data', function (chunk) {
      if (Buffer.isBuffer(chunk)) {
        buf.append(chunk);
      } else {
        str += chunk;
      }
    });

    res.on('end', function () {
      var ret;

      if (res.statusCode === 200) {
        if (buf.length) {
          // TSV-RPC response is string only
          ret = buf.toString();
        } else {
          ret = str;
        }

        if (typeof res.headers['Content-Type'] !== 'string') {
          callback(undefined, _this._parse(ret));
        } else if (res.headers['Content-Type'].indexOf('colenc=B')) {
          callback(undefined, _this._parseBase64Encode(ret, options.encode));
        } else if (res.headers['Content-Type'].indexOf('colenc=U')) {
          callback(undefined, _this._parseURLEncode(ret));
        } else {
          callback(undefined, _this._parse(ret));
        }
      } else if (res.statusCode === 404) {
        callback('No record was found');
      } else if (res.statusCode === 400) {
        callback('Bad request');
      } else {
        callback('Connection error');
      }
    });
  }).on('error', function () {
    callback('Connection error');
  }).end();
};

Rpc.prototype._parse = function (tsv) {
  var lines = [], kv = [], ret = {};

  if (typeof tsv === 'string' && tsv.length > 0) {
    lines = tsv.replace(/\n$/, '').split('\n');

    for (var i = 0; i < lines.length; ++i) {
      kv = lines[i].split('\t');
      ret[kv[0]] = kv[1];
    }
  }

  return ret;
};

Rpc.prototype._parseBase64Encode = function (tsv, encode) {
  var lines = [], kv = [], ret = {}, i = 0;

  if (typeof tsv === 'string' && tsv.length > 0) {
    lines = tsv.replace(/\n$/, '').split('\n');

    if (typeof encode === 'undefined' || encode === null) {
      for (; i < lines.length; ++i) {
        kv = lines[i].split('\t');
        ret[new Buffer(kv[0], 'base64').toString()] =
        new Buffer(kv[1], 'base64').toString();
      }
    } else if (encode === 'binary') {
      for (; i < lines.length; ++i) {
        kv = lines[i].split('\t');
        ret[new Buffer(kv[0], 'base64').toString()] = new Buffer(kv[1], 'base64');
      }
    } else {
      for (; i < lines.length; ++i) {
        kv = lines[i].split('\t');
        ret[new Buffer(kv[0], 'base64').toString(encode)] =
        new Buffer(kv[1], 'base64').toString(encode);
      }
    }
  }

  return ret;
};

Rpc.prototype._parseURLEncode = function (tsv) {
  var lines = [], kv = [], ret = {};

  if (typeof tsv === 'string' && tsv.length > 0) {
    lines = tsv.replace(/\n$/, '').split('\n');

    for (var i = 0; i < lines.length; ++i) {
      kv = lines[i].split('\t');
      ret[decodeURIComponent(kv[0])] = decodeURIComponent(kv[1]);
    }
  }

  return ret;
};

module.exports = Rpc;
<|endoftext|>


<commit_before>/* Thunk
   Creates a thunk representing the given closure.
   Since we want automatic memoization of as many expressions as possible, we
   use a JS object as a sort of tagged pointer, where the member x denotes the
   object actually pointed to. If a "pointer" points to a thunk, it has a
   member 't' which is set to true; if it points to a value, be it a function,
   a value of an algebraic type of a primitive value, it has no member 't'.
*/

function T(f) {
    this.f = f;
}

/* Apply
   Applies the function f to the arguments args. If the application is under-
   saturated, a closure is returned, awaiting further arguments. If it is over-
   saturated, the function is fully applied, and the result (assumed to be a
   function) is then applied to the remaining arguments.
*/
function A(f, args) {
    f = f instanceof T ? E(f) : f;
    // Closure does some funny stuff with functions that occasionally
    // results in non-functions getting applied, so we have to deal with
    // it.
    if(!f.apply) {
        return f;
    }

    var arity = f.arity ? f.arity : f.length;
    if(args.length === arity) {
        return f.apply(null, args);
    }
    if(args.length > arity) {
        var first = args.splice(0, arity);
        return A(f.apply(null, first), args);
    } else {
        var g = function() {
            var as = args.concat(Array.prototype.slice.call(arguments));
            return A(f, as);
        };
        g.arity = arity - args.length;
        return g;
    }
}

/* Eval
   Evaluate the given thunk t into head normal form.
   If the "thunk" we get isn't actually a thunk, just return it.
*/
function E(t) {
    if(t instanceof T) {
        if(t.f) {
            t.x = t.f();
            t.f = 0;
        }
        return t.x;
    }
    return t;
}

/* Throw an error.
   We need to be able to use throw as an exception so we wrap it in a function.
*/
function die(err) {
    throw err;
}

function quot(a, b) {
    return (a-a%b)/b;
}

function quotRemI(a, b) {
    return [0, (a-a%b)/b, a%b];
}

// 32 bit integer multiplication, with correct overflow behavior
// note that |0 or >>>0 needs to be applied to the result, for int and word
// respectively.
function imul(a, b) {
  // ignore high a * high a as the result will always be truncated
  var lows = (a & 0xffff) * (b & 0xffff); // low a * low b
  var aB = (a & 0xffff) * (b & 0xffff0000); // low a * high b
  var bA = (a & 0xffff0000) * (b & 0xffff); // low b * high a
  return lows + aB + bA; // sum will not exceed 52 bits, so it's safe
}

function addC(a, b) {
    var x = a+b;
    return [0, x & 0xffffffff, x > 0x7fffffff];
}

function subC(a, b) {
    var x = a-b;
    return [0, x & 0xffffffff, x < -2147483648];
}

function sinh (arg) {
    return (Math.exp(arg) - Math.exp(-arg)) / 2;
}

function tanh (arg) {
    return (Math.exp(arg) - Math.exp(-arg)) / (Math.exp(arg) + Math.exp(-arg));
}

function cosh (arg) {
    return (Math.exp(arg) + Math.exp(-arg)) / 2;
}

// Scratch space for byte arrays.
var rts_scratchBuf = new ArrayBuffer(8);
var rts_scratchW32 = new Uint32Array(rts_scratchBuf);
var rts_scratchFloat = new Float32Array(rts_scratchBuf);
var rts_scratchDouble = new Float64Array(rts_scratchBuf);

function decodeFloat(x) {
    rts_scratchFloat[0] = x;
    var sign = x < 0 ? -1 : 1;
    var exp = ((rts_scratchW32[0] >> 23) & 0xff) - 150;
    var man = rts_scratchW32[0] & 0x7fffff;
    if(exp === 0) {
        ++exp;
    } else {
        man |= (1 << 23);
    }
    return [0, sign*man, exp];
}

function decodeDouble(x) {
    rts_scratchDouble[0] = x;
    var sign = x < 0 ? -1 : 1;
    var manHigh = rts_scratchW32[1] & 0xfffff;
    var manLow = rts_scratchW32[0];
    var exp = ((rts_scratchW32[1] >> 20) & 0x7ff) - 1075;
    if(exp === 0) {
        ++exp;
    } else {
        manHigh |= (1 << 20);
    }
    return [0, sign, manHigh, manLow, exp];
}

function err(str) {
    die(toJSStr(str)[1]);
}

/* unpackCString#
   NOTE: update constructor tags if the code generator starts munging them.
*/
function unCStr(str) {return unAppCStr(str, [0]);}

function unFoldrCStr(str, f, z) {
    var acc = z;
    for(var i = str.length-1; i >= 0; --i) {
        acc = A(f, [[0, str.charCodeAt(i)], acc]);
    }
    return acc;
}

function unAppCStr(str, chrs) {
    var i = arguments[2] ? arguments[2] : 0;
    if(i >= str.length) {
        return E(chrs);
    } else {
        return [1,[0,str.charCodeAt(i)],new T(function() {
            return unAppCStr(str,chrs,i+1);
        })];
    }
}

function charCodeAt(str, i) {return str.charCodeAt(i);}

function fromJSStr(str) {
    return unCStr(E(str)[1]);
}

function toJSStr(hsstr) {
    var s = '';
    for(var str = E(hsstr); str[0] == 1; str = E(str[2])) {
        s += String.fromCharCode(E(str[1])[1]);
    }
    return [0,s];
}

// newMutVar
function nMV(val) {
    return ({x: val});
}

// readMutVar
function rMV(mv) {
    return mv.x;
}

// writeMutVar
function wMV(mv, val) {
    mv.x = val;
}

function localeEncoding() {
    var le = newByteArr(5);
    le['b']['i8'] = 'U'.charCodeAt(0);
    le['b']['i8'] = 'T'.charCodeAt(0);
    le['b']['i8'] = 'F'.charCodeAt(0);
    le['b']['i8'] = '-'.charCodeAt(0);
    le['b']['i8'] = '8'.charCodeAt(0);
    return le;
}

var isFloatNaN = isDoubleNaN = isNaN;

function isDoubleInfinite(d) {
    return (d === Infinity);
}
var isFloatInfinite = isDoubleInfinite;

function isDoubleNegativeZero(x) {
    return (x===0 && (1/x)===-Infinity);
}
var isFloatNegativeZero = isDoubleNegativeZero;

function strEq(a, b) {
    return a == b;
}

function strOrd(a, b) {
    if(a < b) {
        return [0];
    } else if(a == b) {
        return [1];
    }
    return [2];
}

function jsCatch(act, handler) {
    try {
        return A(act,[0]);
    } catch(e) {
        return A(handler,[e, 0]);
    }
}

function hs_eqWord64(a, b) {
    return (a[0] == b[0] && a[1] == b[1]);
}

// Word64# representation: (Word, Word)
function hs_wordToWord64(low) {
    return [0, low];
}

function hs_mkWord64(high, low) {
    return [high, low];
}

var coercionToken = undefined;

/* Haste represents constructors internally using 1 for the first constructor,
   2 for the second, etc.
   However, dataToTag should use 0, 1, 2, etc. Also, booleans might be unboxed.
 */
function dataToTag(x) {
    if(x instanceof Array) {
        return x[0];
    } else {
        return x;
    }
}

function __word_encodeDouble(d, e) {
    return d * Math.pow(2,e);
}

var __word_encodeFloat = __word_encodeDouble;
var jsRound = Math.round; // Stupid GHC doesn't like periods in FFI IDs...
if(typeof _ == 'undefined') {
    var _ = undefined;
}
<commit_msg>Optimize eval/apply function application a bit.<commit_after>/* Thunk
   Creates a thunk representing the given closure.
   Since we want automatic memoization of as many expressions as possible, we
   use a JS object as a sort of tagged pointer, where the member x denotes the
   object actually pointed to. If a "pointer" points to a thunk, it has a
   member 't' which is set to true; if it points to a value, be it a function,
   a value of an algebraic type of a primitive value, it has no member 't'.
*/

function T(f) {
    this.f = f;
}

/* Apply
   Applies the function f to the arguments args. If the application is under-
   saturated, a closure is returned, awaiting further arguments. If it is over-
   saturated, the function is fully applied, and the result (assumed to be a
   function) is then applied to the remaining arguments.
*/
function A(f, args) {
    f = f instanceof T ? E(f) : f;
    // Closure does some funny stuff with functions that occasionally
    // results in non-functions getting applied, so we have to deal with
    // it.
    if(!f.apply) {
        return f;
    }

    if(f.arity === undefined) {
        f.arity = f.length;
    }
    if(args.length === f.arity) {
        return f.apply(null, args);
    }
    if(args.length > f.arity) {
        var first = args.splice(0, f.arity);
        return A(f.apply(null, first), args);
    } else {
        var g = function() {
            var as = args.concat(Array.prototype.slice.call(arguments));
            return A(f, as);
        };
        g.arity = f.arity - args.length;
        return g;
    }
}

/* Eval
   Evaluate the given thunk t into head normal form.
   If the "thunk" we get isn't actually a thunk, just return it.
*/
function E(t) {
    if(t instanceof T) {
        if(t.f) {
            t.x = t.f();
            t.f = 0;
        }
        return t.x;
    }
    return t;
}

/* Throw an error.
   We need to be able to use throw as an exception so we wrap it in a function.
*/
function die(err) {
    throw err;
}

function quot(a, b) {
    return (a-a%b)/b;
}

function quotRemI(a, b) {
    return [0, (a-a%b)/b, a%b];
}

// 32 bit integer multiplication, with correct overflow behavior
// note that |0 or >>>0 needs to be applied to the result, for int and word
// respectively.
function imul(a, b) {
  // ignore high a * high a as the result will always be truncated
  var lows = (a & 0xffff) * (b & 0xffff); // low a * low b
  var aB = (a & 0xffff) * (b & 0xffff0000); // low a * high b
  var bA = (a & 0xffff0000) * (b & 0xffff); // low b * high a
  return lows + aB + bA; // sum will not exceed 52 bits, so it's safe
}

function addC(a, b) {
    var x = a+b;
    return [0, x & 0xffffffff, x > 0x7fffffff];
}

function subC(a, b) {
    var x = a-b;
    return [0, x & 0xffffffff, x < -2147483648];
}

function sinh (arg) {
    return (Math.exp(arg) - Math.exp(-arg)) / 2;
}

function tanh (arg) {
    return (Math.exp(arg) - Math.exp(-arg)) / (Math.exp(arg) + Math.exp(-arg));
}

function cosh (arg) {
    return (Math.exp(arg) + Math.exp(-arg)) / 2;
}

// Scratch space for byte arrays.
var rts_scratchBuf = new ArrayBuffer(8);
var rts_scratchW32 = new Uint32Array(rts_scratchBuf);
var rts_scratchFloat = new Float32Array(rts_scratchBuf);
var rts_scratchDouble = new Float64Array(rts_scratchBuf);

function decodeFloat(x) {
    rts_scratchFloat[0] = x;
    var sign = x < 0 ? -1 : 1;
    var exp = ((rts_scratchW32[0] >> 23) & 0xff) - 150;
    var man = rts_scratchW32[0] & 0x7fffff;
    if(exp === 0) {
        ++exp;
    } else {
        man |= (1 << 23);
    }
    return [0, sign*man, exp];
}

function decodeDouble(x) {
    rts_scratchDouble[0] = x;
    var sign = x < 0 ? -1 : 1;
    var manHigh = rts_scratchW32[1] & 0xfffff;
    var manLow = rts_scratchW32[0];
    var exp = ((rts_scratchW32[1] >> 20) & 0x7ff) - 1075;
    if(exp === 0) {
        ++exp;
    } else {
        manHigh |= (1 << 20);
    }
    return [0, sign, manHigh, manLow, exp];
}

function err(str) {
    die(toJSStr(str)[1]);
}

/* unpackCString#
   NOTE: update constructor tags if the code generator starts munging them.
*/
function unCStr(str) {return unAppCStr(str, [0]);}

function unFoldrCStr(str, f, z) {
    var acc = z;
    for(var i = str.length-1; i >= 0; --i) {
        acc = A(f, [[0, str.charCodeAt(i)], acc]);
    }
    return acc;
}

function unAppCStr(str, chrs) {
    var i = arguments[2] ? arguments[2] : 0;
    if(i >= str.length) {
        return E(chrs);
    } else {
        return [1,[0,str.charCodeAt(i)],new T(function() {
            return unAppCStr(str,chrs,i+1);
        })];
    }
}

function charCodeAt(str, i) {return str.charCodeAt(i);}

function fromJSStr(str) {
    return unCStr(E(str)[1]);
}

function toJSStr(hsstr) {
    var s = '';
    for(var str = E(hsstr); str[0] == 1; str = E(str[2])) {
        s += String.fromCharCode(E(str[1])[1]);
    }
    return [0,s];
}

// newMutVar
function nMV(val) {
    return ({x: val});
}

// readMutVar
function rMV(mv) {
    return mv.x;
}

// writeMutVar
function wMV(mv, val) {
    mv.x = val;
}

function localeEncoding() {
    var le = newByteArr(5);
    le['b']['i8'] = 'U'.charCodeAt(0);
    le['b']['i8'] = 'T'.charCodeAt(0);
    le['b']['i8'] = 'F'.charCodeAt(0);
    le['b']['i8'] = '-'.charCodeAt(0);
    le['b']['i8'] = '8'.charCodeAt(0);
    return le;
}

var isFloatNaN = isDoubleNaN = isNaN;

function isDoubleInfinite(d) {
    return (d === Infinity);
}
var isFloatInfinite = isDoubleInfinite;

function isDoubleNegativeZero(x) {
    return (x===0 && (1/x)===-Infinity);
}
var isFloatNegativeZero = isDoubleNegativeZero;

function strEq(a, b) {
    return a == b;
}

function strOrd(a, b) {
    if(a < b) {
        return [0];
    } else if(a == b) {
        return [1];
    }
    return [2];
}

function jsCatch(act, handler) {
    try {
        return A(act,[0]);
    } catch(e) {
        return A(handler,[e, 0]);
    }
}

function hs_eqWord64(a, b) {
    return (a[0] == b[0] && a[1] == b[1]);
}

// Word64# representation: (Word, Word)
function hs_wordToWord64(low) {
    return [0, low];
}

function hs_mkWord64(high, low) {
    return [high, low];
}

var coercionToken = undefined;

/* Haste represents constructors internally using 1 for the first constructor,
   2 for the second, etc.
   However, dataToTag should use 0, 1, 2, etc. Also, booleans might be unboxed.
 */
function dataToTag(x) {
    if(x instanceof Array) {
        return x[0];
    } else {
        return x;
    }
}

function __word_encodeDouble(d, e) {
    return d * Math.pow(2,e);
}

var __word_encodeFloat = __word_encodeDouble;
var jsRound = Math.round; // Stupid GHC doesn't like periods in FFI IDs...
if(typeof _ == 'undefined') {
    var _ = undefined;
}
<|endoftext|>