<commit_before>(function(root, factory) {
  if (typeof define === 'function' && define.amd) {
    define([], factory) /* global define */
  } else if (typeof module === 'object' && module.exports) {
    module.exports = factory()
  } else {
    root.Moo = factory()
  }
}(this, function() {
  'use strict';

  var hasSticky = typeof new RegExp().sticky === 'boolean'

  function isRegExp(o) { return o && o.constructor === RegExp }

  function reEscape(s) {
    return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&')
  }
  function reGroups(s) {
    var re = new RegExp('|' + s)
    return re.exec('').length - 1
  }
  function reCapture(s) {
    return '(' + s + ')'
  }
  function reUnion(regexps) {
    var source =  regexps.map(function(s) {
      return "(?:" + s + ")"
    }).join('|')
    return "(?:" + source + ")"
  }

  function compareLength(a, b) {
    return b.length - a.length
  }

  function sortPatterns(array) {
    // sort literals by length to ensure longest match
    var regexps = []
    var literals = []
    for (var i=0; i<array.length; i++) {
      var obj = array[i]
      ;(isRegExp(obj) ? regexps : literals).push(obj)
    }
    literals.sort(compareLength)
    // append regexps to the end
    return literals.concat(regexps)
  }

  function regexpOrLiteral(obj) {
    if (typeof obj === 'string') {
      return '(?:' + reEscape(obj) + ')'

    } else if (isRegExp(obj)) {
      // TODO: consider /u support
      if (obj.ignoreCase) { throw new Error('RegExp /i flag not allowed') }
      if (obj.global) { throw new Error('RegExp /g flag is implied') }
      if (obj.sticky) { throw new Error('RegExp /y flag is implied') }
      if (obj.multiline) { throw new Error('RegExp /m flag is implied') }
      return obj.source

    } else {
      throw new Error('not a pattern: ' + obj)
    }
  }

  function pattern(obj) {
    if (typeof obj === 'string') {
      return '(' + reEscape(obj) + ')'

    } else if (Array.isArray(obj)) {
      // sort to help ensure longest match
      var options = sortPatterns(obj)
      return '(' + options.map(regexpOrLiteral).join('|') + ')'

    } else {
      return regexpOrLiteral(obj)
    }
  }

  function objectToRules(object) {
    var keys = Object.getOwnPropertyNames(object)
    var result = []
    for (var i=0; i<keys.length; i++) {
      var key = keys[i]
      result.push([key, object[key]])
    }
    return result
  }

  function compileRules(rules, hasStates) {
    if (!Array.isArray(rules)) rules = objectToRules(rules)
    var groups = []
    var parts = []
    for (var i=0; i<rules.length; i++) {
      var rule = rules[i]
      var name = rule[0]
      var obj = rule[1]

      // get options
      if (typeof obj !== 'object' || Array.isArray(obj) || isRegExp(obj)) {
        obj = { match: obj }
      }
      var options = Object.assign({
        name: name,
        lineBreaks: false,
        pop: false,
        next: null,
        push: null,
      }, obj)
      groups.push(options)

      // convert to RegExp
      var pat = pattern(obj.match)

      // validate
      var regexp = new RegExp(pat)
      if (regexp.test("")) {
        throw new Error("RegExp matches empty string: " + regexp)
      }
      var groupCount = reGroups(pat)
      if (groupCount > 1) {
        throw new Error("RegExp has more than one capture group: " + regexp)
      }
      if (!hasStates && (options.pop || options.push || options.next)) {
        throw new Error("State-switching options are not allowed in stateless lexers (for token '" + name + "')")
      }

      // try and detect rules matching newlines
      if (!options.lineBreaks && regexp.test('\n')) {
        throw new Error('Rule should declare lineBreaks: ' + regexp)
      }

      // store regex
      var isCapture = !!groupCount
      if (!isCapture) pat = reCapture(pat)
      parts.push(pat)
    }

    var suffix = hasSticky ? '' : '|(?:)'
    var flags = hasSticky ? 'ym' : 'gm'
    var regexp = new RegExp(reUnion(parts) + suffix, flags)

    return {regexp: regexp, groups: groups}
  }

  function compile(rules) {
    var result = compileRules(rules)
    return new Lexer({start: result}, 'start')
  }

  function compileStates(states, start) {
    var keys = Object.getOwnPropertyNames(states)
    if (!start) start = keys[0]

    var map = Object.create(null)
    for (var i=0; i<keys.length; i++) {
      var key = keys[i]
      map[key] = compileRules(states[key], true)
    }

    for (var i=0; i<keys.length; i++) {
      var groups = map[keys[i]].groups
      for (var j=0; j<groups.length; j++) {
        var g = groups[i]
        var state = g && (g.push || g.next)
        if (state && !map[state]) {
          throw new Error("Missing state '" + state + "' (in token '" + g.name + "' of state '" + keys[i] + "')")
        }
      }
    }

    return new Lexer(map, start)
  }

  var Lexer = function(states, state) {
    this.states = states
    this.buffer = ''
    this.stack = []
    this.setState(state)
    this.reset()
  }

  Lexer.error = {
    name: 'ERRORTOKEN',
    lineBreaks: true,
  }

  Lexer.prototype.setState = function(state) {
    if (!state || this.state === state) return
    this.state = state
    var index = this.re ? this.re.lastIndex : 0
    var info = this.states[state]
    this.groups = info.groups
    this.re = info.regexp
    this.re.lastIndex = index
  }

  Lexer.prototype.popState = function() {
    this.setState(this.stack.pop())
  }

  Lexer.prototype.pushState = function(state) {
    this.stack.push(this.state)
    this.setState(state)
  }

  Lexer.prototype.eat = hasSticky ? function(re) {
    // assume re is /y
    return re.exec(this.buffer)
  } : function(re) {
    // assume re is /g
    var match = re.exec(this.buffer)
    // assert(match)
    // assert(match.index === 0)
    if (match[0].length === 0) {
      return null
    }
    return match
  }
  // TODO: try instead the |(?:) trick?

  function tokenToString() {
    return this.value || this.name
  }

  Lexer.prototype.lex = function() {
    var re = this.re
    var buffer = this.buffer

    if (re.lastIndex === buffer.length) {
      return // EOF
    }

    var start = re.lastIndex
    var match = this.eat(re)
    var group, value, text
    if (match === null) {
      group = Lexer.error

      // consume rest of buffer
      text = value = buffer.slice(start)
      re.lastIndex = buffer.length

    } else {
      text = match[0]
      var groups = this.groups
      for (var i = 0; i < groups.length; i++) {
        var value = match[i + 1]
        if (value !== undefined) {
          group = groups[i]
          break
        }
      }
      // assert(i < groupCount)
      // TODO is `buffer` being leaked here?
    }

    // count line breaks
    var lineBreaks = 0
    if (group.lineBreaks) {
      var re = /\n/g
      var nl = 1
      if (text === '\n') {
        lineBreaks = 1
      } else {
        while (re.exec(text)) { lineBreaks++; nl = re.lastIndex }
      }
    }

    var size = text.length
    var token = {
      type: group.name,
      value: value,
      toString: tokenToString,
      offset: start,
      size: size,
      lineBreaks: lineBreaks,
      line: this.line,
      col: this.col,
    }

    if (group.pop) {
      this.popState()
    } else if (group.push) {
      this.pushState(group.push)
    } else if (group.next) {
      this.setState(group.next)
    }

    this.line += lineBreaks
    if (lineBreaks !== 0) {
      this.col = size - nl + 1
    } else {
      this.col += size
    }
    return token
  }

  Lexer.prototype.lexAll = function() {
    var tokens = []
    var token
    while ((token = this.lex())) {
      tokens.push(token)
    }
    return tokens
  }

  Lexer.prototype.index = function() {
    return this.re.lastIndex
  }

  Lexer.prototype.reset = function(data, state) {
    this.buffer = data || ''
    this.re.lastIndex = 0
    this.line = state ? state.line : 1
    this.col = state ? state.col : 1
    return this
  }

  Lexer.prototype.save = function() {
    return {
      line: this.line,
      col: this.col,
    }
  }

  Lexer.prototype.feed = function(data) {
    this.buffer += data
    return this
  }

  Lexer.prototype.remaining = function() {
    return this.buffer.slice(this.re.lastIndex)
  }

  Lexer.prototype.clone = function(input) {
    var map = Object.create(null), keys = Object.getOwnPropertyNames(this.states)
    for (var i = 0; i < keys.length; i++) {
      var key = keys[i]
      var s = this.states[key]
      map[key] = {
        groups: s.groups,
        regexp: new RegExp(s.regexp.source, s.regexp.flags),
      }
    }
    return new Lexer(map, this.state, input)
  }

  var moo = {} // TODO: what should moo() do?
  moo.compile = compile
  moo.states = compileStates
  return moo

}))
<commit_msg>Fix tokenToString<commit_after>(function(root, factory) {
  if (typeof define === 'function' && define.amd) {
    define([], factory) /* global define */
  } else if (typeof module === 'object' && module.exports) {
    module.exports = factory()
  } else {
    root.Moo = factory()
  }
}(this, function() {
  'use strict';

  var hasSticky = typeof new RegExp().sticky === 'boolean'

  function isRegExp(o) { return o && o.constructor === RegExp }

  function reEscape(s) {
    return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&')
  }
  function reGroups(s) {
    var re = new RegExp('|' + s)
    return re.exec('').length - 1
  }
  function reCapture(s) {
    return '(' + s + ')'
  }
  function reUnion(regexps) {
    var source =  regexps.map(function(s) {
      return "(?:" + s + ")"
    }).join('|')
    return "(?:" + source + ")"
  }

  function compareLength(a, b) {
    return b.length - a.length
  }

  function sortPatterns(array) {
    // sort literals by length to ensure longest match
    var regexps = []
    var literals = []
    for (var i=0; i<array.length; i++) {
      var obj = array[i]
      ;(isRegExp(obj) ? regexps : literals).push(obj)
    }
    literals.sort(compareLength)
    // append regexps to the end
    return literals.concat(regexps)
  }

  function regexpOrLiteral(obj) {
    if (typeof obj === 'string') {
      return '(?:' + reEscape(obj) + ')'

    } else if (isRegExp(obj)) {
      // TODO: consider /u support
      if (obj.ignoreCase) { throw new Error('RegExp /i flag not allowed') }
      if (obj.global) { throw new Error('RegExp /g flag is implied') }
      if (obj.sticky) { throw new Error('RegExp /y flag is implied') }
      if (obj.multiline) { throw new Error('RegExp /m flag is implied') }
      return obj.source

    } else {
      throw new Error('not a pattern: ' + obj)
    }
  }

  function pattern(obj) {
    if (typeof obj === 'string') {
      return '(' + reEscape(obj) + ')'

    } else if (Array.isArray(obj)) {
      // sort to help ensure longest match
      var options = sortPatterns(obj)
      return '(' + options.map(regexpOrLiteral).join('|') + ')'

    } else {
      return regexpOrLiteral(obj)
    }
  }

  function objectToRules(object) {
    var keys = Object.getOwnPropertyNames(object)
    var result = []
    for (var i=0; i<keys.length; i++) {
      var key = keys[i]
      result.push([key, object[key]])
    }
    return result
  }

  function compileRules(rules, hasStates) {
    if (!Array.isArray(rules)) rules = objectToRules(rules)
    var groups = []
    var parts = []
    for (var i=0; i<rules.length; i++) {
      var rule = rules[i]
      var name = rule[0]
      var obj = rule[1]

      // get options
      if (typeof obj !== 'object' || Array.isArray(obj) || isRegExp(obj)) {
        obj = { match: obj }
      }
      var options = Object.assign({
        name: name,
        lineBreaks: false,
        pop: false,
        next: null,
        push: null,
      }, obj)
      groups.push(options)

      // convert to RegExp
      var pat = pattern(obj.match)

      // validate
      var regexp = new RegExp(pat)
      if (regexp.test("")) {
        throw new Error("RegExp matches empty string: " + regexp)
      }
      var groupCount = reGroups(pat)
      if (groupCount > 1) {
        throw new Error("RegExp has more than one capture group: " + regexp)
      }
      if (!hasStates && (options.pop || options.push || options.next)) {
        throw new Error("State-switching options are not allowed in stateless lexers (for token '" + name + "')")
      }

      // try and detect rules matching newlines
      if (!options.lineBreaks && regexp.test('\n')) {
        throw new Error('Rule should declare lineBreaks: ' + regexp)
      }

      // store regex
      var isCapture = !!groupCount
      if (!isCapture) pat = reCapture(pat)
      parts.push(pat)
    }

    var suffix = hasSticky ? '' : '|(?:)'
    var flags = hasSticky ? 'ym' : 'gm'
    var regexp = new RegExp(reUnion(parts) + suffix, flags)

    return {regexp: regexp, groups: groups}
  }

  function compile(rules) {
    var result = compileRules(rules)
    return new Lexer({start: result}, 'start')
  }

  function compileStates(states, start) {
    var keys = Object.getOwnPropertyNames(states)
    if (!start) start = keys[0]

    var map = Object.create(null)
    for (var i=0; i<keys.length; i++) {
      var key = keys[i]
      map[key] = compileRules(states[key], true)
    }

    for (var i=0; i<keys.length; i++) {
      var groups = map[keys[i]].groups
      for (var j=0; j<groups.length; j++) {
        var g = groups[i]
        var state = g && (g.push || g.next)
        if (state && !map[state]) {
          throw new Error("Missing state '" + state + "' (in token '" + g.name + "' of state '" + keys[i] + "')")
        }
      }
    }

    return new Lexer(map, start)
  }

  var Lexer = function(states, state) {
    this.states = states
    this.buffer = ''
    this.stack = []
    this.setState(state)
    this.reset()
  }

  Lexer.error = {
    name: 'ERRORTOKEN',
    lineBreaks: true,
  }

  Lexer.prototype.setState = function(state) {
    if (!state || this.state === state) return
    this.state = state
    var index = this.re ? this.re.lastIndex : 0
    var info = this.states[state]
    this.groups = info.groups
    this.re = info.regexp
    this.re.lastIndex = index
  }

  Lexer.prototype.popState = function() {
    this.setState(this.stack.pop())
  }

  Lexer.prototype.pushState = function(state) {
    this.stack.push(this.state)
    this.setState(state)
  }

  Lexer.prototype.eat = hasSticky ? function(re) {
    // assume re is /y
    return re.exec(this.buffer)
  } : function(re) {
    // assume re is /g
    var match = re.exec(this.buffer)
    // assert(match)
    // assert(match.index === 0)
    if (match[0].length === 0) {
      return null
    }
    return match
  }
  // TODO: try instead the |(?:) trick?

  function tokenToString() {
    return this.value || this.type
  }

  Lexer.prototype.lex = function() {
    var re = this.re
    var buffer = this.buffer

    if (re.lastIndex === buffer.length) {
      return // EOF
    }

    var start = re.lastIndex
    var match = this.eat(re)
    var group, value, text
    if (match === null) {
      group = Lexer.error

      // consume rest of buffer
      text = value = buffer.slice(start)
      re.lastIndex = buffer.length

    } else {
      text = match[0]
      var groups = this.groups
      for (var i = 0; i < groups.length; i++) {
        var value = match[i + 1]
        if (value !== undefined) {
          group = groups[i]
          break
        }
      }
      // assert(i < groupCount)
      // TODO is `buffer` being leaked here?
    }

    // count line breaks
    var lineBreaks = 0
    if (group.lineBreaks) {
      var re = /\n/g
      var nl = 1
      if (text === '\n') {
        lineBreaks = 1
      } else {
        while (re.exec(text)) { lineBreaks++; nl = re.lastIndex }
      }
    }

    var size = text.length
    var token = {
      type: group.name,
      value: value,
      toString: tokenToString,
      offset: start,
      size: size,
      lineBreaks: lineBreaks,
      line: this.line,
      col: this.col,
    }

    if (group.pop) {
      this.popState()
    } else if (group.push) {
      this.pushState(group.push)
    } else if (group.next) {
      this.setState(group.next)
    }

    this.line += lineBreaks
    if (lineBreaks !== 0) {
      this.col = size - nl + 1
    } else {
      this.col += size
    }
    return token
  }

  Lexer.prototype.lexAll = function() {
    var tokens = []
    var token
    while ((token = this.lex())) {
      tokens.push(token)
    }
    return tokens
  }

  Lexer.prototype.index = function() {
    return this.re.lastIndex
  }

  Lexer.prototype.reset = function(data, state) {
    this.buffer = data || ''
    this.re.lastIndex = 0
    this.line = state ? state.line : 1
    this.col = state ? state.col : 1
    return this
  }

  Lexer.prototype.save = function() {
    return {
      line: this.line,
      col: this.col,
    }
  }

  Lexer.prototype.feed = function(data) {
    this.buffer += data
    return this
  }

  Lexer.prototype.remaining = function() {
    return this.buffer.slice(this.re.lastIndex)
  }

  Lexer.prototype.clone = function(input) {
    var map = Object.create(null), keys = Object.getOwnPropertyNames(this.states)
    for (var i = 0; i < keys.length; i++) {
      var key = keys[i]
      var s = this.states[key]
      map[key] = {
        groups: s.groups,
        regexp: new RegExp(s.regexp.source, s.regexp.flags),
      }
    }
    return new Lexer(map, this.state, input)
  }

  var moo = {} // TODO: what should moo() do?
  moo.compile = compile
  moo.states = compileStates
  return moo

}))
<|endoftext|>


