<commit_before>import React from 'react'
import Controls from './Controls'
import UserRangeInputs from './UserRangeInputs'
require('./styles.scss')

class App extends React.Component {
  constructor() {
    super()
    this.state = {
      guess: '',
      showGuess: null,
      hint: null,
      min: 1,
      max: 100,
      generatedNum: null,
      gameWon: false,
      showMinRange: null,
      showMaxRange: null,
    }

    this.handleChange = this.handleChange.bind(this)
    this.handleSubmit = this.handleSubmit.bind(this)
    this.handleClear = this.handleClear.bind(this)
    this.handleReset = this.handleReset.bind(this)
    this.handleMinRange = this.handleMinRange.bind(this)
    this.handleMaxRange = this.handleMaxRange.bind(this)
    this.handleRangeSubmit = this.handleRangeSubmit.bind(this)
  }
  componentDidMount() {
    let { min, max } = this.state
    this.setState({
      generatedNum: this.randomNum(),
      showMinRange: min,
      showMaxRange: max,
     })
  }

  randomNum() {
    return Math.floor(Math.random() * (this.state.max - this.state.min + 1)) + this.state.min
  }

  handleChange(e) {
    let guess = e.target.value

    if (Number.isNaN(+guess)) {
      alert('Sorry, that is not a number')
      guess = ''
    } else if (+guess >= 101 || +guess <= 0) {
      alert('Sorry, you are outside the range')
      guess = ''
    }

    this.setState({guess: guess})
  }

  handleSubmit() {
    const { guess, min, max } = this.state
    this.setState({showGuess: guess, guess: '', hint: this.highOrLow(), gameWon: true}, ()=> {
        if (this.state.hint === 'Winner winner, chicken dinner!') {
          this.setState({
            min: min - 10,
            max: max + 10,
          }, () => {
             this.setState({
               generatedNum: this.randomNum(),
             }, () => {
               this.setState({
                    showMinRange: min,
                    showMaxRange: max,
              })
            })
         })
       }
    })
  }

  handleClear() {
    this.setState({ guess: '' })
  }

  handleReset() {
    this.setState({ showGuess: '', guess: '', hint: '', generatedNum: this.randomNum(), gameWon: false})
  }

  handleMinRange(e) {
    let minRange = e.target.value
    this.setState({min: minRange})
  }

  handleMaxRange(e) {
    let maxRange = e.target.value
    this.setState({max: maxRange})
  }

  handleRangeSubmit(minMax) {
    let { min, max } = this.state
    this.setState({
      showMinRange: minMax.min,
      showMaxRange: minMax.max,
      gameWon: true,
      min: +minMax.min,
      max: +minMax.max,
    }, () => {
      this.setState({ generatedNum: this.randomNum() })
    })
  }

  renderGuess() {
    return this.state.showGuess
  }

  renderMinRange() {
    return this.state.showMinRange
  }

  renderMaxRange() {
    return this.state.showMaxRange
  }

  renderHint() {
    return this.state.hint
  }

  buttonDisabled() {
    return !this.state.guess
  }

  resetDisabled() {
    return !this.state.gameWon
  }

  highOrLow() {
    let { guess, generatedNum } = this.state
    if (guess > generatedNum)  {
      return 'Sorry, that guess is too high.  Try a lower number.'
    } else if ( guess < generatedNum) {
      return 'Sorry, that guess is too low.  Try a higher number'
    } else {
      return 'Winner winner, chicken dinner!'
    }
  }

  // win() {
  //   let { min, max } = this.state
  //   if (this.state.hint === 'Winner winner, chicken dinner!') {
  //     this.setState({
  //       min: +10,
  //       max: -10,
  //       gameWon: true,
  //     })
  //   }
  // }
  //
  //
  // win() {
  //   let {guess, generatedNum } = this.state
  //   if (guess === generatedNum) {
  //     this.setState({gameWon: true, min: -10, max: +10})
  //   }
  // }

  render() {
    return (

Number Guesser in React

Your last guess was...

{this.renderGuess()}

{this.renderHint()}

        <Controls
          buttonDisabled={this.buttonDisabled()}
          resetDisabled={this.resetDisabled()}
          highOrLow={this.highOrLow()}
          guess={this.state.guess}
          handleChange={this.handleChange}
          handleSubmit={this.handleSubmit}
          handleClear={this.handleClear}
          handleReset={this.handleReset}/>
        <UserRangeInputs
          handleMinRange={this.handleMinRange}
          handleMaxRange={this.handleMaxRange}
          handleRangeSubmit={this.handleRangeSubmit}/>

              Min:  {this.renderMinRange()}
              Max:  {this.renderMaxRange()}

    )
  }
}

module.exports = App
<commit_msg>show updated range<commit_after>import React from 'react'
import Controls from './Controls'
import UserRangeInputs from './UserRangeInputs'
require('./styles.scss')

class App extends React.Component {
  constructor() {
    super()
    this.state = {
      guess: '',
      showGuess: null,
      hint: null,
      min: 1,
      max: 100,
      generatedNum: null,
      gameWon: false,
      showMinRange: null,
      showMaxRange: null,
    }

    this.handleChange = this.handleChange.bind(this)
    this.handleSubmit = this.handleSubmit.bind(this)
    this.handleClear = this.handleClear.bind(this)
    this.handleReset = this.handleReset.bind(this)
    this.handleMinRange = this.handleMinRange.bind(this)
    this.handleMaxRange = this.handleMaxRange.bind(this)
    this.handleRangeSubmit = this.handleRangeSubmit.bind(this)
  }
  componentDidMount() {
    let { min, max } = this.state
    this.setState({
      generatedNum: this.randomNum(),
      showMinRange: min,
      showMaxRange: max,
     })
  }

  randomNum() {
    return Math.floor(Math.random() * (this.state.max - this.state.min + 1)) + this.state.min
  }

  handleChange(e) {
    let guess = e.target.value

    if (Number.isNaN(+guess)) {
      alert('Sorry, that is not a number')
      guess = ''
    } else if (+guess >= 101 || +guess <= 0) {
      alert('Sorry, you are outside the range')
      guess = ''
    }
    this.setState({guess: guess})
  }

  handleSubmit() {
    const { guess, min, max } = this.state
    this.setState({showGuess: guess, guess: '', hint: this.highOrLow(), gameWon: true}, ()=> {
        if (this.state.hint === 'Winner winner, chicken dinner!') {
          this.setState({
            min: min - 10,
            max: max + 10,
          }, () => {
             this.setState({
               generatedNum: this.randomNum(),
             }, () => {
               this.setState({
                    showMinRange: this.state.min,
                    showMaxRange: this.state.max,
              })
            })
         })
       }
    })
  }

  handleClear() {
    this.setState({ guess: '' })
  }

  handleReset() {
    this.setState({ showGuess: '', guess: '', hint: '', generatedNum: this.randomNum(), gameWon: false})
  }

  handleMinRange(e) {
    let minRange = e.target.value
    this.setState({min: minRange})
  }

  handleMaxRange(e) {
    let maxRange = e.target.value
    this.setState({max: maxRange})
  }

  handleRangeSubmit(minMax) {
    let { min, max } = this.state
    this.setState({
      showMinRange: minMax.min,
      showMaxRange: minMax.max,
      gameWon: true,
      min: +minMax.min,
      max: +minMax.max,
    }, () => {
      this.setState({ generatedNum: this.randomNum() })
    })
  }

  renderGuess() {
    return this.state.showGuess
  }

  renderMinRange() {
    return this.state.showMinRange
  }

  renderMaxRange() {
    return this.state.showMaxRange
  }

  renderHint() {
    return this.state.hint
  }

  buttonDisabled() {
    return !this.state.guess
  }

  resetDisabled() {
    return !this.state.gameWon
  }

  highOrLow() {
    let { guess, generatedNum } = this.state
    if (guess > generatedNum)  {
      return 'Sorry, that guess is too high.  Try a lower number.'
    } else if ( guess < generatedNum) {
      return 'Sorry, that guess is too low.  Try a higher number'
    } else {
      return 'Winner winner, chicken dinner!'
    }
  }

  // win() {
  //   let { min, max } = this.state
  //   if (this.state.hint === 'Winner winner, chicken dinner!') {
  //     this.setState({
  //       min: +10,
  //       max: -10,
  //       gameWon: true,
  //     })
  //   }
  // }
  //
  //
  // win() {
  //   let {guess, generatedNum } = this.state
  //   if (guess === generatedNum) {
  //     this.setState({gameWon: true, min: -10, max: +10})
  //   }
  // }

  render() {
    return (

Number Guesser in React

Your last guess was...

{this.renderGuess()}

{this.renderHint()}

        <Controls
          buttonDisabled={this.buttonDisabled()}
          resetDisabled={this.resetDisabled()}
          highOrLow={this.highOrLow()}
          guess={this.state.guess}
          handleChange={this.handleChange}
          handleSubmit={this.handleSubmit}
          handleClear={this.handleClear}
          handleReset={this.handleReset}/>
        <UserRangeInputs
          handleMinRange={this.handleMinRange}
          handleMaxRange={this.handleMaxRange}
          handleRangeSubmit={this.handleRangeSubmit}/>

              Min:  {this.renderMinRange()}
              Max:  {this.renderMaxRange()}

    )
  }
}

module.exports = App
<|endoftext|>


<commit_before>var irc = require('irc');
var knex = require('knex')({
  client: process.env.CLIENT || 'sqlite3',
  connection: process.env.DATABASE_URL || { filename: 'dev.sqlite3' }
});

console.log(process.env.NC_CHANNEL_LIST.split(','));
var client = new irc.Client(process.env.NC_SERVER || 'chat.freenode.net',
  process.env.NC_NICK || 'nick-counter-bot',
  { channels:process.env.NC_CHANNEL_LIST.split(',') }
);

client.addListener('message', function (from, to, message) {
  console.log(from, to, message);
  knex.select('num_messages')
      .from('messages')
      .where( { nick:from } )
      .then(function(resp) {
        console.log(resp);
        if (resp.length) {
          knex('messages').where({nick:from})
            .update({nick:from, num_messages: resp.num_messages + 1})
            .catch(function (error) {
              console.log(error);
            });
        } else {
          knex('messages')
            .insert({nick:from, num_messages: 1})
            .catch(function (error) {
              console.log(error);
            });
        }
      });
});
<commit_msg>Access first element of the response first<commit_after>var irc = require('irc');
var knex = require('knex')({
  client: process.env.CLIENT || 'sqlite3',
  connection: process.env.DATABASE_URL || { filename: 'dev.sqlite3' }
});

console.log(process.env.NC_CHANNEL_LIST.split(','));
var client = new irc.Client(process.env.NC_SERVER || 'chat.freenode.net',
  process.env.NC_NICK || 'nick-counter-bot',
  { channels:process.env.NC_CHANNEL_LIST.split(',') }
);