<commit_before>#!/usr/bin/env node

'use strict';

const http = require('follow-redirects').http;

const https = require('follow-redirects').https;

const fs = require('fs');

const mkdirp = require('mkdirp');

const colors = require('colors/safe');

const argv = require('yargs')

.usage(colors.cyan.bold('\nUsage : $0 -u <command> [info] <command> [file]'))

.command('u', colors.cyan.bold('❱ ') + 'facebook user\'s username')

.command('i', colors.cyan.bold('❱ ') + 'facebook user\'s user-id')

.demand(['n'])

.describe('n', colors.cyan.bold('❱ ') + 'save image as')

.argv;

const updateNotifier = require('update-notifier');

const idFinder = {

    hostname: 'www.facebook.com',

    port: 443,

    path: '/' + argv.u,

    method: 'GET',

    headers: {

        'accept': 'text/html,application/json,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',

        'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.86 Safari/537.36',

        'Host': 'www.facebook.com',

        'Connection': 'Keep-Alive',

        'Accept-Language': 'en-GB,en-US;q=0.8,en;q=0.6'
    }
};

const userID = {

    hostname: 'www.facebook.com',

    port: 443,

    path: '/' + argv.i,

    method: 'GET',

    headers: {

        'accept': 'text/html,application/json,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',

        'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.86 Safari/537.36',

        'Host': 'www.facebook.com',

        'Connection': 'Keep-Alive',

        'Accept-Language': 'en-GB,en-US;q=0.8,en;q=0.6'

    }

};

const folderName = './Image/';

mkdirp(folderName, err => {
    if (err) {
        console.error(err);
        process.exit(1);
    } else {
        console.log('Direcotry Created');
    }
});

if (argv.i) {
    const getUserID = https.request(userID, res => {
        if (res.statusCode === 200) {
            console.log('user found');
        } else {
            console.log('not done!');

            process.exit(1);
        }

        let storeData = '';

        res.setEncoding('utf8');

        res.on('data', d => {

            storeData += d;

        });

        res.on('end', () => {

            const matchPattern = new RegExp(/entity_id":"\d*/);

            const arrMatches = storeData.match(matchPattern);

            if (arrMatches && arrMatches[0]) {
                const getID = arrMatches[0].replace('entity_id":"', '');

                const getImageIn = fs.createWriteStream(folderName + argv.n + '.jpg');
                http.get('http://graph.facebook.com/' + getID +'/picture?width=1600', res => {
                        res.pipe(getImageIn);
                        console.log('image saved');
                    }).on('error', err => {
                    console.error(err);
                    process.exit(1);
                });
            } else {
                process.exit(1);
            }
        });
    });
    getUserID.end();
}
<commit_msg>tabs | downs<commit_after>#!/usr/bin/env node

'use strict';

const http = require('follow-redirects').http;

const https = require('follow-redirects').https;

const fs = require('fs');

const mkdirp = require('mkdirp');

const colors = require('colors/safe');

const argv = require('yargs')

.usage(colors.cyan.bold('\nUsage : $0 -u <command> [info] <command> [file]'))

.command('u', colors.cyan.bold('❱ ') + 'facebook user\'s username')

.command('i', colors.cyan.bold('❱ ') + 'facebook user\'s user-id')

.demand(['n'])

.describe('n', colors.cyan.bold('❱ ') + 'save image as')

.argv;

const updateNotifier = require('update-notifier');

const pkg = require('./package.json');

updateNotifier({pkg}).notify();

const userID = {
	hostname: 'www.facebook.com',

	port: 443,

	path: '/' + argv.i,

	method: 'GET',

	headers: {
		'accept': 'text/html,application/json,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',

		'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.86 Safari/537.36',

		'Host': 'www.facebook.com',

		'Connection': 'Keep-Alive',

		'Accept-Language': 'en-GB,en-US;q=0.8,en;q=0.6'
	}
};

const folderName = './Image/';

mkdirp(folderName, err => {
	if (err) {
		console.error(err);

		process.exit(1);
	} else {
		console.log('Direcotry Created');
	}
});

if (argv.i) {
	const getUserID = https.request(userID, res => {
		if (res.statusCode === 200) {
			console.log('user found');
		} else {
			console.log('not done!');

			process.exit(1);
		}

		let storeData = '';

		res.setEncoding('utf8');

		res.on('data', d => {
			storeData += d;
		});

		res.on('end', () => {
			const matchPattern = new RegExp(/entity_id":"\d*/);

			const arrMatches = storeData.match(matchPattern);

			if (arrMatches && arrMatches[0]) {
				const getID = arrMatches[0].replace('entity_id":"', '');

				const getImageIn = fs.createWriteStream(folderName + argv.n + '.jpg');

				http.get('http://graph.facebook.com/' + getID + '/picture?width=1600', res => {
					res.pipe(getImageIn);

					console.log('image saved');
				}).on('error', err => {
					console.error(err);

					process.exit(1);
				});
			} else {
				process.exit(1);
			}
		});
	});
	getUserID.end();
}

if (argv.u) {
	const getImageIn = fs.createWriteStream(folderName + argv.n + '.jpg');

	http.get('http://graph.facebook.com/' + argv.u + '/picture?width=1600', res => {
		res.pipe(getImageIn);

		console.log('image saved');
	}).on('error', err => {
		console.error(err);

		process.exit(1);
	});
} else {
	process.exit(1);
}
<|endoftext|>


<commit_before>'use strict'
module.exports = npa
module.exports.resolve = resolve
module.exports.Result = Result

let url
let HostedGit
let semver
let path
let validatePackageName
let osenv

const isWindows = process.platform === 'win32' || global.FAKE_WINDOWS
const hasSlashes = isWindows ? /\\|[/]/ : /[/]/
const isURL = /^(?:git[+])?[a-z]+:/i
const isFilename = /[.](?:tgz|tar.gz|tar)$/i

function npa (arg, where) {
  let name
  let spec
  const nameEndsAt = arg[0] === '@' ? arg.slice(1).indexOf('@') + 1 : arg.indexOf('@')
  const namePart = nameEndsAt > 0 ? arg.slice(0, nameEndsAt) : arg
  if (isURL.test(arg)) {
    spec = arg
  } else if (namePart[0] !== '@' && (hasSlashes.test(namePart) || isFilename.test(namePart))) {
    spec = arg
  } else if (nameEndsAt > 0) {
    name = namePart
    spec = arg.slice(nameEndsAt + 1)
  } else {
    if (!validatePackageName) validatePackageName = require('validate-npm-package-name')
    const valid = validatePackageName(arg)
    if (valid.validForOldPackages) {
      name = arg
    } else {
      spec = arg
    }
  }
  return resolve(name, spec, where, arg)
}

const isFilespec = isWindows ? /^(?:[.]|~[/]|[/\\]|[a-zA-Z]:)/ : /^(?:[.]|~[/]|[/]|[a-zA-Z]:)/

function resolve (name, spec, where, arg) {
  const res = new Result({
    raw: arg,
    name: name,
    rawSpec: spec,
    fromArgument: arg != null
  })

  if (name) res.setName(name)

  if (spec && (isFilespec.test(spec) || /^file:/i.test(spec))) {
    return fromFile(res, where)
  }
  if (!HostedGit) HostedGit = require('hosted-git-info')
  const hosted = HostedGit.fromUrl(spec, {noGitPlus: true, noCommittish: true})
  if (hosted) {
    return fromHostedGit(res, hosted)
  } else if (spec && isURL.test(spec)) {
    return fromURL(res)
  } else if (spec && (hasSlashes.test(spec) || isFilename.test(spec))) {
    return fromFile(res, where)
  } else {
    return fromRegistry(res)
  }
}

function invalidPackageName (name, valid) {
  const err = new Error(`Invalid package name "${name}": ${valid.errors.join('; ')}`)
  err.code = 'EINVALIDPACKAGENAME'
  return err
}
function invalidTagName (name) {
  const err = new Error(`Invalid tag name "${name}": Tags may not have any characters that encodeURIComponent encodes.`)
  err.code = 'EINVALIDTAGNAME'
  return err
}

function Result (opts) {
  this.type = opts.type
  this.registry = opts.registry
  this.where = opts.where
  if (opts.raw == null) {
    this.raw = opts.name ? opts.name + '@' + opts.rawSpec : opts.rawSpec
  } else {
    this.raw = opts.raw
  }
  this.name = undefined
  this.escapedName = undefined
  this.scope = undefined
  this.rawSpec = opts.rawSpec == null ? '' : opts.rawSpec
  this.saveSpec = opts.saveSpec
  this.fetchSpec = opts.fetchSpec
  if (opts.name) this.setName(opts.name)
  this.gitRange = opts.gitRange
  this.gitCommittish = opts.gitCommittish
  this.hosted = opts.hosted
}
Result.prototype = {}

Result.prototype.setName = function (name) {
  if (!validatePackageName) validatePackageName = require('validate-npm-package-name')
  const valid = validatePackageName(name)
  if (!valid.validForOldPackages) {
    throw invalidPackageName(name, valid)
  }
  this.name = name
  this.scope = name[0] === '@' ? name.slice(0, name.indexOf('/')) : undefined
  // scoped packages in couch must have slash url-encoded, e.g. @foo%2Fbar
  this.escapedName = name.replace('/', '%2f')
  return this
}

Result.prototype.toJSON = function () {
  const result = Object.assign({}, this)
  delete result.hosted
  return result
}

function setGitCommittish (res, committish) {
  if (committish != null && committish.length >= 7 && committish.slice(0, 7) === 'semver:') {
    res.gitRange = decodeURIComponent(committish.slice(7))
    res.gitCommittish = null
  } else if (committish == null || committish === '') {
    res.gitCommittish = 'master'
  } else {
    res.gitCommittish = committish
  }
  return res
}

const isAbsolutePath = /^[/]|^[A-Za-z]:/

function resolvePath (where, spec) {
  if (isAbsolutePath.test(spec)) return spec
  if (!path) path = require('path')
  return path.resolve(where, spec)
}

function isAbsolute (dir) {
  if (dir[0] === '/') return true
  if (/^[A-Za-z]:/.test(dir)) return true
  return false
}

function fromFile (res, where) {
  if (!where) where = process.cwd()
  res.type = isFilename.test(res.rawSpec) ? 'file' : 'directory'
  res.where = where

  const spec = res.rawSpec.replace(/\\/g, '/')
    .replace(/^file:[/]*([A-Za-z]:)/, '$1') // drive name paths on windows
    .replace(/^file:(?:[/]*([~./]))?/, '$1')
  if (/^~[/]/.test(spec)) {
    // this is needed for windows and for file:~/foo/bar
    if (!osenv) osenv = require('osenv')
    res.fetchSpec = resolvePath(osenv.home(), spec.slice(2))
    res.saveSpec = 'file:' + spec
  } else {
    res.fetchSpec = resolvePath(where, spec)
    if (isAbsolute(spec)) {
      res.saveSpec = 'file:' + spec
    } else {
      if (!path) path = require('path')
      res.saveSpec = 'file:' + path.relative(where, res.fetchSpec)
    }
  }
  return res
}

function fromHostedGit (res, hosted) {
  res.type = 'git'
  res.hosted = hosted
  res.saveSpec = hosted.toString({noGitPlus: false, noCommittish: false})
  res.fetchSpec = hosted.getDefaultRepresentation() === 'shortcut' ? null : hosted.toString()
  return setGitCommittish(res, hosted.committish)
}

function unsupportedURLType (protocol, spec) {
  const err = new Error(`Unsupported URL Type "${protocol}": ${spec}`)
  err.code = 'EUNSUPPORTEDPROTOCOL'
  return err
}

function fromURL (res) {
  if (!url) url = require('url')
  const urlparse = url.parse(res.rawSpec)
  res.saveSpec = res.rawSpec
  // check the protocol, and then see if it's git or not
  switch (urlparse.protocol) {
    case 'git:':
    case 'git+http:':
    case 'git+https:':
    case 'git+rsync:':
    case 'git+ftp:':
    case 'git+ssh:':
    case 'git+file:':
      res.type = 'git'
      setGitCommittish(res, urlparse.hash != null ? urlparse.hash.slice(1) : '')
      urlparse.protocol = urlparse.protocol.replace(/^git[+]/, '')
      delete urlparse.hash
      res.fetchSpec = url.format(urlparse)
      break

    case 'http:':
    case 'https:':
      res.type = 'remote'
      res.fetchSpec = res.saveSpec
      break

    default:
      throw unsupportedURLType(urlparse.protocol, res.rawSpec)
  }

  return res
}