client.addListener('message', function (from, to, message) {
  knex.select('num_messages')
      .from('messages')
      .where( { nick:from } )
      .then(function(resp) {
        if (resp.length) {
          knex('messages').where({nick:from})
            .update({nick:from, num_messages: resp[0].num_messages + 1})
            .catch(function (error) {
              console.log(error);
            });
        } else {
          knex('messages')
            .insert({nick:from, num_messages: 1})
            .catch(function (error) {
              console.log(error);
            });
        }
      });
});
<|endoftext|>


<commit_before>
var Element = require('./Element');
var RSSItem = require('./RSSItem');

const head = '<?xml version="1.0" encoding="UTF-8"?>';

const rssHead = new Element('rss', {
  'version': '2.0',
  'xmlns:content':'http://purl.org/rss/1.0/modules/content/'
});

module.exports = RSS;

/**
 * @constructor RSS
 * @param {Object} options
 */

function RSS(options) {
  var self = this;
  var options = options || {};
  var elements = this.elements = {};

  //Required elements
  options.title = options.title || 'Untitled';
  options.link = options.link || 'www.example.com';
  options.description = options.description || 'Undescribed';

  // Construct RSS feed
  var keys = Object.keys(options), key;

  while (key = keys.shift()) {
    var value = options[key];
    elements[key] = this[key] = new Element(key, value);
  };

  // Flag for wrapping content in CDATA blocks
  this.description.CDATA = true;
  this.title.CDATA = true;

  // Root channel element
  var channelName = options.channel || 'Untitled';
  this.channel = new Element('channel', channelName);

  // Container for RSS items
  this.items = [];

  // Container for options
  this.options = {};

  // Listen for changes on all Elements
  Element.on('change', function() {
    self.lastModified = Date.now();
  });

  return this;
};

RSS.createFeed = function(options) {
  return new RSS(options);
};

RSS.createElement = function(name, text, attrs) {
  return new Element(name, text, attrs);
};

/**
 * Set option
 *
 * @param {String} key
 * @param {Any} val
 */

RSS.prototype.set = function(key, val) {
  this.options[key] = val;
};

/**
 * Get option
 *
 * @param {String} key
 * @return option
 */

RSS.prototype.get = function(key) {
  return this.options[key];
};

/**
 * Get a conformant date string
 *
 * @return String
 */

RSS.prototype.dateString = dateString;

function dateString() {
  return (new Date).toUTCString();
};

/**
 * Update publication date
 */

RSS.prototype.setPubDate = setPubDate;

function setPubDate() {
  var pubDate = this.elements.pubDate;

  if (!pubDate) return;

  // Update the `pubDate` element's text value
  pubDate.text(this.dateString());
};

/**
 * addItem
 *
 * Add an item to the RSS feed
 *
 * @param {Object} options
 * @return RSSItem
 */

RSS.prototype.addItem =
RSS.prototype.item = addItem;

function addItem(options, cb) {
  var item = new RSSItem;
  var options = options || {};

  options.guid = options.guid || this.dateString();

  var keys = Object.keys(options), key;

  // Construct item
  while (key = keys.shift()) {
    var value = options[key];
    item.add(key, new Element(key, value));
  };

  // Flag for wrapping content in CDATA blocks
  if (item.description) item.description.CDATA = true;
  if (item.title) item.title.CDATA = true;

  if (cb) cb(item);

  // Add item to list
  this.items.push(item);

  // Update modified clock
  this.lastModified = Date.now();

  // Update publish date
  this.setPubDate();

  return item;
};

/**
 * Render channel or item elements
 *
 * @param {String} type
 * @return String
 * @api private
 */

RSS.prototype._render = _render;

function _render(type) {
  var elements = this[type];
  var keys = Object.keys(elements), key;
  var result = '';

  while (key = keys.shift()) {
    result += elements[key].toString();
  };

  return result;
};

/**
 * Render the RSS feed
 *
 * @return String
 * @api public
 */

RSS.prototype.render =
RSS.prototype.xml = render;

function render(cb) {

  // Return cached result
  if (this.lastModified <= this.lastRendered) {
    return this.cached;
  };

  // Render elements
  var channel        = this.channel;
  var channelContent = this._render('elements');
  var itemsContent   = this._render('items');

  // Generate XML
  var result = head
    + rssHead.open()
    + channel.open()
    + channelContent
    + itemsContent
    + channel.close()
    + rssHead.close();

  if (cb) cb(null, result);

  // Update cache
  this.cached = result;

  // Update clocks
  var now = Date.now();
  this.lastModified = now;
  this.lastRendered = now;

  return result;
};
<commit_msg>Add feed.appendChild for feed elements<commit_after>
var Element = require('./Element');
var RSSItem = require('./RSSItem');

const head = '<?xml version="1.0" encoding="UTF-8"?>';

const rssHead = new Element('rss', {
  'version': '2.0',
  'xmlns:content':'http://purl.org/rss/1.0/modules/content/'
});

module.exports = RSS;

/**
 * @constructor RSS
 * @param {Object} options
 */

function RSS(options) {
  var self = this;
  var options = options || {};
  var elements = this.elements = {};

  //Required elements
  options.title = options.title || 'Untitled';
  options.link = options.link || 'www.example.com';
  options.description = options.description || 'Undescribed';

  // Construct RSS feed
  var keys = Object.keys(options), key;

  while (key = keys.shift()) {
    var value = options[key];
    elements[key] = this[key] = new Element(key, value);
  };

  // Flag for wrapping content in CDATA blocks
  this.description.CDATA = true;
  this.title.CDATA = true;

  // Root channel element
  var channelName = options.channel || 'Untitled';
  this.channel = new Element('channel', channelName);

  // Container for RSS items
  this.items = [];

  // Container for options
  this.options = {};

  // Listen for changes on all Elements
  Element.on('change', function() {
    self.lastModified = Date.now();
  });

  return this;
};

RSS.createFeed = function(options) {
  return new RSS(options);
};

RSS.createElement = function(name, text, attrs) {
  return new Element(name, text, attrs);
};

RSS.prototype.appendChild = function(element) {
  this.elements[element._name] = element;
};

/**
 * Set option
 *
 * @param {String} key
 * @param {Any} val
 */

RSS.prototype.set = function(key, val) {
  this.options[key] = val;
};

/**
 * Get option
 *
 * @param {String} key
 * @return option
 */

RSS.prototype.get = function(key) {
  return this.options[key];
};

/**
 * Get a conformant date string
 *
 * @return String
 */

RSS.prototype.dateString = dateString;

function dateString() {
  return (new Date).toUTCString();
};

/**
 * Update publication date
 */

RSS.prototype.setPubDate = setPubDate;

function setPubDate() {
  var pubDate = this.elements.pubDate;

  if (!pubDate) return;

  // Update the `pubDate` element's text value
  pubDate.text(this.dateString());
};

/**
 * addItem
 *
 * Add an item to the RSS feed
 *
 * @param {Object} options
 * @return RSSItem
 */

RSS.prototype.addItem =
RSS.prototype.item = addItem;

function addItem(options, cb) {
  var item = new RSSItem;
  var options = options || {};

  options.guid = options.guid || this.dateString();

  var keys = Object.keys(options), key;

  // Construct item
  while (key = keys.shift()) {
    var value = options[key];
    item.add(key, new Element(key, value));
  };

  // Flag for wrapping content in CDATA blocks
  if (item.description) item.description.CDATA = true;
  if (item.title) item.title.CDATA = true;

  if (cb) cb(item);

  // Add item to list
  this.items.push(item);

  // Update modified clock
  this.lastModified = Date.now();

  // Update publish date
  this.setPubDate();

  return item;
};

/**
 * Render channel or item elements
 *
 * @param {String} type
 * @return String
 * @api private
 */

RSS.prototype._render = _render;

function _render(type) {
  var elements = this[type];
  var keys = Object.keys(elements), key;
  var result = '';

  while (key = keys.shift()) {
    result += elements[key].toString();
  };

  return result;
};

/**
 * Render the RSS feed
 *
 * @return String
 * @api public
 */

RSS.prototype.render =
RSS.prototype.xml = render;

function render(cb) {

  // Return cached result
  if (this.lastModified <= this.lastRendered) {
    return this.cached;
  };

  // Render elements
  var channel        = this.channel;
  var channelContent = this._render('elements');
  var itemsContent   = this._render('items');

  // Generate XML
  var result = head
    + rssHead.open()
    + channel.open()
    + channelContent
    + itemsContent
    + channel.close()
    + rssHead.close();

  if (cb) cb(null, result);

  // Update cache
  this.cached = result;

  // Update clocks
  var now = Date.now();
  this.lastModified = now;
  this.lastRendered = now;

  return result;
};
<|endoftext|>


<commit_before>'use strict';

Object.defineProperty(exports, "__esModule", {
    value: true
});
exports.SUM = SUM;

var _FLATTEN = require('./FLATTEN');

function SUM() {
    var numbers = (0, _FLATTEN.FLATTEN)(arguments);
    return numbers.reduce(function (a, b) {
        return a + b;
    });
}<commit_msg>Update SUM<commit_after>'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.SUM = SUM;

var _FLATTEN = require('./FLATTEN');

var _ERROR = require('./ERROR');

var _ERROR2 = _interopRequireDefault(_ERROR);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

// Author: Peter Moresi
function SUM() {
  for (var _len = arguments.length, numbers = Array(_len), _key = 0; _key < _len; _key++) {
    numbers[_key] = arguments[_key];
  }

  return (0, _FLATTEN.FLATTEN)((0, _FLATTEN.FLATTEN)(numbers)).reduce(function (a, b) {
    if (typeof b !== 'number') {
      return _ERROR2.default.value;
    }
    return a + b;
  });
}<|endoftext|>


<commit_before>"use strict";

// eslint-disable-next-line no-magic-numbers
module.exports = `wires_${ `${ Math.random() }`.slice( 2 ) }${ Date.now() }`;
<commit_msg>Creates proper random value for UID.<commit_after>"use strict";

const { randomBytes } = require( `crypto` );

const LENGTH = 20;

// eslint-disable-next-line no-magic-numbers
module.exports = `wires_${ randomBytes( LENGTH ).toString( `hex` ) }`;
<|endoftext|>


<commit_before>/*
## API docs? Nope, ape docs!

---
ape is a command line tool to generate documentation from your comments.
It parses your source code files, and strips markdown formatted comments out,
it then puts your code in github-flavored-markdown code blocks, and displays the comments in line.

It wasn't written to be fancy, but rather to have a simple, automated way of keeping docs on github up to date.

To use:

    sudo npm install -g ape
    ape [list of files or directories]
*/

// Require dependencies
var fs = require('fs'),
    path = require('path'),
    gfm = require('ghm'),
    hljs = require('hljs'),
    jade = require('jade');

// This is the exported function that does the actual parsing and documentation generation
exports.generate_doc = function (filename, outputFormat, outputPath, template, callback) {
    path.exists(filename, function (exists) {
        if (exists) {
            var code = fs.readFileSync(filename).toString().split('\n');
            parse_code(filename, code, outputFormat, outputPath, template, callback);
        } else {
            callback(new Error('file does not exist ' + filename));
        }
    });
};