function fromRegistry (res) {
  res.registry = true
  const spec = res.rawSpec === '' ? 'latest' : res.rawSpec
  // no save spec for registry components as we save based on the fetched
  // version, not on the argument so this can't compute that.
  res.saveSpec = null
  res.fetchSpec = spec
  if (!semver) semver = require('semver')
  const version = semver.valid(spec, true)
  const range = semver.validRange(spec, true)
  if (version) {
    res.type = 'version'
  } else if (range) {
    res.type = 'range'
  } else {
    if (encodeURIComponent(spec) !== spec) {
      throw invalidTagName(spec)
    }
    res.type = 'tag'
  }
  return res
}
<commit_msg>src: Add toString method<commit_after>'use strict'
module.exports = npa
module.exports.resolve = resolve
module.exports.Result = Result

let url
let HostedGit
let semver
let path
let validatePackageName
let osenv

const isWindows = process.platform === 'win32' || global.FAKE_WINDOWS
const hasSlashes = isWindows ? /\\|[/]/ : /[/]/
const isURL = /^(?:git[+])?[a-z]+:/i
const isFilename = /[.](?:tgz|tar.gz|tar)$/i

function npa (arg, where) {
  let name
  let spec
  const nameEndsAt = arg[0] === '@' ? arg.slice(1).indexOf('@') + 1 : arg.indexOf('@')
  const namePart = nameEndsAt > 0 ? arg.slice(0, nameEndsAt) : arg
  if (isURL.test(arg)) {
    spec = arg
  } else if (namePart[0] !== '@' && (hasSlashes.test(namePart) || isFilename.test(namePart))) {
    spec = arg
  } else if (nameEndsAt > 0) {
    name = namePart
    spec = arg.slice(nameEndsAt + 1)
  } else {
    if (!validatePackageName) validatePackageName = require('validate-npm-package-name')
    const valid = validatePackageName(arg)
    if (valid.validForOldPackages) {
      name = arg
    } else {
      spec = arg
    }
  }
  return resolve(name, spec, where, arg)
}

const isFilespec = isWindows ? /^(?:[.]|~[/]|[/\\]|[a-zA-Z]:)/ : /^(?:[.]|~[/]|[/]|[a-zA-Z]:)/

function resolve (name, spec, where, arg) {
  const res = new Result({
    raw: arg,
    name: name,
    rawSpec: spec,
    fromArgument: arg != null
  })

  if (name) res.setName(name)

  if (spec && (isFilespec.test(spec) || /^file:/i.test(spec))) {
    return fromFile(res, where)
  }
  if (!HostedGit) HostedGit = require('hosted-git-info')
  const hosted = HostedGit.fromUrl(spec, {noGitPlus: true, noCommittish: true})
  if (hosted) {
    return fromHostedGit(res, hosted)
  } else if (spec && isURL.test(spec)) {
    return fromURL(res)
  } else if (spec && (hasSlashes.test(spec) || isFilename.test(spec))) {
    return fromFile(res, where)
  } else {
    return fromRegistry(res)
  }
}

function invalidPackageName (name, valid) {
  const err = new Error(`Invalid package name "${name}": ${valid.errors.join('; ')}`)
  err.code = 'EINVALIDPACKAGENAME'
  return err
}
function invalidTagName (name) {
  const err = new Error(`Invalid tag name "${name}": Tags may not have any characters that encodeURIComponent encodes.`)
  err.code = 'EINVALIDTAGNAME'
  return err
}

function Result (opts) {
  this.type = opts.type
  this.registry = opts.registry
  this.where = opts.where
  if (opts.raw == null) {
    this.raw = opts.name ? opts.name + '@' + opts.rawSpec : opts.rawSpec
  } else {
    this.raw = opts.raw
  }
  this.name = undefined
  this.escapedName = undefined
  this.scope = undefined
  this.rawSpec = opts.rawSpec == null ? '' : opts.rawSpec
  this.saveSpec = opts.saveSpec
  this.fetchSpec = opts.fetchSpec
  if (opts.name) this.setName(opts.name)
  this.gitRange = opts.gitRange
  this.gitCommittish = opts.gitCommittish
  this.hosted = opts.hosted
}
Result.prototype = {}

Result.prototype.setName = function (name) {
  if (!validatePackageName) validatePackageName = require('validate-npm-package-name')
  const valid = validatePackageName(name)
  if (!valid.validForOldPackages) {
    throw invalidPackageName(name, valid)
  }
  this.name = name
  this.scope = name[0] === '@' ? name.slice(0, name.indexOf('/')) : undefined
  // scoped packages in couch must have slash url-encoded, e.g. @foo%2Fbar
  this.escapedName = name.replace('/', '%2f')
  return this
}

Result.prototype.toString = function () {
  const full = []
  if (this.name != null && this.name !== '') full.push(this.name)
  const spec = this.saveSpec || this.fetchSpec || this.rawSpec
  if (spec != null && spec !== '') full.push(spec)
  return full.length ? full.join('@') : this.raw
}

Result.prototype.toJSON = function () {
  const result = Object.assign({}, this)
  delete result.hosted
  return result
}

function setGitCommittish (res, committish) {
  if (committish != null && committish.length >= 7 && committish.slice(0, 7) === 'semver:') {
    res.gitRange = decodeURIComponent(committish.slice(7))
    res.gitCommittish = null
  } else if (committish == null || committish === '') {
    res.gitCommittish = 'master'
  } else {
    res.gitCommittish = committish
  }
  return res
}

const isAbsolutePath = /^[/]|^[A-Za-z]:/

function resolvePath (where, spec) {
  if (isAbsolutePath.test(spec)) return spec
  if (!path) path = require('path')
  return path.resolve(where, spec)
}

function isAbsolute (dir) {
  if (dir[0] === '/') return true
  if (/^[A-Za-z]:/.test(dir)) return true
  return false
}

function fromFile (res, where) {
  if (!where) where = process.cwd()
  res.type = isFilename.test(res.rawSpec) ? 'file' : 'directory'
  res.where = where

  const spec = res.rawSpec.replace(/\\/g, '/')
    .replace(/^file:[/]*([A-Za-z]:)/, '$1') // drive name paths on windows
    .replace(/^file:(?:[/]*([~./]))?/, '$1')
  if (/^~[/]/.test(spec)) {
    // this is needed for windows and for file:~/foo/bar
    if (!osenv) osenv = require('osenv')
    res.fetchSpec = resolvePath(osenv.home(), spec.slice(2))
    res.saveSpec = 'file:' + spec
  } else {
    res.fetchSpec = resolvePath(where, spec)
    if (isAbsolute(spec)) {
      res.saveSpec = 'file:' + spec
    } else {
      if (!path) path = require('path')
      res.saveSpec = 'file:' + path.relative(where, res.fetchSpec)
    }
  }
  return res
}

function fromHostedGit (res, hosted) {
  res.type = 'git'
  res.hosted = hosted
  res.saveSpec = hosted.toString({noGitPlus: false, noCommittish: false})
  res.fetchSpec = hosted.getDefaultRepresentation() === 'shortcut' ? null : hosted.toString()
  return setGitCommittish(res, hosted.committish)
}

function unsupportedURLType (protocol, spec) {
  const err = new Error(`Unsupported URL Type "${protocol}": ${spec}`)
  err.code = 'EUNSUPPORTEDPROTOCOL'
  return err
}

function fromURL (res) {
  if (!url) url = require('url')
  const urlparse = url.parse(res.rawSpec)
  res.saveSpec = res.rawSpec
  // check the protocol, and then see if it's git or not
  switch (urlparse.protocol) {
    case 'git:':
    case 'git+http:':
    case 'git+https:':
    case 'git+rsync:':
    case 'git+ftp:':
    case 'git+ssh:':
    case 'git+file:':
      res.type = 'git'
      setGitCommittish(res, urlparse.hash != null ? urlparse.hash.slice(1) : '')
      urlparse.protocol = urlparse.protocol.replace(/^git[+]/, '')
      delete urlparse.hash
      res.fetchSpec = url.format(urlparse)
      break

    case 'http:':
    case 'https:':
      res.type = 'remote'
      res.fetchSpec = res.saveSpec
      break

    default:
      throw unsupportedURLType(urlparse.protocol, res.rawSpec)
  }

  return res
}

function fromRegistry (res) {
  res.registry = true
  const spec = res.rawSpec === '' ? 'latest' : res.rawSpec
  // no save spec for registry components as we save based on the fetched
  // version, not on the argument so this can't compute that.
  res.saveSpec = null
  res.fetchSpec = spec
  if (!semver) semver = require('semver')
  const version = semver.valid(spec, true)
  const range = semver.validRange(spec, true)
  if (version) {
    res.type = 'version'
  } else if (range) {
    res.type = 'range'
  } else {
    if (encodeURIComponent(spec) !== spec) {
      throw invalidTagName(spec)
    }
    res.type = 'tag'
  }
  return res
}
<|endoftext|>