/*
This function is a helper for frontends, to make it simpler to determine if a file can be processed by ape.
It returns a callback with a single boolean parameter indicating if the file is supported
*/
exports.supported = function (filename, callback) {
    var lang = languages[path.extname(filename)];
    if (typeof lang === 'undefined' ) {
        callback(false);
    } else {
        callback(true);
    }
};

// A simple helper function to return the dictionary of comment regexs, determined by the file extension
function get_language(filename) {
    var lang = languages[path.extname(filename)];
    return lang;
}

/*
This is the main function to parse the line array of source code, and return a new line array
containing the formatted text
*/
function parse_code(filename, code, outputFormat, outputPath, template, callback) {
    var parsed_code = [],
        this_line,
        in_comment,
        in_code,
        spaces,
        lang = get_language(filename),
        commentblock = [],
        codeblock = [],
        tempblock = [];

    if (typeof lang === 'undefined') return;

    function pushblock() {
        parsed_code.push({ code: codeblock.join('\n'), comment: commentblock.join('\n') });
        codeblock = [];
        commentblock = [];
        in_code = false;
    }

    for (var i = 0, l = code.length; i < l; i++) {
        this_line = code[i];
        if (this_line.match(lang.comment) && !in_comment && !this_line.match(/^#\!/)) {
            if (in_code) pushblock();
            commentblock.push(this_line.replace(lang.comment, ''))
        } else if (this_line.match(lang.start) && !in_comment) {
            if (lang.name === 'python' && in_code) {
                while (codeblock[codeblock.length - 1].trim() !== '') {
                    tempblock.push(codeblock.pop());
                }
            }
            if (in_code) pushblock();
            if (lang.name === 'python') {
                for (var ti = 0, tl = tempblock.length; ti < tl; ti++) {
                    codeblock.push(tempblock.pop());
                }
            }
            in_comment = true;
            spaces = this_line.match(/^\s+/);
            if (spaces) spaces = spaces[0].length;
            this_line = this_line.replace(lang.start, '');
            if (this_line.match(lang.end)) {
                this_line = this_line.replace(lang.end, '');
                in_comment = false;
            }
            if (this_line.trim() !== '') commentblock.push(this_line);
        } else if (this_line.match(lang.end) && in_comment) {
            this_line = this_line.replace(lang.end, '');
            if (this_line.trim() !== '') commentblock.push(this_line);
            in_comment = false;
        } else if (this_line.trim() === '' && !in_comment && !in_code) {
            pushblock();
        } else {
            if (in_comment) {
                if (lang.name === 'python') this_line = this_line.substring(spaces);
                commentblock.push(this_line);
            } else {
                if (!in_code && this_line.trim() !== '') in_code = true;
                codeblock.push(this_line);
            }
        }
    }

    pushblock();

    if (outputFormat === 'md') {
        write_md(filename, parsed_code, outputPath, callback);
    } else if (outputFormat === 'html') {
        write_html(filename, parsed_code, outputPath, template, callback);
    }
}

// This function writes the parsed output to a markdown file, matching the original source's filename but changing the extension to .md
function write_md(filename, parsed_code, outputPath, callback) {
    var outfile,
        outcode = '';

    if (typeof outputPath === 'undefined') {
        outfile = filename.replace(path.extname(filename), '.md');
    } else {
        outfile = path.join(outputPath, path.basename(filename).replace(path.extname(filename), '.md'));
    }

    for (var i = 0, l = parsed_code.length; i < l; i++) {
        if (parsed_code[i].comment !== '') outcode += parsed_code[i].comment + '\n\n';
        if (parsed_code[i].code !== '') outcode += '```' + get_language(filename).name + '\n' + parsed_code[i].code + '\n```\n\n';
    }

    fs.writeFileSync(outfile, outcode, 'utf8');
    callback(null, outfile);
}

// This function writes parsed output to html
function write_html(filename, parsed_code, outputPath, template, callback) {
    var outfile,
        templatePath,
        template;

    if (typeof outputPath === 'undefined') {
        outfile = filename.replace(path.extname(filename), '.html');
    } else {
        outfile = path.join(outputPath, path.basename(filename).replace(path.extname(filename), '.html'));
    }

    if (typeof template === 'undefined') {
        templatePath = path.join(__dirname, 'template.jade');
    } else {
        templatePath = template;
    }

    template = fs.readFileSync(__dirname + '/template.jade', 'utf-8');
    var fn = jade.compile(template);
    fs.writeFileSync(outfile, fn({ gfm: gfm, data: parsed_code, hljs: hljs, lang: get_language(filename).name }));
    callback(null, outfile);
}

/*
Here we define our supported languages. Each language is a dictionary, keyed on the file extension. Inside the dictionary
we have the the following items:

* 'name': the identifier that we output to the markdown for code blocks
* 'comment': is a regex that will match a single line comment for the specific language, but does NOT include the text on the line, only the comment
* 'start': a regular expression to match the beginning of a multi-line commment block. 'start' should only match if it's on the beginning
of a line
* 'end': the partner regex to 'start' matching the end of a multi-line comment only if the match is at the end of a line.
*/
var languages = {
    '.js': { name: 'javascript', comment: /^\s*\/\/\s?/, start: /^\s*\/\*\s?/, end: /\*\/\s*$/ },
    '.py': { name: 'python', comment: /^\s*#\s?/, start: /^\s*\"\"\"\s?/, end: /\"\"\"\s*$/ },
    '.rb': { name: 'ruby', comment: /^\s*#\s?/, start: /^\s*\=begin\s?/, end: /\=end\s*$/ },
    '.lua': { name: 'lua', comment: /^\s*--\s?/, start: /^\s*--\[\[\s?/, end: /--\]\]\s*$/ }
};
<commit_msg>ape.js: add coffeescript to languages<commit_after>/*
## API docs? Nope, ape docs!

---
ape is a command line tool to generate documentation from your comments.
It parses your source code files, and strips markdown formatted comments out,
it then puts your code in github-flavored-markdown code blocks, and displays the comments in line.

It wasn't written to be fancy, but rather to have a simple, automated way of keeping docs on github up to date.

To use:

    sudo npm install -g ape
    ape [list of files or directories]
*/

// Require dependencies
var fs = require('fs'),
    path = require('path'),
    gfm = require('ghm'),
    hljs = require('hljs'),
    jade = require('jade');

// This is the exported function that does the actual parsing and documentation generation
exports.generate_doc = function (filename, outputFormat, outputPath, template, callback) {
    path.exists(filename, function (exists) {
        if (exists) {
            var code = fs.readFileSync(filename).toString().split('\n');
            parse_code(filename, code, outputFormat, outputPath, template, callback);
        } else {
            callback(new Error('file does not exist ' + filename));
        }
    });
};

/*
This function is a helper for frontends, to make it simpler to determine if a file can be processed by ape.
It returns a callback with a single boolean parameter indicating if the file is supported
*/
exports.supported = function (filename, callback) {
    var lang = languages[path.extname(filename)];
    if (typeof lang === 'undefined' ) {
        callback(false);
    } else {
        callback(true);
    }
};

// A simple helper function to return the dictionary of comment regexs, determined by the file extension
function get_language(filename) {
    var lang = languages[path.extname(filename)];
    return lang;
}

/*
This is the main function to parse the line array of source code, and return a new line array
containing the formatted text
*/
function parse_code(filename, code, outputFormat, outputPath, template, callback) {
    var parsed_code = [],
        this_line,
        in_comment,
        in_code,
        spaces,
        lang = get_language(filename),
        commentblock = [],
        codeblock = [],
        tempblock = [];

    if (typeof lang === 'undefined') return;

    function pushblock() {
        parsed_code.push({ code: codeblock.join('\n'), comment: commentblock.join('\n') });
        codeblock = [];
        commentblock = [];
        in_code = false;
    }

    for (var i = 0, l = code.length; i < l; i++) {
        this_line = code[i];
        if (this_line.match(lang.comment) && !in_comment && !this_line.match(/^#\!/)) {
            if (in_code) pushblock();
            commentblock.push(this_line.replace(lang.comment, ''))
        } else if (this_line.match(lang.start) && !in_comment) {
            if (lang.name === 'python' && in_code) {
                while (codeblock[codeblock.length - 1].trim() !== '') {
                    tempblock.push(codeblock.pop());
                }
            }
            if (in_code) pushblock();
            if (lang.name === 'python') {
                for (var ti = 0, tl = tempblock.length; ti < tl; ti++) {
                    codeblock.push(tempblock.pop());
                }
            }
            in_comment = true;
            spaces = this_line.match(/^\s+/);
            if (spaces) spaces = spaces[0].length;
            this_line = this_line.replace(lang.start, '');
            if (this_line.match(lang.end)) {
                this_line = this_line.replace(lang.end, '');
                in_comment = false;
            }
            if (this_line.trim() !== '') commentblock.push(this_line);
        } else if (this_line.match(lang.end) && in_comment) {
            this_line = this_line.replace(lang.end, '');
            if (this_line.trim() !== '') commentblock.push(this_line);
            in_comment = false;
        } else if (this_line.trim() === '' && !in_comment && !in_code) {
            pushblock();
        } else {
            if (in_comment) {
                if (lang.name === 'python') this_line = this_line.substring(spaces);
                commentblock.push(this_line);
            } else {
                if (!in_code && this_line.trim() !== '') in_code = true;
                codeblock.push(this_line);
            }
        }
    }

    pushblock();

    if (outputFormat === 'md') {
        write_md(filename, parsed_code, outputPath, callback);
    } else if (outputFormat === 'html') {
        write_html(filename, parsed_code, outputPath, template, callback);
    }
}

// This function writes the parsed output to a markdown file, matching the original source's filename but changing the extension to .md
function write_md(filename, parsed_code, outputPath, callback) {
    var outfile,
        outcode = '';

    if (typeof outputPath === 'undefined') {
        outfile = filename.replace(path.extname(filename), '.md');
    } else {
        outfile = path.join(outputPath, path.basename(filename).replace(path.extname(filename), '.md'));
    }

    for (var i = 0, l = parsed_code.length; i < l; i++) {
        if (parsed_code[i].comment !== '') outcode += parsed_code[i].comment + '\n\n';
        if (parsed_code[i].code !== '') outcode += '```' + get_language(filename).name + '\n' + parsed_code[i].code + '\n```\n\n';
    }

    fs.writeFileSync(outfile, outcode, 'utf8');
    callback(null, outfile);
}

// This function writes parsed output to html
function write_html(filename, parsed_code, outputPath, template, callback) {
    var outfile,
        templatePath,
        template;

    if (typeof outputPath === 'undefined') {
        outfile = filename.replace(path.extname(filename), '.html');
    } else {
        outfile = path.join(outputPath, path.basename(filename).replace(path.extname(filename), '.html'));
    }

    if (typeof template === 'undefined') {
        templatePath = path.join(__dirname, 'template.jade');
    } else {
        templatePath = template;
    }

    template = fs.readFileSync(__dirname + '/template.jade', 'utf-8');
    var fn = jade.compile(template);
    fs.writeFileSync(outfile, fn({ gfm: gfm, data: parsed_code, hljs: hljs, lang: get_language(filename).name }));
    callback(null, outfile);
}

/*
Here we define our supported languages. Each language is a dictionary, keyed on the file extension. Inside the dictionary
we have the the following items:

* 'name': the identifier that we output to the markdown for code blocks
* 'comment': is a regex that will match a single line comment for the specific language, but does NOT include the text on the line, only the comment
* 'start': a regular expression to match the beginning of a multi-line commment block. 'start' should only match if it's on the beginning
of a line
* 'end': the partner regex to 'start' matching the end of a multi-line comment only if the match is at the end of a line.
*/
var languages = {
    '.js': { name: 'javascript', comment: /^\s*\/\/\s?/, start: /^\s*\/\*\s?/, end: /\*\/\s*$/ },
    '.py': { name: 'python', comment: /^\s*#\s?/, start: /^\s*\"\"\"\s?/, end: /\"\"\"\s*$/ },
    '.rb': { name: 'ruby', comment: /^\s*#\s?/, start: /^\s*\=begin\s?/, end: /\=end\s*$/ },
    '.lua': { name: 'lua', comment: /^\s*--\s?/, start: /^\s*--\[\[\s?/, end: /--\]\]\s*$/ },
    '.coffee': { name: 'coffeescript', comment: /^\s*#(?!##)\s?/, start: /^\s*###\s?/, end: /###\s*$/ }
};
<|endoftext|>


<commit_before>'use strict';
var Endpoint = require('./api/endpoint')
var Permissions = require('./api/permissions')

var fs = require('fs')
var path = require('path')
var _ = require('lodash')

class Api {
	constructor(app) {
		this.app = app
		this.endpoints = []
		this.DiffType = this.app.history.DiffType
		this.permissions = new Permissions(app)
	}

	exists(endpoint) {
		let find = false
		this.endpoints.forEach((e) => {
			if (endpoint.method == e.method && endpoint.url == e.url) {
				find = true
			}
		})
		return find
	}

	add(endpoint, options) {
		if (endpoint) {
			if (this.exists(endpoint)) {
				this.remove(endpoint.method, endpoint.url)
			}
			this.endpoints.push(new Endpoint(this.app, endpoint))
			if (options.save != false) {
				this.save(options)
			}
		}
	}

	put(endpoint, pos, options) {
		this.endpoints[pos] = new Endpoint(this.app, endpoint)
		if (options.save != false) {
			this.save(options)
		}
	}

	remove(method, url, options) {
		for (let i in this.endpoints) {
			let endpoint = this.endpoints[i]
			if (endpoint.url == url && endpoint.method == method) {
				this.endpoints.splice(i, 1)
				if (options.save != false) {
					this.save(options)
				}
				return
			}
		}
	}

	get(method, url) {
		for (let endpoint of this.endpoints) {
			if (endpoint.url == url && endpoint.method == method) {
				return endpoint
			}
		}
	}

	findAll() { return this.endpoints }

	load() {
		//console.log('\nLoading endpoints...')
		this.endpoints = []

		//this.generateApi()
		try {
			//console.log('API.... load ', path.join(this.app.path, 'api.json'))
			let content = fs.readFileSync(path.join(this.app.path, 'api.json'))
			let endpoints = JSON.parse(content.toString())
			//console.log(endpoints)
			//console.log 'Overload default endpoints with endpoints.json'
			endpoints.forEach((endpoint) => {
				/*let find = false
				this.endpoints.forEach((e2, i) => {
					if (e2.method == endpoint.method && e2.url == endpoint.url) {
						find = i
					}
				})
				if (find === false) {*/
				this.add(endpoint)
					/*
				}
				else {
					this.put(endpoint, find)
				}*/
			})
		} catch (e) {
			//console.log('not endpoint found')
			//console.log 'api.json not found: ', e
		}
	}

	registerEndpoints(appServer) {
		//console.log '\nSetup API...'
		this.endpoints.forEach((endpoint) => {
			//console.log(endpoint.method.toUpperCase() + ' ' + endpoint.url)
			let route = appServer[endpoint.method.toLowerCase()]
			//console.log(route)
			route.call(appServer, '/api' + endpoint.url, this.permissions.check(endpoint.permissions), (req, res) => {
				endpoint.handle(req, res)
			})
		})
	}

	toJson() {
		let res = []
		this.endpoints.forEach((endpoint) => {
			res.push(endpoint.toJson())
		})
		return res
	}

	save(opts) {
		if (opts && opts.beforeSave) {
			opts.beforeSave()
		}
		fs.writeFileSync(path.join(this.app.path, 'api.json'), JSON.stringify(this.toJson(), null, '\t'))
		if (opts && opts.afterSave) {
			opts.afterSave()
		}
	}
}

module.exports = Api
<commit_msg>fix endpoint loading error (options save set to false)<commit_after>'use strict';
var Endpoint = require('./api/endpoint')
var Permissions = require('./api/permissions')

var fs = require('fs')
var path = require('path')
var _ = require('lodash')

class Api {
	constructor(app) {
		this.app = app
		this.endpoints = []
		this.DiffType = this.app.history.DiffType
		this.permissions = new Permissions(app)
	}

	exists(endpoint) {
		let find = false
		this.endpoints.forEach((e) => {
			if (endpoint.method == e.method && endpoint.url == e.url) {
				find = true
			}
		})
		return find
	}

	add(endpoint, options) {
		options = options || {}
		if (endpoint) {
			if (this.exists(endpoint)) {
				this.remove(endpoint.method, endpoint.url)
			}
			this.endpoints.push(new Endpoint(this.app, endpoint))
			if (options.save != false) {
				this.save(options)
			}
		}
	}

	put(endpoint, pos, options) {
		this.endpoints[pos] = new Endpoint(this.app, endpoint)
		if (options.save != false) {
			this.save(options)
		}
	}

	remove(method, url, options) {
		for (let i in this.endpoints) {
			let endpoint = this.endpoints[i]
			if (endpoint.url == url && endpoint.method == method) {
				this.endpoints.splice(i, 1)
				if (options.save != false) {
					this.save(options)
				}
				return
			}
		}
	}

	get(method, url) {
		for (let endpoint of this.endpoints) {
			if (endpoint.url == url && endpoint.method == method) {
				return endpoint
			}
		}
	}

	findAll() { return this.endpoints }

	load() {
		//console.log('\nLoading endpoints...')
		this.endpoints = []

		//this.generateApi()
		try {
			//console.log('API.... load ', path.join(this.app.path, 'api.json'))
			let content = fs.readFileSync(path.join(this.app.path, 'api.json'))
			let endpoints = JSON.parse(content.toString())

			endpoints.forEach((endpoint) => {
				this.add(endpoint, {save: false})
			})
		} catch (e) {
			console.error('error loading endpoints', e)
			//console.log('not endpoint found')
			//console.log 'api.json not found: ', e
		}
	}

	registerEndpoints(appServer) {
		//console.log '\nSetup API...'
		this.endpoints.forEach((endpoint) => {
			//console.log(endpoint.method.toUpperCase() + ' ' + endpoint.url)
			let route = appServer[endpoint.method.toLowerCase()]
			//console.log(route)
			route.call(appServer, '/api' + endpoint.url, this.permissions.check(endpoint.permissions), (req, res) => {
				endpoint.handle(req, res)
			})
		})
	}

	toJson() {
		let res = []
		this.endpoints.forEach((endpoint) => {
			res.push(endpoint.toJson())
		})
		return res
	}

	save(opts) {
		if (opts && opts.beforeSave) {
			opts.beforeSave()
		}
		fs.writeFileSync(path.join(this.app.path, 'api.json'), JSON.stringify(this.toJson(), null, '\t'))
		if (opts && opts.afterSave) {
			opts.afterSave()
		}
	}
}

module.exports = Api
<|endoftext|>


<commit_before>"use strict";

var CONSTANT_PREFIX = "var getMessage = function() { var r = function(val, args){ for(var x = 0;x<args.length;x++){ val = val.replace('{'+x+'}', args[x]); } return val; }; var p = function() { var val = arguments[0]; var ret; if (val.indexOf('{0}') != -1) ret = function(){return r(val,arguments);} else ret = function(){return val;} for(var x = 1; x < arguments.length;x++) { for (var a in arguments[x]) ret[a] = arguments[x][a]; } return ret; }; return ";
var CONSTANT_SUFFIX = "; }";

var Node = require('./Node');
var processor = require('./processor');

var createSpringMessagesPreprocessor = function(args, config, logger, helper) {
    config = config || {};
    var log = logger.create("preprocessor.spring-messages");
    var defaultOptions = {
        prefix: "", // Used for boilerplate, for example wrap in a define() call
        suffix: ""  // Used for boilerplate, for example, close function calls with );
    };

    var options = helper.merge(defaultOptions, args.options || {}, config.options || {});

    var transformPath = args.transformPath || config.transformPath || function(filepath) {
            return filepath + ".js";
        };

    return function(content, file, done) {
        log.debug("Processing %s", file.originalPath);
        file.path = transformPath(file.originalPath);

        var lines = content.split("\n");

        var tree = processor.process(lines);

        done(null, options.prefix + CONSTANT_PREFIX + Node.render(tree) + CONSTANT_SUFFIX + options.suffix);
    };

};

createSpringMessagesPreprocessor.$inject = ['args', 'config.springMessagesPreprocessor', 'logger', 'helper'];

module.exports = {
    'preprocessor:spring-messages': ["factory", createSpringMessagesPreprocessor]
};<commit_msg>Fix PREFIX script to be valid.<commit_after>"use strict";

var CONSTANT_PREFIX = "var getTaboolaBackstageMessages = function (){\n";
CONSTANT_PREFIX += "var r = function(val, args){\n";
CONSTANT_PREFIX += "    for(var x = 0;x<args.length;x++){\n";
CONSTANT_PREFIX += "        val = val.replace('{'+x+'}', args[x]);\n";
CONSTANT_PREFIX += "    }\n";
CONSTANT_PREFIX += "    return val;\n";
CONSTANT_PREFIX += "};\n";
CONSTANT_PREFIX += "var p = function() {\n";
CONSTANT_PREFIX += "    var val = arguments[0];\n";
CONSTANT_PREFIX += "    var ret;\n";
CONSTANT_PREFIX += "    if(val.indexOf('{0}') != -1)\n";
CONSTANT_PREFIX += "        ret = function(){return r(val,arguments);}\n";
CONSTANT_PREFIX += "    else ret = function(){return val;}\n";
CONSTANT_PREFIX += "    for(var x = 1; x < arguments.length;x++) {\n";
CONSTANT_PREFIX += "        for(var a in arguments[x])\n";
CONSTANT_PREFIX += "            ret[a] = arguments[x][a];\n";
CONSTANT_PREFIX += "    }\n";
CONSTANT_PREFIX += "    return ret;\n";
CONSTANT_PREFIX += "};\n";
CONSTANT_PREFIX += "return (";
var CONSTANT_SUFFIX = "); }";

var Node = require('./Node');
var processor = require('./processor');

var createSpringMessagesPreprocessor = function(args, config, logger, helper) {
    config = config || {};
    var log = logger.create("preprocessor.spring-messages");
    var defaultOptions = {
        prefix: "", // Used for boilerplate, for example wrap in a define() call
        suffix: ""  // Used for boilerplate, for example, close function calls with );
    };

    var options = helper.merge(defaultOptions, args.options || {}, config.options || {});

    var transformPath = args.transformPath || config.transformPath || function(filepath) {
            return filepath + ".js";
        };

    return function(content, file, done) {
        log.debug("Processing %s", file.originalPath);
        file.path = transformPath(file.originalPath);

        var lines = content.split("\n");

        var tree = processor.process(lines);

        done(null, options.prefix + CONSTANT_PREFIX + Node.render(tree) + CONSTANT_SUFFIX + options.suffix);
    };

};

createSpringMessagesPreprocessor.$inject = ['args', 'config.springMessagesPreprocessor', 'logger', 'helper'];

module.exports = {
    'preprocessor:spring-messages': ["factory", createSpringMessagesPreprocessor]
};<|endoftext|>


<commit_before>module.exports = Traverse;
module.exports.Traverse = Traverse;

function Traverse (obj) {
    if (!(this instanceof Traverse)) return new Traverse(obj);

    this.get = function () { return obj };

    this.modify = function (f) {
        var path = [];
        var parents = [];
        walk(obj);
        return this;

        function walk (node) {
            var state = {
                node : node,
                path : [].concat(path),
                parent : parents.slice(-1)[0],
                key : path.slice(-1)[0],
                isRoot : node == obj,
                update : function (x) {
                    if (state.isRoot) {
                        obj = x;
                    }
                    else {
                        state.parent.node[state.key] = x;
                    }
                    state.node = x;
                },
                level : path.length,
            };
            if (typeof(node) == 'object' && node !== null) {
                state.isLeaf = Object.keys(node).length == 0
            }
            else {
                state.isLeaf = true;
            }

            state.notLeaf = !state.isLeaf;
            state.notRoot = !state.isRoot;

            f.call(state, node);
            if (typeof(state.node) == 'object' && state.node !== null) {
                parents.push(state);
                Object.keys(state.node).forEach(function (key) {
                    path.push(key);
                    walk(state.node[key]);
                    path.pop();
                });
                parents.pop();
            }
        }
    };

    this.forEach = function (f) {
        this.modify(function (node) {
            delete this.update;
            f.call(this,node);
        },null);
        return this;
    };

    this.paths = function () {
        var acc = [];
        this.each(function (x) {
            acc.push(this.path);
        });
        return acc;
    };

    this.nodes = function () {
        var acc = [];
        this.each(function (x) {
            acc.push(this.node);
        });
        return acc;
    };
}
<commit_msg>clone in the constructor so updates don't mess up the root object's refs<commit_after>module.exports = Traverse;
module.exports.Traverse = Traverse;

function Traverse (refObj) {
    if (!(this instanceof Traverse)) return new Traverse(refObj);

    // clone refObj for a properly immutable interface:
    function clone(ref) {
        if (typeof ref == 'object' && ref !== null) {
            var node = ref.constructor();
            Object.keys(ref).forEach(function (key) {
                node[key] = clone(ref[key]);
            });
            return node;
        }
        else {
            return ref;
        }
    }
    var obj = clone(refObj);

    this.get = function () { return obj };

    this.modify = function (f) {
        var path = [];
        var parents = [];
        walk(obj);
        return this;

        function walk (node) {
            var state = {
                node : node,
                path : [].concat(path),
                parent : parents.slice(-1)[0],
                key : path.slice(-1)[0],
                isRoot : node == obj,
                update : function (x) {
                    if (state.isRoot) {
                        obj = x;
                    }
                    else {
                        state.parent.node[state.key] = x;
                    }
                    state.node = x;
                },
                level : path.length,
            };
            if (typeof node == 'object' && node !== null) {
                state.isLeaf = Object.keys(node).length == 0
            }
            else {
                state.isLeaf = true;
            }

            state.notLeaf = !state.isLeaf;
            state.notRoot = !state.isRoot;

            f.call(state, node);
            if (typeof state.node == 'object' && state.node !== null) {
                parents.push(state);
                Object.keys(state.node).forEach(function (key) {
                    path.push(key);
                    walk(state.node[key]);
                    path.pop();
                });
                parents.pop();
            }
        }
    };

    this.forEach = function (f) {
        this.modify(function (node) {
            delete this.update;
            f.call(this,node);
        },null);
        return this;
    };

    this.paths = function () {
        var acc = [];
        this.each(function (x) {
            acc.push(this.path);
        });
        return acc;
    };

    this.nodes = function () {
        var acc = [];
        this.each(function (x) {
            acc.push(this.node);
        });
        return acc;
    };
}
<|endoftext|>


<commit_before>"use strict";

/**
 * Module dependencies.
 */
var APIBase = require("./apibase").APIBase,
	Logger = require("./logging").Logger,
	config = require("../config").Config,
	sys = require("sys"),
	fs = require("fs"),
	StringUtils = require("./stringutils").StringUtils,
	FnUtils = require("./fnutils").FnUtils,
	api;

/**
 * API
 *
 * Creates a new RESTful API wrapper from a schema definition
 *
 * @constructor
 * @param {String} schema
 * @param {String} oauthkey
 * @param {String} oauthsecret
 */
 function Api(schema, oauthkey /*optional*/, oauthsecret /*optional*/) {
	var logger = new Logger(config);

	this.schema = schema;

	logger.log('Building api');
	function createResourceConstructor(resourceName) {
		var logger = logger;
		return function Resource() {
			this.logger = logger;
			this.resourceUrlSlug  = resourceName.toLowerCase();
		};
	}

	for(var prop in schema.resources) {
		if (schema.resources.hasOwnProperty(prop)) {
			var resourceName = schema.resources[prop].resource;

			var resourceConstructor = createResourceConstructor(resourceName);

			resourceConstructor.prototype = new APIBase(resourceName, schema.host, schema.version, oauthkey, oauthsecret);

			schema.resources[prop].actions.forEach(FnUtils.bind(resourceConstructor, resourceConstructor.prototype.buildApiCall));
			this[prop] = resourceConstructor;
		}
	}
}

Api.prototype.getSchema = function() {
	return this.schema;
};

Api.prototype.getResourceClassName = function(resource) {
	for (var resourceName in this.schema.resources) {
		if (this.schema.resources.hasOwnProperty(resourceName)) {
			if (this.schema.resources[resourceName].resource.toLowerCase() === resource.toLowerCase()) {
				return resourceName;
			}
		}
	}

	return '';
};

Api.prototype.getActionMethodName = function(resourceClassName, action) {
	var actionMethodName = '';

	this.schema.resources[resourceClassName].actions.forEach(function(act) {
		if (StringUtils.isAString(act) && act.toLowerCase() === action.toLowerCase()) {
			actionMethodName = 'get' + StringUtils.capitalize(act);
		}
		else if (act.apiCall && act.apiCall.toLowerCase() === action.toLowerCase()) {
			actionMethodName = act.methodName;
		}
	});

	return actionMethodName;
};

Api.build = function(schema, oauthkey /*optional*/, oauthsecret /*optional*/) {
	return new Api(schema, oauthkey, oauthsecret);
};

Api.buildFromFile = function(schemaPath, oauthkey /*optional*/, oauthsecret /*optional*/) {
	// Blocking here but we should only ever do this once and the library is
	// unusable until it has read the schema.
	var schemaText = fs.readFileSync(schemaPath),
		schema = JSON.parse(schemaText.toString());

	return new Api(schema, oauthkey, oauthsecret);
};

exports.Api = Api;
<commit_msg>Removed superfluous logging when build the api wrapper<commit_after>"use strict";

/**
 * Module dependencies.
 */
var APIBase = require("./apibase").APIBase,
	sys = require("sys"),
	fs = require("fs"),
	StringUtils = require("./stringutils").StringUtils,
	FnUtils = require("./fnutils").FnUtils,
	api;

/**
 * API
 *
 * Creates a new RESTful API wrapper from a schema definition
 *
 * @constructor
 * @param {String} schema
 * @param {String} oauthkey
 * @param {String} oauthsecret
 */
 function Api(schema, oauthkey /*optional*/, oauthsecret /*optional*/) {
	this.schema = schema;

	function createResourceConstructor(resourceName) {
		var logger = logger;
		return function Resource() {
			this.logger = logger;
			this.resourceUrlSlug  = resourceName.toLowerCase();
		};
	}

	for(var prop in schema.resources) {
		if (schema.resources.hasOwnProperty(prop)) {
			var resourceName = schema.resources[prop].resource;

			var resourceConstructor = createResourceConstructor(resourceName);

			resourceConstructor.prototype = new APIBase(resourceName, schema.host, schema.version, oauthkey, oauthsecret);

			schema.resources[prop].actions.forEach(FnUtils.bind(resourceConstructor, resourceConstructor.prototype.buildApiCall));
			this[prop] = resourceConstructor;
		}
	}
}

Api.prototype.getSchema = function() {
	return this.schema;
};

Api.prototype.getResourceClassName = function(resource) {
	for (var resourceName in this.schema.resources) {
		if (this.schema.resources.hasOwnProperty(resourceName)) {
			if (this.schema.resources[resourceName].resource.toLowerCase() === resource.toLowerCase()) {
				return resourceName;
			}
		}
	}

	return '';
};

Api.prototype.getActionMethodName = function(resourceClassName, action) {
	var actionMethodName = '';

	this.schema.resources[resourceClassName].actions.forEach(function(act) {
		if (StringUtils.isAString(act) && act.toLowerCase() === action.toLowerCase()) {
			actionMethodName = 'get' + StringUtils.capitalize(act);
		}
		else if (act.apiCall && act.apiCall.toLowerCase() === action.toLowerCase()) {
			actionMethodName = act.methodName;
		}
	});

	return actionMethodName;
};

Api.build = function(schema, oauthkey /*optional*/, oauthsecret /*optional*/) {
	return new Api(schema, oauthkey, oauthsecret);
};

Api.buildFromFile = function(schemaPath, oauthkey /*optional*/, oauthsecret /*optional*/) {
	// Blocking here but we should only ever do this once and the library is
	// unusable until it has read the schema.
	var schemaText = fs.readFileSync(schemaPath),
		schema = JSON.parse(schemaText.toString());

	return new Api(schema, oauthkey, oauthsecret);
};

exports.Api = Api;
<|endoftext|>


<commit_before>var request = require('request')

var API_URL = 'https://api.digitalocean.com/v2/'

var api = {
  call: function (options, callback) {
    options.url = API_URL + options.action
    options.headers = {
      json: true,
      Authorization: 'Bearer ' + options.token
    }

    delete options.action
    delete options.token

    request(options, function (err, res, body) {
      if (err) return callback(err)
      if (res.statusCode >= 400) return callback(JSON.parse(body), body)

      callback(null, body)
    })
  }
}

module.exports = api
<commit_msg>Add Content-Type json to headers<commit_after>var request = require('request')

var API_URL = 'https://api.digitalocean.com/v2/'

var api = {
  call: function (options, callback) {
    options.url = API_URL + options.action
    options.headers = {
      json: true,
      Authorization: 'Bearer ' + options.token,
      "Content-Type": "application/json"
    }

    delete options.action
    delete options.token

    request(options, function (err, res, body) {
      if (err) return callback(err)
      if (res.statusCode >= 400) return callback(JSON.parse(body), body)

      callback(null, body)
    })
  }
}

module.exports = api
<|endoftext|>


<commit_before>var Mongoose = require('mongoose');
var Express = require('express');
var BodyParser = require('body-parser');

var ModuleBuilder = require('./module-builder.js');
var Definition = require('./definition.js');
var SwaggerBuilder = require('./swagger-builder.js');

var MONGO_FIELDS = ['_id', '__v'];
var SELECT = MONGO_FIELDS.map(function(f) {return '-' + f}).join(' ');
var METHODS = ['get', 'patch', 'put', 'post', 'delete'];

var removeMongoFields = function(obj) {
  if (typeof obj !== 'object') return obj;
  else if (Array.isArray(obj)) return obj.map(removeMongoFields);
  else {
    for (key in obj) {
      if (MONGO_FIELDS.indexOf(key) === -1) {
        obj[key] = removeMongoFields(obj[key]);
      } else {
        delete obj[key];
      }
    }
    return obj;
  }
}

var setJamminDefaults = function(req, res, next) {
  if (!req.jammin) {
    req.jammin = {
      query: JSON.parse(JSON.stringify(req.query)),
      document: JSON.parse(JSON.stringify(req.body)),
      arguments: JSON.parse(JSON.stringify(req.body)),
      method: req.method.toLowerCase(),
    }
  }
  for (key in req.params) {
    req.jammin.query[key] = req.params[key];
  }
  next();
}

/** API **/

var API = module.exports = function(options) {
  options = options || {};
  if (typeof options === 'string') options =  {databaseURL: options};
  var self = this;
  self.router = Express.Router();
  self.router.use(BodyParser.json());
  self.moduleBuilder = new ModuleBuilder(self.router);
  METHODS.concat(['use']).forEach(function(method) {
    var origFunc = self.router[method];
    self.router[method] = function() {
      arguments = Array.prototype.slice.call(arguments);
      var insertLoc = 0;
      for (var i = 0; i < arguments.length; ++i) {
        if (typeof arguments[i] === 'function') {
          insertLoc = i;
          break;
        }
      }
      arguments.splice(insertLoc, 0, setJamminDefaults);
      return origFunc.apply(self.router, arguments);
    }
  })
  if (options.databaseURL) {
    self.mongoose = Mongoose.createConnection(options.databaseURL);
  }
  self.swaggerBuilder = new SwaggerBuilder(options.swagger);
}

API.prototype.module = function() {
  this.moduleBuilder.addRoutes.apply(this.moduleBuilder, arguments);
}

API.Schema = Mongoose.Schema;

API.prototype.define = function(label, schema) {
  this.swaggerBuilder.addDefinition(label, schema);
  if (Object.keys(this).indexOf(label) !== -1) {
    throw new Error("Invalid label " + label + "\nLabel is restricted or already defined")
  }
  this[label] = new Definition(this, label, schema);
}

API.prototype.swagger = function() {
  var self = this;
  arguments = Array.prototype.slice.call(arguments);
  var path = arguments[0];
  var middleware = arguments.splice(1);
  var options  = typeof middleware[0] === 'object' ? middleware.shift() : {};
  middleware.unshift(path);
  middleware.push(function(req, res, next) {
    if (req.query.pretty) {
      res.set('Content-Type', 'application/json');
      res.send(JSON.stringify(self.swaggerBuilder.swagger, null, 2));
    } else {
      res.json(self.swaggerBuilder.swagger);
    }
  })
  self.router.get.apply(self.router, middleware);
}

<commit_msg>remove unused code<commit_after>var Mongoose = require('mongoose');
var Express = require('express');
var BodyParser = require('body-parser');

var ModuleBuilder = require('./module-builder.js');
var Definition = require('./definition.js');
var SwaggerBuilder = require('./swagger-builder.js');

var METHODS = ['get', 'patch', 'put', 'post', 'delete'];

var setJamminDefaults = function(req, res, next) {
  if (!req.jammin) {
    req.jammin = {
      query: JSON.parse(JSON.stringify(req.query)),
      document: JSON.parse(JSON.stringify(req.body)),
      arguments: JSON.parse(JSON.stringify(req.body)),
      method: req.method.toLowerCase(),
    }
  }
  for (key in req.params) {
    req.jammin.query[key] = req.params[key];
  }
  next();
}

/** API **/

var API = module.exports = function(options) {
  options = options || {};
  if (typeof options === 'string') options =  {databaseURL: options};
  var self = this;
  self.router = Express.Router();
  self.router.use(BodyParser.json());
  self.moduleBuilder = new ModuleBuilder(self.router);
  METHODS.concat(['use']).forEach(function(method) {
    var origFunc = self.router[method];
    self.router[method] = function() {
      arguments = Array.prototype.slice.call(arguments);
      var insertLoc = 0;
      for (var i = 0; i < arguments.length; ++i) {
        if (typeof arguments[i] === 'function') {
          insertLoc = i;
          break;
        }
      }
      arguments.splice(insertLoc, 0, setJamminDefaults);
      return origFunc.apply(self.router, arguments);
    }
  })
  if (options.databaseURL) {
    self.mongoose = Mongoose.createConnection(options.databaseURL);
  }
  self.swaggerBuilder = new SwaggerBuilder(options.swagger);
}

API.prototype.module = function() {
  this.moduleBuilder.addRoutes.apply(this.moduleBuilder, arguments);
}

API.Schema = Mongoose.Schema;

API.prototype.define = function(label, schema) {
  this.swaggerBuilder.addDefinition(label, schema);
  if (Object.keys(this).indexOf(label) !== -1) {
    throw new Error("Invalid label " + label + "\nLabel is restricted or already defined")
  }
  this[label] = new Definition(this, label, schema);
}

API.prototype.swagger = function() {
  var self = this;
  arguments = Array.prototype.slice.call(arguments);
  var path = arguments[0];
  var middleware = arguments.splice(1);
  var options  = typeof middleware[0] === 'object' ? middleware.shift() : {};
  middleware.unshift(path);
  middleware.push(function(req, res, next) {
    if (req.query.pretty) {
      res.set('Content-Type', 'application/json');
      res.send(JSON.stringify(self.swaggerBuilder.swagger, null, 2));
    } else {
      res.json(self.swaggerBuilder.swagger);
    }
  })
  self.router.get.apply(self.router, middleware);
}

<|endoftext|>


<commit_before>var request = require('request');
var q = require('q');
var _ = require('underscore');

var api = exports = module.exports = {};
var tokenPromise = null;

api.init = function() {
  this.settings = {};
  this.defaultConfiguration();
};

api.defaultConfiguration = function() {
  this.set('tokenEndpoint', 'token');
  this.set('maxLimit', 500);
};

api.urlFor = function(resource, id) {
  var url = this.settings.url + '/' + resource;
  if (id) {
    url = url + '/' + id;
  }

  return url;
};

api.getToken = function() {
  if (!tokenPromise) {
    var deferred = q.defer();
    tokenPromise = deferred.promise;

    request(
      {
        url: this.urlFor(this.settings.tokenEndpoint),
        method: 'POST',
        form: {grant_type: 'client_credentials', client_id: this.settings.clientId, client_secret: this.settings.clientSecret},
        json: true
      },
      resolveResponse(deferred)
    );
  }

  return tokenPromise.get('access_token');
};

api.get = function(resource, id, parameters) {
  return this.getToken().then(_.bind(function(token) {
    var deferred = q.defer();

    request(
      {url: this.urlFor(resource, id), qs: parameters, headers: {'Authorization': 'Bearer ' + token}, json: true},
      resolveResponse(deferred)
    );

    return deferred.promise;
  }, this));
};

api.getResult = function(resource, id, parameters) {
  return this.get(resource, id, parameters).get('result');
};

api.index = function(resource, parameters) {
  return this.getToken().then(_.bind(function(token) {
    var deferred = q.defer();

    request({url: this.urlFor(resource), qs: parameters, headers: {'Authorization': 'Bearer ' + token}, json: true}, resolveResponse(deferred));

    return deferred.promise;
  }, this));
};

api.indexAll = function(resource, parameters) {
  var promises = [];
  promises.push(this.index(resource, _.extend({}, parameters, {offset: 0, limit: this.settings.maxLimit})));
  return promises[0].then(_.bind(function(firstPage) {
    for (var offset = this.settings.maxLimit; offset < firstPage.pagination.total; offset += this.settings.maxLimit) {
      promises.push(this.index(resource, _.extend({}, parameters, {offset: offset, limit: this.settings.maxLimit})));
    }

    return q.all(promises).then(function(pages) {
      return _.flatten(_.pluck(pages, 'result'), true);
    });
  }, this));
};

api.set = function(setting, value) {
  if (arguments.length == 1) {
    return this.settings[setting];
  }

  this.settings[setting] = value;
  return this;
};

function resolveResponse(deferred) {
  return function(error, res, body) {
    if (error) {
      deferred.reject(error);
    } else if (res.statusCode != 200) {
      deferred.reject(body);
    } else {
      deferred.resolve(body);
    }
  };
}
<commit_msg>Handle expired tokens by refetching token with credentials.<commit_after>var request = require('request');
var q = require('q');
var _ = require('underscore');

var api = exports = module.exports = {};
var tokenPromise = null;

api.init = function() {
  this.settings = {};
  this.defaultConfiguration();
};

api.defaultConfiguration = function() {
  this.set('tokenEndpoint', 'token');
  this.set('maxLimit', 500);
};

api.urlFor = function(resource, id) {
  var url = this.settings.url + '/' + resource;
  if (id) {
    url = url + '/' + id;
  }

  return url;
};

api.getToken = function() {
  if (!tokenPromise) {
    var deferred = q.defer();
    tokenPromise = deferred.promise;

    request(
      {
        url: this.urlFor(this.settings.tokenEndpoint),
        method: 'POST',
        form: {grant_type: 'client_credentials', client_id: this.settings.clientId, client_secret: this.settings.clientSecret},
        json: true
      },
      resolveResponse(deferred)
    );
  }

  return tokenPromise.get('access_token');
};

api.get = function(resource, id, parameters) {
  return this.getToken().then(_.bind(function(token) {
    var deferred = q.defer();
    var req = {url: this.urlFor(resource, id), qs: parameters, headers: {'Authorization': 'Bearer ' + token}, json: true};

    request(req, resolveResponse(deferred, this, req));

    return deferred.promise;
  }, this));
};

api.getResult = function(resource, id, parameters) {
  return this.get(resource, id, parameters).get('result');
};

api.index = function(resource, parameters) {
  return this.getToken().then(_.bind(function(token) {
    var deferred = q.defer();
    var req = {url: this.urlFor(resource), qs: parameters, headers: {'Authorization': 'Bearer ' + token}, json: true};

    request(req, resolveResponse(deferred, this, req));

    return deferred.promise;
  }, this));
};

api.indexAll = function(resource, parameters) {
  var promises = [];
  promises.push(this.index(resource, _.extend({}, parameters, {offset: 0, limit: this.settings.maxLimit})));
  return promises[0].then(_.bind(function(firstPage) {
    for (var offset = this.settings.maxLimit; offset < firstPage.pagination.total; offset += this.settings.maxLimit) {
      promises.push(this.index(resource, _.extend({}, parameters, {offset: offset, limit: this.settings.maxLimit})));
    }

    return q.all(promises).then(function(pages) {
      return _.flatten(_.pluck(pages, 'result'), true);
    });
  }, this));
};

api.set = function(setting, value) {
  if (arguments.length == 1) {
    return this.settings[setting];
  }

  this.settings[setting] = value;
  return this;
};

function resolveResponse(deferred, api, req) {
  return function(error, res, body) {
    if (error) {
      deferred.reject(error);
    } else if (api && req && isExpiredToken(res, body)) {
      tokenPromise = null;
      api.getToken().then(_.bind(function(token) {
        req.headers.Authorization = 'Bearer ' + token;
        request(req, resolveResponse(deferred, api, req));
      }, api));
    } else if (res.statusCode != 200) {
      deferred.reject(body);
    } else {
      deferred.resolve(body);
    }
  };
}

function isExpiredToken(res, body) {
  return res.statusCode == 401 && body.error === 'invalid_grant';
}
<|endoftext|>


<commit_before>var request = require('request'),
  xtend = require('xtend'),
  parseLinks = require('parse-links'),
  url = require('url');

var api = module.exports;
var Connection = require('./Connection');

api.getConnections = function(accessToken, done) {
  request.get({
    url: this.apiUrl + '/connections',
    qs: { access_token: accessToken },
    headers: {"Accept": "application/xml"},
  }, function (err, r, body) {
    if (err) { return done(err); }

    if (r.statusCode.toString().substr(0, 1) !== '2'){
      return done(new Error(body));
    }

    try {
      var result = JSON.parse(body).map(function(c) {
        return new Connection(this, accessToken, c);
      });
      done(null, result);
    } catch(e) {
      done(e);
    }
  }.bind(this));
};

api.getSocialConnections = function(accessToken, done) {
  request.get({
    url: this.apiUrl + '/connections',
    qs: { access_token: accessToken, only_socials: true },
    headers: {"Accept": "application/xml"}
  }, function (err, r, body) {
    if (err) { return done(err); }

    if (r.statusCode.toString().substr(0, 1) !== '2'){
      return done(new Error(body));
    }
    try {
      var result = JSON.parse(body).map(function(c) {
        return new Connection(this, accessToken, c);
      });
      done(null, result);
    } catch(e) {
      done(e);
    }
  }.bind(this));
};

api.getEnterpriseConnections = function(accessToken, done) {
  request.get({
    url: this.apiUrl + '/connections',
    qs: {
      access_token: accessToken,
      only_enterprise: true
    },
    headers: {"Accept": "application/xml"}
  }, function (err, r, body) {
    if (err) { return done(err); }

    if (r.statusCode.toString().substr(0, 1) !== '2'){
      return done(new Error(body));
    }
    try {
      var result = JSON.parse(body).map(function(c) {
        return new Connection(this, accessToken, c);
      });
      done(null, result);
    } catch(e) {
      done(e);
    }
  }.bind(this));
};

api.getSocialUsers = function (accessToken, options, done) {
  if(typeof options === 'function'){
    done = options;
    options = {};
  }
  options = xtend({social: true}, options);
  return api.getUsers.bind(this)(accessToken, options, done);
};

api.getEnterpriseUsers = function (accessToken, options, done) {
  if(typeof options === 'function'){
    done = options;
    options = {};
  }
  options = xtend({social: false}, options);
  return api.getUsers.bind(this)(accessToken, options, done);
};

api.getUsers = function(accessToken, options, done) {
  var nextPageLink, req, connection;

  if(typeof options === 'function'){
    done = options;
    options = {};
  }else{
    options = options || {};
    if(options.perPage){
      options.per_page = options.perPage;
      delete options.perPage;
    }
    if(options.page){
      nextPageLink = options.page;
      delete options.page;
    }
    if(options.connection){
      connection = options.connection;
      delete options.connection;
    }
  }

  if(nextPageLink){
    req = { url: url.parse(nextPageLink) };
  }else {
    req = { qs: xtend({ access_token: accessToken }, options) };
    if (connection) {
      req.url = this.apiUrl + '/connections/' + connection + '/users';
    } else if (options.social) {
      req.url = this.apiUrl + '/socialconnections/users';
      delete options.social;
    } else if (options.social === false) {
      req.url = this.apiUrl + '/enterpriseconnections/users';
      delete options.social;
    } else {
      req.url = this.apiUrl + '/users';
    }
  }

  request.get(req, function (err, r, body) {
    if (err) return done(err);

    if (r.statusCode.toString().substr(0, 1) !== '2'){
      return done(new Error(body));
    }

    try {
      var results = JSON.parse(body);
      if(r.headers.link){

        var links = parseLinks(r.headers.link);

        if(links.next){
          Object.defineProperty(results, 'nextPageLink' , {
            enumerable: false,
            writeable: false,
            value: links.next
          });
        }

      }
      done(null, results);
    } catch(e) {
      done(e);
    }

  });
};

api.updateTemplate = function (accessToken, strategy, options, done) {
  request.put({
    url: this.apiUrl + '/connection-templates/' + strategy,
    qs: { access_token: accessToken },
    json: options
  }, function (err, r, body) {
    if (err) return done(err);
    if(r.statusCode === 400) {
      return done(new Error(body.detail || body));
    }
    if (r.statusCode.toString().substr(0, 1) !== '2') return done(new Error(body));
    done();
  });
};

api.getTemplate = function (accessToken, strategy, done) {
  request.get({
    url: this.apiUrl + '/connection-templates/' + strategy,
    qs: { access_token: accessToken }
  }, function (err, r, body) {
    if (err) return done(err);
    if (r.statusCode.toString().substr(0, 1) !== '2') return done(new Error(body));
    done(null, JSON.parse(body));
  });
};

api.getStrategies = function (accessToken, done) {
  request.get({
    url: this.apiUrl + '/strategies',
    qs: { access_token: accessToken }
  }, function (err, r, body) {
    if (err) return done(err);
    if (r.statusCode.toString().substr(0, 1) !== '2') return done(new Error(body));
    done(null, JSON.parse(body));
  });
};

api.getConnection = function(accessToken, name, done) {
  request.get({
    url: this.apiUrl + '/connections/' + name,
    qs: { access_token: accessToken }
  }, function (err, r, body) {
    if (err) return done(err);
    if (r.statusCode === 404) return done(null, null);
    if (r.statusCode.toString().substr(0, 1) !== '2') return done(new Error(body));

    try {
      var data = JSON.parse(body);
      var connection = new Connection(this, accessToken, data);
      done(null, connection);
    } catch(e) {
      done(e);
    }
  }.bind(this));
};

api.createConnection = function (accessToken, connection, done) {
  request.post({
    url:  this.apiUrl + '/connections',
    qs:   { access_token: accessToken },
    json: connection
  }, function (err, r, body) {
    if (err) { return done(err); }
    if(r.statusCode === 400) {
      return done(new Error(body.detail || body));
    }
    done(null, body);
  });
};

api.deleteConnection = function(accessToken, name, done)
{
  request.del({
    url: this.apiUrl + '/connections/' + name,
    qs: { access_token: accessToken }
  }, function (err, r, body) {
    if (err) return done(err);
    if (r.statusCode === 404) return done(null, null);
    if (r.statusCode.toString().substr(0, 1) !== '2') return done(new Error(body));

    try {
      var data = JSON.parse(body);
      done(null, data);
    } catch(e) {
      done(e);
    }
  }.bind(this));
};

api.updateConnection = function (accessToken, connection, done) {
  request.put({
    url:  this.apiUrl + '/connections/' + connection.name,
    qs:   { access_token: accessToken },
    json: connection
  }, function (err, r, body) {
    if (err) { return done(err); }
    if(r.statusCode === 400) {
      return done(new Error(body.detail || body));
    }
    done(null, body);
  });
};

api.deleteTenant = function (accessToken, name, done) {
  request.del({
    url: this.apiUrl + '/tenants/' + name,
    qs: { access_token: accessToken }
  }, function (err, r, body) {
    if (err) return done(err);
    if (r.statusCode === 404) return done(null, null);
    if (r.statusCode.toString().substr(0, 1) !== '2') return done(new Error(body));
    done();
  }.bind(this));
};

api.createClient = function (accessToken, options, done) {
  request.post({
    url:  this.apiUrl + '/clients',
    qs:   { access_token: accessToken },
    json: options
  }, function (err, r, body) {
    if (err) { return done(err); }
    if (r.statusCode === 400) {
      return done(new Error(body.detail || body));
    }

    done(null, body);
  });
};

api.deleteClient = function (accessToken, name, done) {
  request.del({
    url: this.apiUrl + '/tenants/' + name,
    qs: { access_token: accessToken }
  }, function (err, r, body) {
    if (err) return done(err);
    if (r.statusCode === 404) return done(null, null);
    if (r.statusCode.toString().substr(0, 1) !== '2') return done(new Error(body));
    done();
  }.bind(this));
};

api.getClients = function (accessToken, clientID, done) {
  if (typeof clientID === 'function') {
    done = clientID;
    clientID = '';
  }

  request.get({
    url: this.apiUrl + '/clients/' + clientID,
    qs: { access_token: accessToken }
  }, function (err, r, body) {
    if (err) return done(err);
    if (r.statusCode.toString().substr(0, 1) !== '2') return done(new Error(body));
    done(null, JSON.parse(body));
  });
};

api.getClientsByUserId = function (accessToken, userId, done) {
  request.get({
    url: this.apiUrl + '/clients/?userId=' + userId,
    qs: { access_token: accessToken }
  }, function (err, r, body) {
    if (err) return done(err);
    if (r.statusCode.toString().substr(0, 1) !== '2') return done(new Error(body));
    done(null, JSON.parse(body));
  });
};
<commit_msg>deleteClient method<commit_after>var request = require('request'),
  xtend = require('xtend'),
  parseLinks = require('parse-links'),
  url = require('url');

var api = module.exports;
var Connection = require('./Connection');

api.getConnections = function(accessToken, done) {
  request.get({
    url: this.apiUrl + '/connections',
    qs: { access_token: accessToken },
    headers: {"Accept": "application/xml"},
  }, function (err, r, body) {
    if (err) { return done(err); }

    if (r.statusCode.toString().substr(0, 1) !== '2'){
      return done(new Error(body));
    }

    try {
      var result = JSON.parse(body).map(function(c) {
        return new Connection(this, accessToken, c);
      });
      done(null, result);
    } catch(e) {
      done(e);
    }
  }.bind(this));
};

api.getSocialConnections = function(accessToken, done) {
  request.get({
    url: this.apiUrl + '/connections',
    qs: { access_token: accessToken, only_socials: true },
    headers: {"Accept": "application/xml"}
  }, function (err, r, body) {
    if (err) { return done(err); }

    if (r.statusCode.toString().substr(0, 1) !== '2'){
      return done(new Error(body));
    }
    try {
      var result = JSON.parse(body).map(function(c) {
        return new Connection(this, accessToken, c);
      });
      done(null, result);
    } catch(e) {
      done(e);
    }
  }.bind(this));
};

api.getEnterpriseConnections = function(accessToken, done) {
  request.get({
    url: this.apiUrl + '/connections',
    qs: {
      access_token: accessToken,
      only_enterprise: true
    },
    headers: {"Accept": "application/xml"}
  }, function (err, r, body) {
    if (err) { return done(err); }

    if (r.statusCode.toString().substr(0, 1) !== '2'){
      return done(new Error(body));
    }
    try {
      var result = JSON.parse(body).map(function(c) {
        return new Connection(this, accessToken, c);
      });
      done(null, result);
    } catch(e) {
      done(e);
    }
  }.bind(this));
};

api.getSocialUsers = function (accessToken, options, done) {
  if(typeof options === 'function'){
    done = options;
    options = {};
  }
  options = xtend({social: true}, options);
  return api.getUsers.bind(this)(accessToken, options, done);
};

api.getEnterpriseUsers = function (accessToken, options, done) {
  if(typeof options === 'function'){
    done = options;
    options = {};
  }
  options = xtend({social: false}, options);
  return api.getUsers.bind(this)(accessToken, options, done);
};

api.getUsers = function(accessToken, options, done) {
  var nextPageLink, req, connection;

  if(typeof options === 'function'){
    done = options;
    options = {};
  }else{
    options = options || {};
    if(options.perPage){
      options.per_page = options.perPage;
      delete options.perPage;
    }
    if(options.page){
      nextPageLink = options.page;
      delete options.page;
    }
    if(options.connection){
      connection = options.connection;
      delete options.connection;
    }
  }

  if(nextPageLink){
    req = { url: url.parse(nextPageLink) };
  }else {
    req = { qs: xtend({ access_token: accessToken }, options) };
    if (connection) {
      req.url = this.apiUrl + '/connections/' + connection + '/users';
    } else if (options.social) {
      req.url = this.apiUrl + '/socialconnections/users';
      delete options.social;
    } else if (options.social === false) {
      req.url = this.apiUrl + '/enterpriseconnections/users';
      delete options.social;
    } else {
      req.url = this.apiUrl + '/users';
    }
  }

  request.get(req, function (err, r, body) {
    if (err) return done(err);

    if (r.statusCode.toString().substr(0, 1) !== '2'){
      return done(new Error(body));
    }

    try {
      var results = JSON.parse(body);
      if(r.headers.link){

        var links = parseLinks(r.headers.link);

        if(links.next){
          Object.defineProperty(results, 'nextPageLink' , {
            enumerable: false,
            writeable: false,
            value: links.next
          });
        }

      }
      done(null, results);
    } catch(e) {
      done(e);
    }

  });
};

api.updateTemplate = function (accessToken, strategy, options, done) {
  request.put({
    url: this.apiUrl + '/connection-templates/' + strategy,
    qs: { access_token: accessToken },
    json: options
  }, function (err, r, body) {
    if (err) return done(err);
    if(r.statusCode === 400) {
      return done(new Error(body.detail || body));
    }
    if (r.statusCode.toString().substr(0, 1) !== '2') return done(new Error(body));
    done();
  });
};

api.getTemplate = function (accessToken, strategy, done) {
  request.get({
    url: this.apiUrl + '/connection-templates/' + strategy,
    qs: { access_token: accessToken }
  }, function (err, r, body) {
    if (err) return done(err);
    if (r.statusCode.toString().substr(0, 1) !== '2') return done(new Error(body));
    done(null, JSON.parse(body));
  });
};

api.getStrategies = function (accessToken, done) {
  request.get({
    url: this.apiUrl + '/strategies',
    qs: { access_token: accessToken }
  }, function (err, r, body) {
    if (err) return done(err);
    if (r.statusCode.toString().substr(0, 1) !== '2') return done(new Error(body));
    done(null, JSON.parse(body));
  });
};

api.getConnection = function(accessToken, name, done) {
  request.get({
    url: this.apiUrl + '/connections/' + name,
    qs: { access_token: accessToken }
  }, function (err, r, body) {
    if (err) return done(err);
    if (r.statusCode === 404) return done(null, null);
    if (r.statusCode.toString().substr(0, 1) !== '2') return done(new Error(body));

    try {
      var data = JSON.parse(body);
      var connection = new Connection(this, accessToken, data);
      done(null, connection);
    } catch(e) {
      done(e);
    }
  }.bind(this));
};

api.createConnection = function (accessToken, connection, done) {
  request.post({
    url:  this.apiUrl + '/connections',
    qs:   { access_token: accessToken },
    json: connection
  }, function (err, r, body) {
    if (err) { return done(err); }
    if(r.statusCode === 400) {
      return done(new Error(body.detail || body));
    }
    done(null, body);
  });
};

api.deleteConnection = function(accessToken, name, done)
{
  request.del({
    url: this.apiUrl + '/connections/' + name,
    qs: { access_token: accessToken }
  }, function (err, r, body) {
    if (err) return done(err);
    if (r.statusCode === 404) return done(null, null);
    if (r.statusCode.toString().substr(0, 1) !== '2') return done(new Error(body));

    try {
      var data = JSON.parse(body);
      done(null, data);
    } catch(e) {
      done(e);
    }
  }.bind(this));
};

api.updateConnection = function (accessToken, connection, done) {
  request.put({
    url:  this.apiUrl + '/connections/' + connection.name,
    qs:   { access_token: accessToken },
    json: connection
  }, function (err, r, body) {
    if (err) { return done(err); }
    if(r.statusCode === 400) {
      return done(new Error(body.detail || body));
    }
    done(null, body);
  });
};

api.deleteTenant = function (accessToken, name, done) {
  request.del({
    url: this.apiUrl + '/tenants/' + name,
    qs: { access_token: accessToken }
  }, function (err, r, body) {
    if (err) return done(err);
    if (r.statusCode === 404) return done(null, null);
    if (r.statusCode.toString().substr(0, 1) !== '2') return done(new Error(body));
    done();
  }.bind(this));
};

api.createClient = function (accessToken, options, done) {
  request.post({
    url:  this.apiUrl + '/clients',
    qs:   { access_token: accessToken },
    json: options
  }, function (err, r, body) {
    if (err) { return done(err); }
    if (r.statusCode === 400) {
      return done(new Error(body.detail || body));
    }

    done(null, body);
  });
};

api.deleteClient = function (accessToken, clientID, done) {
  request.del({
    url: this.apiUrl + '/clients/' + clientID,
    qs: { access_token: accessToken }
  }, function (err, r, body) {
    if (err) return done(err);
    if (r.statusCode === 404) return done();
    if (r.statusCode.toString().substr(0, 1) !== '2') return done(new Error(body));
    done();
  }.bind(this));
};

api.getClients = function (accessToken, clientID, done) {
  if (typeof clientID === 'function') {
    done = clientID;
    clientID = '';
  }

  request.get({
    url: this.apiUrl + '/clients/' + clientID,
    qs: { access_token: accessToken }
  }, function (err, r, body) {
    if (err) return done(err);
    if (r.statusCode.toString().substr(0, 1) !== '2') return done(new Error(body));
    done(null, JSON.parse(body));
  });
};

api.getClientsByUserId = function (accessToken, userId, done) {
  request.get({
    url: this.apiUrl + '/clients/?userId=' + userId,
    qs: { access_token: accessToken }
  }, function (err, r, body) {
    if (err) return done(err);
    if (r.statusCode.toString().substr(0, 1) !== '2') return done(new Error(body));
    done(null, JSON.parse(body));
  });
};
<|endoftext|>


<commit_before>/**
 * @copyright Copyright © 2016 Medalia, Inc. All rights reserved.
 * @license Licensed under the MIT License (MIT).
 */

'use strict';

const request = require('request');
const config = require('nconf');
const fs = require('fs');
const path = require('path');
const strformat = require('strformat');

const sendMessage = (data, context) => {
    var message = strformat('' + data, context);
    var body = config.get('req-body');
    body.message = message;
    request.post(
        'http://api.hipchat.com/v2/room/' + config.get('settings:room') + '/notification?auth_token=' + config.get('settings:api-token'),
        (err, response, body) => {
            if (err) console.log(err);
            console.log(body);
        }
    ).form(body);
};

module.exports = (configFileOrObject, fileOrMessage, context) => {
    config.argv()
        .env()
        .file({ file: configFileOrObject})
        .defaults(configFileOrObject);

    if (!fs.existsSync(fileOrMessage)) {
        sendMessage(fileOrMessage, context);
    } else {
        fs.readFile(fileOrMessage, (err, data) => {
            if (err) throw err;
            sendMessage(data, context);
        });
    }
};
<commit_msg>bug fixing<commit_after>/**
 * @copyright Copyright © 2016 Medalia, Inc. All rights reserved.
 * @license Licensed under the MIT License (MIT).
 */

'use strict';

const request = require('request');
const nconf = require('nconf');
const fs = require('fs');
const path = require('path');
const strformat = require('strformat');
const util = require('util');

const sendMessage = (data, context) => {
    var message = strformat('' + data, context);
    var body = config.get('req-body');
    body.message = message;
    request.post(
        'http://api.hipchat.com/v2/room/' + nconfg.get('settings:room') + '/notification?auth_token=' nconf.get('settings:api-token'),
        (err, response, body) => {
            if (err) console.log(err);
            console.log(body);
        }
    ).form(body);
};

const fileExist = (file) => {
    return fs.existsSync(file);
};

module.exports = (configFileOrObject, fileOrMessage, context) => {
    var config = nconf.argv().env();
    if (fileExist(configFileOrObject)) {
        config.file({ file: configFileOrObject})
    } else if (util.isObject(configFileOrObject)) {
        config.defaults(configFileOrObject);
    } else {
        throw new Error("Illegal argument, expected a file path or a json Object");
    }

    if (!fileExist(fileOrMessage)) {
        sendMessage(fileOrMessage, context);
    } else {
        fs.readFile(fileOrMessage, (err, data) => {
            if (err) throw err;
            sendMessage(data, context);
        });
    }
};
<|endoftext|>