<commit_before>
process.title = "npm"

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

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

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"
              , "find" : "search"
              , "s" : "search"
              , "se" : "search"
              , "author" : "owner"
              , "home" : "docs"
              }

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

              , "rebuild"
              , "link"

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

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

              , "test"
              , "stop"
              , "start"
              , "restart"
              , "run-script"
              , "completion"
              ]
  , plumbing = [ "build"
               , "unbuild"
               , "xmas"
               ]
  , 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)
    }
    if (commandCache[a]) return commandCache[a]
    var cmd = require(__dirname+"/lib/"+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 !== process.execPath) {
      log.verbose("node symlink", node)
      process.execPath = node
      process.installPrefix = path.resolve(node, "..", "..")
    }

    // look up configs
    ini.resolveConfigs(conf, function (er) {
      if (er) return cb(er)

      var n = 2
        , errState

      loadPrefix(npm, conf, next)
      loadUid(npm, conf, next)

      function next (er) {
        if (errState) return
        if (er) return cb(errState = er)
        if (-- n <= 0) return cb()
      }
    })
  })
}

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

  findPrefix(p, function (er, p) {
    Object.defineProperty(npm, "prefix",
      { get : function () { return p }
      , set : function (r) { return p = r }
      , enumerable : true
      })
    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 cb()
}

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, "dir",
  { get : function () {
      if (npm.config.get("global")) {
        return path.resolve(npm.prefix, "lib", "node_modules")
      } else {
        return path.resolve(npm.prefix, "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.js")
}
<commit_msg>Case-insensitively compare execPath<commit_after>
process.title = "npm"

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

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

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"
              , "find" : "search"
              , "s" : "search"
              , "se" : "search"
              , "author" : "owner"
              , "home" : "docs"
              }

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

              , "rebuild"
              , "link"

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

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

              , "test"
              , "stop"
              , "start"
              , "restart"
              , "run-script"
              , "completion"
              ]
  , plumbing = [ "build"
               , "unbuild"
               , "xmas"
               ]
  , 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)
    }
    if (commandCache[a]) return commandCache[a]
    var cmd = require(__dirname+"/lib/"+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
    ini.resolveConfigs(conf, function (er) {
      if (er) return cb(er)

      var n = 2
        , errState

      loadPrefix(npm, conf, next)
      loadUid(npm, conf, next)

      function next (er) {
        if (errState) return
        if (er) return cb(errState = er)
        if (-- n <= 0) return cb()
      }
    })
  })
}

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

  findPrefix(p, function (er, p) {
    Object.defineProperty(npm, "prefix",
      { get : function () { return p }
      , set : function (r) { return p = r }
      , enumerable : true
      })
    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 cb()
}

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, "dir",
  { get : function () {
      if (npm.config.get("global")) {
        return path.resolve(npm.prefix, "lib", "node_modules")
      } else {
        return path.resolve(npm.prefix, "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.js")
}
<|endoftext|>


<commit_before>/**
 *
 * NUT adapter
 *
 * Adapter loading NUT data from an UPS
 *
 */

"use strict";

var utils = require(__dirname + '/lib/utils'); // Get common adapter utils
var Nut   = require('node-nut');

var adapter = utils.adapter({
  name: 'nut',
  ready: function () {
    //oNut = new Nut(3493, 'localhost');
    var oNut = new Nut(adapter.config.host_port, adapter.config.host_ip);

    oNut.on('error', function(err) {
      adapter.log.error('Error happend: ' + err);
    });

    oNut.on('close', function() {
      adapter.log.debug('NUT Connection closed. Done.');
      setTimeout(function () {
        adapter.stop();
      }, 2000);
    });

    oNut.on('ready', function() {
      adapter.log.debug('NUT Connection ready');
      var self = this;
      this.GetUPSVars(adapter.config.ups_name,function(varlist) {
        adapter.log.debug('Got values, start setting them');
        storeNutData(varlist);
        self.close();
      });
    });

    oNut.start();
  }
});

adapter.on('stateChange', function (id, state) {
    adapter.log.debug('stateChange ' + id + ' ' + JSON.stringify(state));

    // you can use the ack flag to detect if state is command(false) or status(true)
    if (!state.ack) {
        adapter.log.info('ack is not set!');
    }
});

function storeNutData(varlist) {
  var last='';
  var current='';
  var index=0;
  var stateName='';

  for (var key in varlist) {
    index=key.indexOf('.');
    if (index > 0) {
      current=key.substring(0,index);
    }
    else {
      current='';
      last='';
      index=-1;
    }
    if (((last=='') || (last!=current)) && (current!='')) {
      adapter.log.debug('Create Channel '+current);
      adapter.setObjectNotExists(current, {
          type: 'channel',
          common: {name: current},
          native: {}
      });
    }
    stateName=current+'.'+key.substring(index+1).replace(/\./g,'-');
    adapter.log.debug('Create State '+stateName);
    if (stateName=='battery.charge') {
      adapter.setObjectNotExists(stateName, {
          type: 'state',
          common: {name: stateName, type: 'number', role: 'value.battery', read: true, write: false},
          native: {id: stateName}
      });
    }
    else {
      adapter.setObjectNotExists(stateName, {
          type: 'state',
          common: {name: stateName, type: 'string', read: true, write: false},
          native: {id: stateName}
      });
    }
    adapter.log.debug('Set State '+stateName+' = '+varlist[key]);
    adapter.setState(stateName, {ack: true, val: varlist[key]});
    last=current;
  }

  // Command Datapoint to be used with "NOIFY EVENTS" and upsmon
  /*
ONLINE

    The UPS is back on line.
ONBATT

    The UPS is on battery.
LOWBATT

    The UPS battery is low (as determined by the driver).
FSD

    The UPS has been commanded into the "forced shutdown" mode.
COMMOK

    Communication with the UPS has been established.
COMMBAD

    Communication with the UPS was just lost.
SHUTDOWN

    The local system is being shut down.
REPLBATT

    The UPS needs to have its battery replaced.
NOCOMM

    The UPS can’t be contacted for monitoring.
*/
  adapter.setObjectNotExists(stateName, {
      type: 'state',
      common: {
        name: 'upsmon_event',
        type: 'string',
        read: true,
        write: true,
        def:""
      },
      native: {id: 'upsmon_event'}
  });
  adapter.subscribeStates('upsmon_event');

  adapter.log.debug('Create Channel status');
  adapter.setObjectNotExists(current, {
      type: 'channel',
      common: {name: 'status'},
      native: {}
  });
  var severityVal = 4;
  adapter.setObjectNotExists(stateName, {
      type: 'state',
      common: {
        name: 'status.severity',
        role: 'indicator',
        type: 'number',
        read: true,
        write: false,
        def:4,
        states: '0:idle;1:operating;2:operating_critical;3:action_needed;4:unknown'
      },
      native: {id: 'status.severity'}
  });
  if (varlist['ups.status']) {
    var statusMap = {
              'OL':{name:'online',severity:'idle'},
              'OB':{name:'onbattery',severity:'operating'},
              'LB':{name:'lowbattery',severity:'operating_critical'},
              'HB':{name:'highbattery',severity:'operating_critical'},
              'RB':{name:'replacebattery',severity:'action_needed'},
              'CHRG':{name:'charging',severity:'idle'},
              'DISCHRG':{name:'discharging',severity:'operating'},
              'BYPASS':{name:'bypass',severity:'action_needed'},
              'CAL':{name:'calibration',severity:'operating'},
              'OFF':{name:'offline',severity:'action_needed'},
              'OVER':{name:'overload',severity:'action_needed'},
              'TRIM':{name:'trimming',severity:'operating'},
              'BOOST':{name:'boosting',severity:'operating'},
              'FSD':{name:'shutdown',severity:'operating_critical'}
            };
    var severity = {
              'idle':false,
              'operating':false,
              'operating_critical':false,
              'action_needed':false
            };
    var checker=' '+varlist['ups.status']+' ';
    for (var idx in statusMap) {
      if (statusMap.hasOwnProperty(idx)) {
        var found=(checker.indexOf(idx)>-1);
        stateName='status.'+statusMap[idx]['name'];
        adapter.log.debug('Create State '+stateName);
        adapter.setObjectNotExists(stateName, {
            type: 'state',
            common: {name: stateName, type: 'boolean', read: true, write: false},
            native: {id: stateName}
        });
        adapter.log.debug('Set State '+stateName+' = '+found);
        adapter.setState(stateName, {ack: true, val: found});
        if (found) {
          severity[statusMap[idx]['severity']]=true;
          adapter.log.debug('Severity Flag '+statusMap[idx]['severity']+'=true');
        }
      }
    }
    if (severity['operating_critical']) severityVal=2;
      else if (severity['action_needed']) severityVal=3;
      else if (severity['operating']) severityVal=1
      else if (severity['idle']) severityVal=0;
  }
  adapter.log.debug('Set State status.severity = '+severityVal);
  adapter.setState('status.severity', {ack: true, val: severityVal});

  adapter.log.info('All Nut values set');
}
<commit_msg>fixed state creation<commit_after>/**
 *
 * NUT adapter
 *
 * Adapter loading NUT data from an UPS
 *
 */

"use strict";

var utils = require(__dirname + '/lib/utils'); // Get common adapter utils
var Nut   = require('node-nut');

var adapter = utils.adapter({
  name: 'nut',
  ready: function () {
    //oNut = new Nut(3493, 'localhost');
    var oNut = new Nut(adapter.config.host_port, adapter.config.host_ip);

    oNut.on('error', function(err) {
      adapter.log.error('Error happend: ' + err);
    });

    oNut.on('close', function() {
      adapter.log.debug('NUT Connection closed. Done.');
      setTimeout(function () {
        adapter.stop();
      }, 2000);
    });

    oNut.on('ready', function() {
      adapter.log.debug('NUT Connection ready');
      var self = this;
      this.GetUPSVars(adapter.config.ups_name,function(varlist) {
        adapter.log.debug('Got values, start setting them');
        storeNutData(varlist);
        self.close();
      });
    });

    oNut.start();
  }
});

adapter.on('stateChange', function (id, state) {
    adapter.log.debug('stateChange ' + id + ' ' + JSON.stringify(state));

    // you can use the ack flag to detect if state is command(false) or status(true)
    if (!state.ack) {
        adapter.log.info('ack is not set!');
    }
});

function storeNutData(varlist) {
  var last='';
  var current='';
  var index=0;
  var stateName='';

  for (var key in varlist) {
    index=key.indexOf('.');
    if (index > 0) {
      current=key.substring(0,index);
    }
    else {
      current='';
      last='';
      index=-1;
    }
    if (((last=='') || (last!=current)) && (current!='')) {
      adapter.log.debug('Create Channel '+current);
      adapter.setObjectNotExists(current, {
          type: 'channel',
          common: {name: current},
          native: {}
      });
    }
    stateName=current+'.'+key.substring(index+1).replace(/\./g,'-');
    adapter.log.debug('Create State '+stateName);
    if (stateName=='battery.charge') {
      adapter.setObjectNotExists(stateName, {
          type: 'state',
          common: {name: stateName, type: 'number', role: 'value.battery', read: true, write: false},
          native: {id: stateName}
      });
    }
    else {
      adapter.setObjectNotExists(stateName, {
          type: 'state',
          common: {name: stateName, type: 'string', read: true, write: false},
          native: {id: stateName}
      });
    }
    adapter.log.debug('Set State '+stateName+' = '+varlist[key]);
    adapter.setState(stateName, {ack: true, val: varlist[key]});
    last=current;
  }

  // Command Datapoint to be used with "NOIFY EVENTS" and upsmon
  /*
ONLINE

    The UPS is back on line.
ONBATT

    The UPS is on battery.
LOWBATT

    The UPS battery is low (as determined by the driver).
FSD

    The UPS has been commanded into the "forced shutdown" mode.
COMMOK

    Communication with the UPS has been established.
COMMBAD

    Communication with the UPS was just lost.
SHUTDOWN

    The local system is being shut down.
REPLBATT

    The UPS needs to have its battery replaced.
NOCOMM

    The UPS can’t be contacted for monitoring.
*/
  adapter.setObjectNotExists('upsmon_event', {
      type: 'state',
      common: {
        name: 'upsmon_event',
        type: 'string',
        read: true,
        write: true,
        def:""
      },
      native: {id: 'upsmon_event'}
  });
  adapter.subscribeStates('upsmon_event');

  adapter.log.debug('Create Channel status');
  adapter.setObjectNotExists('status', {
      type: 'channel',
      common: {name: 'status'},
      native: {}
  });
  var severityVal = 4;
  adapter.setObjectNotExists('status.severity', {
      type: 'state',
      common: {
        name: 'status.severity',
        role: 'indicator',
        type: 'number',
        read: true,
        write: false,
        def:4,
        states: '0:idle;1:operating;2:operating_critical;3:action_needed;4:unknown'
      },
      native: {id: 'status.severity'}
  });
  if (varlist['ups.status']) {
    var statusMap = {
              'OL':{name:'online',severity:'idle'},
              'OB':{name:'onbattery',severity:'operating'},
              'LB':{name:'lowbattery',severity:'operating_critical'},
              'HB':{name:'highbattery',severity:'operating_critical'},
              'RB':{name:'replacebattery',severity:'action_needed'},
              'CHRG':{name:'charging',severity:'idle'},
              'DISCHRG':{name:'discharging',severity:'operating'},
              'BYPASS':{name:'bypass',severity:'action_needed'},
              'CAL':{name:'calibration',severity:'operating'},
              'OFF':{name:'offline',severity:'action_needed'},
              'OVER':{name:'overload',severity:'action_needed'},
              'TRIM':{name:'trimming',severity:'operating'},
              'BOOST':{name:'boosting',severity:'operating'},
              'FSD':{name:'shutdown',severity:'operating_critical'}
            };
    var severity = {
              'idle':false,
              'operating':false,
              'operating_critical':false,
              'action_needed':false
            };
    var checker=' '+varlist['ups.status']+' ';
    for (var idx in statusMap) {
      if (statusMap.hasOwnProperty(idx)) {
        var found=(checker.indexOf(idx)>-1);
        stateName='status.'+statusMap[idx]['name'];
        adapter.log.debug('Create State '+stateName);
        adapter.setObjectNotExists(stateName, {
            type: 'state',
            common: {name: stateName, type: 'boolean', read: true, write: false},
            native: {id: stateName}
        });
        adapter.log.debug('Set State '+stateName+' = '+found);
        adapter.setState(stateName, {ack: true, val: found});
        if (found) {
          severity[statusMap[idx]['severity']]=true;
          adapter.log.debug('Severity Flag '+statusMap[idx]['severity']+'=true');
        }
      }
    }
    if (severity['operating_critical']) severityVal=2;
      else if (severity['action_needed']) severityVal=3;
      else if (severity['operating']) severityVal=1
      else if (severity['idle']) severityVal=0;
  }
  adapter.log.debug('Set State status.severity = '+severityVal);
  adapter.setState('status.severity', {ack: true, val: severityVal});

  adapter.log.info('All Nut values set');
}
<|endoftext|>


<commit_before>function log(a){console.log(a)}log("one.js");
<commit_msg>Remove test output file that was mistakenly committed.<commit_after><|endoftext|>


<commit_before>const Promise = require('bluebird');
const MessageSkeleton = require('./messageSkeleton')

function mkOrderId(id, chId) {
    return (id + ':' + chId);
}

function invalidCmd(msg) {
    msg.text = ':warning: Invalid command. :warning:\n \
    Take a look at our help. :arrow_right:  `/food4me help`';
    return msg;
}

function help(msg) {
    msg.text = 'Start new order: `/food4me (start|create) {orderName}`\n \
Get info about existing order: `/food4me get {orderName}`\n \
List existing orders: `/food4me get {orderName}`\n \
Close ongoing order: `/food4me (stop|kill|close) {orderName}`\n \
Join order: `/food4me (join|set) {orderName} {your text}`\n \
Update your order item: `/food4me (update|set) {orderName} {your text}`\n \
Remove your order item: `/food4me (rm|cancel) {orderName}`\n \
Print this help: `/food4me (h|help|halp|man) {orderName}`';
    return msg;
}

function internalError(payload, msg) {
    msg.icon_emoji = ':frowning:';
    msg.text = 'Pssssst... ' + payload.user_name +
        '... There was a little accident... Dunno what happened exactly, \
        but I can\'t do what you have requested right now... :confused: I\'m pretty \
        sure those evil developers are in charge for this... :unamused:';
    return msg;
}

function getOrder(dbo, payload, words, msg) {
    var promise = new Promise(function(resolve, reject) {
        if (words.length < 2) {
            resolve(invalidCmd(msg));
            return;
        }
        const orderId = mkOrderId(words[1], payload.channel_id);
        dbo.getOrder(orderId)
        .then(obj => {
            if (obj) {
                msg.text = Object.keys(obj).reduce((prev, curr) => {
                    return prev + '\n*' + curr + '*:\n' + obj[curr];
                }, 'Items in *' + words[1] + '*:')
            } else {
                msg.text = ('Order *'+ words[1] +'* is empty os does not exists.');
            }
            resolve(msg);
        }).catch(() => resolve(internalError(payload, msg)));
    });
    return promise;
}

function list(dbo, payload, msg) {
    var promise = new Promise(function(resolve, reject) {
        const suffix = ':' + payload.channel_id;
        dbo.listOrdersWithSuffix(suffix)
        .then(list => {
            msg.text = list.reduce(elem => {
                const ord = elem.orderId.split(':')[1];
                const openStr = (elem.isOpen) ? 'open' : 'closed';
                return (ord + ': ' + openStr);
            }, 'Orders:');
        })
        .catch(() => resolve(internalError(payload, msg)));
    });
    return promise;
}

function startOrder(dbo, payload, words, msg) {
    var promise = new Promise(function(resolve, reject) {
        if (words.length < 2) {
            resolve(invalidCmd(msg));
            return;
        }
        const orderId = mkOrderId(words[1], payload.channel_id);
        dbo.createOrder(orderId)
        .then(() => {
            msg.response_type = 'in_channel';
            msg.text = 'Order session *' + words[1] + '* has been started.';
            resolve(msg);
        }).catch(err => {
            if (err === 'ALREADY_SET') {
                msg.text = 'Order *' + words[1] + '* has been already started.';
                resolve(msg);
            } else {
                resolve(internalError(payload, msg));
            }
        });
    });
    return promise;
}

function stopOrder(dbo, payload, words, msg) {
    var promise = new Promise(function(resolve, reject) {
        if (words.length < 2) {
            reject(invalidCmd(msg));
            return;
        }
        const orderId = mkOrderId(words[1], payload.channel_id)
        dbo.closeOrder(orderId)
        .then(() => {
            msg.response_type = 'in_channel';
            msg.text = 'Order *' + words[1] + '* has been closed.';
            resolve(msg);
        })
        .catch(err => {
            if (err === 'CLOSED_OR_NULL') {
                msg.text = 'Order *' + words[1] + '* has been already closed or not exists.';
                resolve(msg);
            } else {
                resolve(internalError(payload, msg));
            }
        });
    });
    return promise;
}

function addItem(dbo, payload, words, msg) {
    var promise = new Promise(function(resolve, reject) {
        if (words.length < 3) {
            resolve(invalidCmd(msg));
            return;
        }
        const orderId = mkOrderId(words[1], payload.channel_id)
        dbo.addItemToOrder(orderId, payload.user_name, words.slice(2).join(' '))
        .then(() => {
            msg.text = 'Your order has been recorded. :wink:';
            resolve(msg);
        })
        .catch(err => {
            if (err === 'CLOSED_OR_NULL') {
                msg.text = 'Order *' + words[1] + '* has been already closed or not exists.';
                resolve(msg);
            } else {
                resolve(internalError(payload, msg));
            }
        });
    });
    return promise;
}

function removeItem(dbo, payload, words, msg) {
    var promise = new Promise(function(resolve, reject) {
        if (words.length < 2) {
            reject(invalidCmd(msg));
            return;
        }
        const orderId = mkOrderId(words[1], payload.channel_id)
        dbo.removeItemFromOrder(orderId, payload.user_name)
        .then(() => {
            msg.text = 'Your item has been removed from order *' + words[1] + '*.';
            resolve(msg);
        }).catch(err => {
            if (err === 'CLOSED_OR_NULL') {
                msg.text = 'Order *' + words[1] + '* has been already closed or not exists.';
                resolve(msg);
            } else if (err === 'INVALID_ITEM') {
                msg.text = 'You haven\'t got any items in order *' + words[1] + '*.';
                resolve(msg);
            } else {
                resolve(internalError(payload, msg));
            }
        });
    });
    return promise;
}

module.exports = function(dbo, payload, words) {
    var msgSkeleton = new MessageSkeleton();
    return {
        getOrder: getOrder.bind({}, dbo, payload, words, msgSkeleton),
        list: list.bind({}, dbo, payload, msgSkeleton),
        startOrder: startOrder.bind({}, dbo, payload, words, msgSkeleton),
        stopOrder: stopOrder.bind({}, dbo, payload, words, msgSkeleton),
        addItem: addItem.bind({}, dbo, payload, words, msgSkeleton),
        removeItem: removeItem.bind({}, dbo, payload, words, msgSkeleton),
        invalidCmd: invalidCmd.bind({}, msgSkeleton),
        help: help.bind({}, msgSkeleton)
    }
};
<commit_msg>listing fix<commit_after>const Promise = require('bluebird');
const MessageSkeleton = require('./messageSkeleton')

function mkOrderId(id, chId) {
    return (id + ':' + chId);
}

function invalidCmd(msg) {
    msg.text = ':warning: Invalid command. :warning:\n \
    Take a look at our help. :arrow_right:  `/food4me help`';
    return msg;
}

function help(msg) {
    msg.text = 'Start new order: `/food4me (start|create) {orderName}`\n \
Get info about existing order: `/food4me get {orderName}`\n \
List existing orders: `/food4me get {orderName}`\n \
Close ongoing order: `/food4me (stop|kill|close) {orderName}`\n \
Join order: `/food4me (join|set) {orderName} {your text}`\n \
Update your order item: `/food4me (update|set) {orderName} {your text}`\n \
Remove your order item: `/food4me (rm|cancel) {orderName}`\n \
Print this help: `/food4me (h|help|halp|man) {orderName}`';
    return msg;
}

function internalError(payload, msg) {
    msg.icon_emoji = ':frowning:';
    msg.text = 'Pssssst... ' + payload.user_name +
        '... There was a little accident... Dunno what happened exactly, \
        but I can\'t do what you have requested right now... :confused: I\'m pretty \
        sure those evil developers are in charge for this... :unamused:';
    return msg;
}

function getOrder(dbo, payload, words, msg) {
    var promise = new Promise(function(resolve, reject) {
        if (words.length < 2) {
            resolve(invalidCmd(msg));
            return;
        }
        const orderId = mkOrderId(words[1], payload.channel_id);
        dbo.getOrder(orderId)
        .then(obj => {
            if (obj) {
                msg.text = Object.keys(obj).reduce((prev, curr) => {
                    return prev + '\n*' + curr + '*:\n' + obj[curr];
                }, 'Items in *' + words[1] + '*:')
            } else {
                msg.text = ('Order *'+ words[1] +'* is empty os does not exists.');
            }
            resolve(msg);
        }).catch(() => resolve(internalError(payload, msg)));
    });
    return promise;
}

function list(dbo, payload, msg) {
    var promise = new Promise(function(resolve, reject) {
        const suffix = ':' + payload.channel_id;
        dbo.listOrdersWithSuffix(suffix)
        .then(list => {
            msg.text = list.reduce(elem => {
                const ord = elem.orderId.split(':')[1];
                const openStr = (elem.isOpen) ? 'open' : 'closed';
                return (ord + ': ' + openStr);
            }, 'Orders:');
            resolve(msg);
        })
        .catch(() => resolve(internalError(payload, msg)));
    });
    return promise;
}

function startOrder(dbo, payload, words, msg) {
    var promise = new Promise(function(resolve, reject) {
        if (words.length < 2) {
            resolve(invalidCmd(msg));
            return;
        }
        const orderId = mkOrderId(words[1], payload.channel_id);
        dbo.createOrder(orderId)
        .then(() => {
            msg.response_type = 'in_channel';
            msg.text = 'Order session *' + words[1] + '* has been started.';
            resolve(msg);
        }).catch(err => {
            if (err === 'ALREADY_SET') {
                msg.text = 'Order *' + words[1] + '* has been already started.';
                resolve(msg);
            } else {
                resolve(internalError(payload, msg));
            }
        });
    });
    return promise;
}

function stopOrder(dbo, payload, words, msg) {
    var promise = new Promise(function(resolve, reject) {
        if (words.length < 2) {
            reject(invalidCmd(msg));
            return;
        }
        const orderId = mkOrderId(words[1], payload.channel_id)
        dbo.closeOrder(orderId)
        .then(() => {
            msg.response_type = 'in_channel';
            msg.text = 'Order *' + words[1] + '* has been closed.';
            resolve(msg);
        })
        .catch(err => {
            if (err === 'CLOSED_OR_NULL') {
                msg.text = 'Order *' + words[1] + '* has been already closed or not exists.';
                resolve(msg);
            } else {
                resolve(internalError(payload, msg));
            }
        });
    });
    return promise;
}

function addItem(dbo, payload, words, msg) {
    var promise = new Promise(function(resolve, reject) {
        if (words.length < 3) {
            resolve(invalidCmd(msg));
            return;
        }
        const orderId = mkOrderId(words[1], payload.channel_id)
        dbo.addItemToOrder(orderId, payload.user_name, words.slice(2).join(' '))
        .then(() => {
            msg.text = 'Your order has been recorded. :wink:';
            resolve(msg);
        })
        .catch(err => {
            if (err === 'CLOSED_OR_NULL') {
                msg.text = 'Order *' + words[1] + '* has been already closed or not exists.';
                resolve(msg);
            } else {
                resolve(internalError(payload, msg));
            }
        });
    });
    return promise;
}

function removeItem(dbo, payload, words, msg) {
    var promise = new Promise(function(resolve, reject) {
        if (words.length < 2) {
            reject(invalidCmd(msg));
            return;
        }
        const orderId = mkOrderId(words[1], payload.channel_id)
        dbo.removeItemFromOrder(orderId, payload.user_name)
        .then(() => {
            msg.text = 'Your item has been removed from order *' + words[1] + '*.';
            resolve(msg);
        }).catch(err => {
            if (err === 'CLOSED_OR_NULL') {
                msg.text = 'Order *' + words[1] + '* has been already closed or not exists.';
                resolve(msg);
            } else if (err === 'INVALID_ITEM') {
                msg.text = 'You haven\'t got any items in order *' + words[1] + '*.';
                resolve(msg);
            } else {
                resolve(internalError(payload, msg));
            }
        });
    });
    return promise;
}

module.exports = function(dbo, payload, words) {
    var msgSkeleton = new MessageSkeleton();
    return {
        getOrder: getOrder.bind({}, dbo, payload, words, msgSkeleton),
        list: list.bind({}, dbo, payload, msgSkeleton),
        startOrder: startOrder.bind({}, dbo, payload, words, msgSkeleton),
        stopOrder: stopOrder.bind({}, dbo, payload, words, msgSkeleton),
        addItem: addItem.bind({}, dbo, payload, words, msgSkeleton),
        removeItem: removeItem.bind({}, dbo, payload, words, msgSkeleton),
        invalidCmd: invalidCmd.bind({}, msgSkeleton),
        help: help.bind({}, msgSkeleton)
    }
};
<|endoftext|>


<commit_before>const request = require('supertest')
const app = require('./index')

const iso8601Regex = /\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d\.\d+([+-][0-2]\d:[0-5]\d|Z)/
const idRegex = /\d+/

jasmine.DEFAULT_TIMEOUT_INTERVAL = 20000

beforeAll(() => new Promise((resolve) => {
  setTimeout(() => {
    resolve()
  }, 1000)
}))

// TODO: [bug] test is not closing the program.
afterAll(() => {
  app.close()
})

test('pokemons.list', () => request(app).get('/pokemons').then((response) => {
  expect(response.body.length).toBe(0)
}))

test('pokemons.create', () => {
  const pikachu = {
    name: 'pikachu',
    price: 15.56,
    stock: 3
  }

  return request(app)
    .post('/pokemons')
    .type('Application/json')
    .send(pikachu)
    .expect(200)
    .then((response) => {
      expect(response.body).toMatchObject(pikachu)
    })
})

test('pokemons.create with invalid params', () => {
  const pikachu = {
    price: 'adsas',
    stock: '!#@!$'
  }

  return request(app)
    .post('/pokemons')
    .type('Application/json')
    .send(pikachu)
    .expect(400)
    .then((response) => {
      expect(response.body).toHaveProperty('errors')
      expect(response.body).toEqual(expect.objectContaining({
        status: 400,
        statusText: 'Bad Request',
        errors: [{
          field: 'name',
          location: 'body',
          messages: [
            '\"name\" is required'
          ],
          types: [
            'any.required'
          ]
        }, {
          field: 'price',
          location: 'body',
          messages: [
            '\"price\" must be a number'
          ],
          types: [
            'number.base'
          ]
        }, {
          field: 'stock',
          location: 'body',
          messages: [
            '\"stock\" must be a number'
          ],
          types: [
            'number.base'
          ]
        }]
      }))
    })
})

test('pokemons.list after create ', () => {
  const pokemons = [{
    id: expect.stringMatching(idRegex),
    name: 'pikachu',
    price: 15.56,
    stock: 3,
    createdAt: expect.stringMatching(iso8601Regex),
    updatedAt: expect.stringMatching(iso8601Regex)
  }]

  return request(app)
    .get('/pokemons')
    .expect(200)
    .then((response) => {
      expect(response.body.length).toBe(1)
      expect(response.body).toEqual(expect.arrayContaining(pokemons))
    })
})

test('pokemons.buy', () => {
  const pokemonToBuy = {
    name: 'pikachu',
    quantity: 2
  }

  return request(app)
    .post('/pokemons/buy')
    .type('Application/json')
    .send(pokemonToBuy)
    .expect(200)
    .then((response) => {
      expect(response.body).toHaveProperty('status', 'paid')
      expect(response.body).toHaveProperty('amount', 3112)
    })
})

test('pokemons.buy not found', () => {
  const pokemonToBuy = {
    name: 'bulbasaur',
    quantity: 3
  }

  return request(app)
    .post('/pokemons/buy')
    .type('Application/json')
    .send(pokemonToBuy)
    .expect(404)
    .then((response) => {
      expect(response.body).toHaveProperty('error')
      expect(response.body.error).toEqual(expect.stringContaining('not found'))
    })
})

test('pokemons.buy with invalid params', () => {
  const pokemonToBuy = {
    quantity: 2.15
  }

  return request(app)
    .post('/pokemons/buy')
    .type('Application/json')
    .send(pokemonToBuy)
    .expect(400)
    .then((response) => {
      expect(response.body).toHaveProperty('errors')
      expect(response.body).toEqual(expect.objectContaining({
        status: 400,
        statusText: 'Bad Request',
        errors: [{
          field: 'name',
          location: 'body',
          messages: [
            '\"name\" is required'
          ],
          types: [
            'any.required'
          ]
        }, {
          field: 'quantity',
          location: 'body',
          messages: [
            '\"quantity\" must be an integer'
          ],
          types: [
            'number.integer'
          ]
        }]
      }))
    })
})

test('pokemons.list after bought ', () => {
  const pokemons = [{
    id: expect.stringMatching(idRegex),
    name: 'pikachu',
    price: 15.56,
    stock: 1,
    createdAt: expect.stringMatching(iso8601Regex),
    updatedAt: expect.stringMatching(iso8601Regex)
  }]

  return request(app)
    .get('/pokemons')
    .expect(200)
    .then((response) => {
      expect(response.body.length).toBe(1)
      expect(response.body).toEqual(expect.arrayContaining(pokemons))
    })
})

test('pokemons.buy not enough ', () => {
  const pokemonToBuy = {
    name: 'pikachu',
    quantity: 5
  }

  return request(app)
    .post('/pokemons/buy')
    .type('Application/json')
    .send(pokemonToBuy)
    .expect(400)
    .then((response) => {
      expect(response.body).toHaveProperty('error')
      expect(response.body.error).toEqual(expect.stringContaining('Not enought pikachu in stock: '))
    })
})
<commit_msg>Update tests with new api error messages<commit_after>const request = require('supertest')
const app = require('./index')

const iso8601Regex = /\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d\.\d+([+-][0-2]\d:[0-5]\d|Z)/
const idRegex = /\d+/

jasmine.DEFAULT_TIMEOUT_INTERVAL = 20000

beforeAll(() => new Promise((resolve) => {
  setTimeout(() => {
    resolve()
  }, 1000)
}))

// TODO: [bug] test is not closing the program.
afterAll(() => {
  app.close()
})

test('pokemons.list', () => request(app).get('/pokemons').then((response) => {
  expect(response.body.length).toBe(0)
}))

test('pokemons.create', () => {
  const pikachu = {
    name: 'pikachu',
    price: 15.56,
    stock: 3
  }

  return request(app)
    .post('/pokemons')
    .type('Application/json')
    .send(pikachu)
    .expect(200)
    .then((response) => {
      expect(response.body).toMatchObject(pikachu)
    })
})

test('pokemons.create with invalid params', () => {
  const pikachu = {
    price: 'adsas',
    stock: '!#@!$'
  }

  return request(app)
    .post('/pokemons')
    .type('Application/json')
    .send(pikachu)
    .expect(400)
    .then((response) => {
      expect(response.body).toHaveProperty('errors')
      expect(response.body).toEqual(expect.objectContaining({
        errors: [
          {
            message: 'name is required and can only contain letters with 1 to 255 characters',
            parameter_name: 'name',
            type: 'invalid_parameter'
          },
          {
            message: 'price must be a decimal number',
            parameter_name: 'price',
            type: 'invalid_parameter'
          },
          {
            message: 'stock must be a integer',
            parameter_name: 'stock',
            type: 'invalid_parameter'
          }
        ]
      }))
    })
})

test('pokemons.list after create ', () => {
  const pokemons = [{
    id: expect.stringMatching(idRegex),
    name: 'pikachu',
    price: 15.56,
    stock: 3,
    createdAt: expect.stringMatching(iso8601Regex),
    updatedAt: expect.stringMatching(iso8601Regex)
  }]

  return request(app)
    .get('/pokemons')
    .expect(200)
    .then((response) => {
      expect(response.body.length).toBe(1)
      expect(response.body).toEqual(expect.arrayContaining(pokemons))
    })
})

test('pokemons.buy', () => {
  const pokemonToBuy = {
    name: 'pikachu',
    quantity: 2
  }

  return request(app)
    .post('/pokemons/buy')
    .type('Application/json')
    .send(pokemonToBuy)
    .expect(200)
    .then((response) => {
      expect(response.body).toHaveProperty('status', 'paid')
      expect(response.body).toHaveProperty('amount', 3112)
    })
})

test('pokemons.buy not found', () => {
  const pokemonToBuy = {
    name: 'bulbasaur',
    quantity: 3
  }

  return request(app)
    .post('/pokemons/buy')
    .type('Application/json')
    .send(pokemonToBuy)
    .expect(404)
    .then((response) => {
      expect(response.body).toHaveProperty('error')
      expect(response.body.error).toEqual(expect.stringContaining('not found'))
    })
})

test('pokemons.buy with invalid params', () => {
  const pokemonToBuy = {
    quantity: 2.15
  }

  return request(app)
    .post('/pokemons/buy')
    .type('Application/json')
    .send(pokemonToBuy)
    .expect(400)
    .then((response) => {
      expect(response.body).toHaveProperty('errors')
      expect(response.body).toEqual(expect.objectContaining({
        errors: [
          {
            message: 'name is required and can only contain letters with 1 to 255 characters',
            parameter_name: 'name',
            type: 'invalid_parameter'
          },
          {
            message: 'quantity is required and must be an integer',
            parameter_name: 'quantity',
            type: 'invalid_parameter'
          }
        ]
      }))
    })
})

test('pokemons.list after bought ', () => {
  const pokemons = [{
    id: expect.stringMatching(idRegex),
    name: 'pikachu',
    price: 15.56,
    stock: 1,
    createdAt: expect.stringMatching(iso8601Regex),
    updatedAt: expect.stringMatching(iso8601Regex)
  }]

  return request(app)
    .get('/pokemons')
    .expect(200)
    .then((response) => {
      expect(response.body.length).toBe(1)
      expect(response.body).toEqual(expect.arrayContaining(pokemons))
    })
})

test('pokemons.buy not enough ', () => {
  const pokemonToBuy = {
    name: 'pikachu',
    quantity: 5
  }

  return request(app)
    .post('/pokemons/buy')
    .type('Application/json')
    .send(pokemonToBuy)
    .expect(400)
    .then((response) => {
      expect(response.body).toHaveProperty('error')
      expect(response.body.error).toEqual(expect.stringContaining('Not enought pikachu in stock: '))
    })
})
<|endoftext|>


<commit_before>'use strict';
const assert = require('assert');
const extractDomain = require('./index');

const urls = [
    'https://www.npmjs.com/package/extract-domain',
    'http://www.example.com:80/path/to/myfile.html?key1=value1&key2=value2#SomewhereInTheDocument',
    'https://npmjs.com/package/extract-domain',
    'http://example.com:80/path/to/myfile.html?key1=value1&key2=value2#SomewhereInTheDocument',
    'http://www.so.many.sub.domains.example.com:80/path/to/myfile.html?key1=value1&key2=value2#SomewhereInTheDocument',
    'http://user:password@example.com:80/path/to/myfile.html?key1=value1&key2=value2#SomewhereInTheDocument',
    'ftp://example.org/resource.txt'
];

const expected = [
    'npmjs.com',
    'example.com',
    'npmjs.com',
    'example.com',
    'example.com',
    'example.com',
    'example.org'
];

describe('extract domain', () => {
    it('should extract given domain from string without sub domain', () => {
        assert.equal(extractDomain(urls[3]), expected[3]);
        assert.equal(extractDomain(urls[1]), expected[1]);
    });

    it('should extract given domain from string', () => {
        assert.equal(extractDomain(urls[1]), expected[1]);

        assert.equal(extractDomain(urls[0]), expected[0]);
    });

    it('should extract given domain from an array of strings', () => {
        const domains = extractDomain(urls);

        domains.map(domain => assert(expected.indexOf(domain) > -1));
    });

    it('should return empty string if it is not a domain', () => {
        assert.equal(extractDomain('/i.am/just.astring//7test'), '');
    });

    it('should throw syntax error exception if the argument is not string nor array', () => {
        try {
            extractDomain('{}');
        } catch (e) {
            assert.equal(e.name, 'TypeError');

            assert.equal(
                e.message,
                'The given URL is not a string. Please verify your string|array.'
            );
        }
    });

    it('should throw syntax error exception if the array value is not a string', () => {
        try {
            extractDomain([ [ 'wow' ] ]);
        } catch (e) {
            assert.equal(e.name, 'TypeError');

            assert.equal(
                e.message,
                'The given URL is not a string. Please verify your string|array.'
            );
        }
    });
});
<commit_msg>update test<commit_after>'use strict';
const assert = require('assert');
const extractDomain = require('./index');

const urls = [
    'https://www.npmjs.com/package/extract-domain',
    'http://www.example.com:80/path/to/myfile.html?key1=value1&key2=value2#SomewhereInTheDocument',
    'https://npmjs.com/package/extract-domain',
    'http://example.com:80/path/to/myfile.html?key1=value1&key2=value2#SomewhereInTheDocument',
    'http://www.so.many.sub.domains.example.com:80/path/to/myfile.html?key1=value1&key2=value2#SomewhereInTheDocument',
    'http://user:password@example.com:80/path/to/myfile.html?key1=value1&key2=value2#SomewhereInTheDocument',
    'ftp://example.org/resource.txt'
];

const expected = [
    'npmjs.com',
    'example.com',
    'npmjs.com',
    'example.org'
];

describe('extract domain', () => {
    it('should extract given domain from string without sub domain', () => {
        assert.equal(extractDomain(urls[3]), expected[1]);
        assert.equal(extractDomain(urls[1]), expected[1]);
    });

    it('should extract given domain from string', () => {
        assert.equal(extractDomain(urls[1]), expected[1]);

        assert.equal(extractDomain(urls[0]), expected[0]);
    });

    it('should extract given domain from an array of strings', () => {
        const domains = extractDomain(urls);

        domains.map(domain => assert(expected.indexOf(domain) > -1));
    });

    it('should return empty string if it is not a domain', () => {
        assert.equal(extractDomain('/i.am/just.astring//7test'), '');
    });

    it('should throw syntax error exception if the argument is not string nor array', () => {
        try {
            extractDomain('{}');
        } catch (e) {
            assert.equal(e.name, 'TypeError');

            assert.equal(
                e.message,
                'The given URL is not a string. Please verify your string|array.'
            );
        }
    });

    it('should throw syntax error exception if the array value is not a string', () => {
        try {
            extractDomain([ [ 'wow' ] ]);
        } catch (e) {
            assert.equal(e.name, 'TypeError');

            assert.equal(
                e.message,
                'The given URL is not a string. Please verify your string|array.'
            );
        }
    });
});
<|endoftext|>