<commit_before>import test from 'ava';

const objc = require('./src/index.js');

test('string creation', t => {
  const NSString = objc.NSString;
  const string = NSString.stringWithString_('Hello World');
  t.is(String(string), 'Hello World');
});

test('primitive return values', t => {
  const NSString = objc.NSString;
  const string = NSString.stringWithString_('I am the doctor');
  const length = string.length();
  t.is(length, 15);
  t.is(typeof length, 'number');
});

test('load constant directly from `objc` module', t => {
  objc.import('AppKit');
  const NSFontAttributeName = objc.NSFontAttributeName;

  t.is(NSFontAttributeName, 'NSFont');
});

test('load constant w/out bundle', t => {
  objc.import('AppKit');
  const NSFontAttributeName = objc.constant('NSFontAttributeName');

  t.is(NSFontAttributeName, 'NSFont');
});

test('load constant w/ bundle', t => {
  objc.import('AppKit');
  const NSFontAttributeName = objc.constant('NSFontAttributeName', 'AppKit');

  t.is(NSFontAttributeName, 'NSFont');
});

test('load constant w/ full bundle name', t => {
  objc.import('AppKit');
  const NSFontAttributeName = objc.constant('NSFontAttributeName', 'com.apple.AppKit');

  t.is(NSFontAttributeName, 'NSFont');
});

test('get username using NSProcessInfo, convert to javascript string and compare the value to the username given by `os.userInfo()`', t => {
  const NSProcessInfo = objc.NSProcessInfo;
  const os = require('os');

  const processInfo = NSProcessInfo.processInfo();
  const username = processInfo.userName();

  t.is(String(username), os.userInfo().username);
});

test('primitive argument types', t => {
  const NSNumber = objc.NSNumber;

  const number = NSNumber.numberWithInt_(5);

  t.is(Number(number), 5);
});

test('inout parameters 1 (^@)', t => {
  const NSFileManager = objc.NSFileManager;
  const fm = NSFileManager.defaultManager();

  const filepath = '/Library/Caches/randomfilenamethatsurelydoesntexust.hey';
  fm.createFileAtPath_contents_attributes_(filepath, null, null);

  const error1 = objc.ref(null);
  const success1 = fm.removeItemAtPath_error_(filepath, error1);

  t.is(success1, true);
  t.is(typeof objc.deref(error1), 'undefined');

  const error2 = objc.ref(null);
  const success2 = fm.removeItemAtPath_error_(filepath, error2);

  t.is(success2, false);
  t.is(typeof objc.deref(error2), 'object');
});

test('inout parameters 2 (^@)', t => {
  const NSDictionary = objc.NSDictionary;
  const NSAppleScript = objc.NSAppleScript;
  const source = 'telll application "Safari" to get URL of current tab of window 1';

  const script = NSAppleScript.alloc().initWithSource_(source);

  const error = objc.ref(null);
  const success = script.compileAndReturnError_(error);

  t.is(success, false);
  t.is(objc.deref(error).isKindOfClass_(NSDictionary), true);
});

test('Automatic array conversion (JS array -> NSArray)', t => {
  const NSArray = objc.NSArray;

  const inputArray = ['I', 'am', 'the', 'doctor'];
  const array = NSArray.arrayWithArray_(inputArray);

  inputArray.forEach((object, index) => {
    const str1 = String(object);
    const str2 = String(array.objectAtIndex_(index));
    t.is(str1, str2);
  });
});

test('Iterate over a NSArray', t => {
  const NSArray = objc.NSArray;

  const inputArray = ['hey', 'missy', 'you', 'so', 'fine'];
  const array = NSArray.arrayWithArray_(inputArray);

  for (const element of array) {
    const index = inputArray.indexOf(String(element));
    inputArray.splice(index, 1);
  }

  t.is(inputArray.length, 0);
});

test('Test calling methods that contain underscores', t => {
  const NSDate = objc.NSDate;

  const now = NSDate.date();
  const web_RFC1123DateString = now._web_RFC1123DateString(); // eslint-disable-line camelcase

  t.is(typeof web_RFC1123DateString, 'object'); // eslint-disable-line camelcase
  t.is(web_RFC1123DateString.isKindOfClass_('NSString'), true); // eslint-disable-line camelcase
});

test('Test possible selectors for 0 underscores', t => {
  const possibleSelectors = require('./src/possible-selectors');

  const selectors = ['date'];

  possibleSelectors('date').forEach((_, index) => {
    selectors.splice(index, 1);
  });

  t.is(selectors.length, 0);
});

test('Test possible selectors for 1 underscore', t => {
  const possibleSelectors = require('./src/possible-selectors');

  const selectors = [
    'performAction:',
    'performAction_'
  ];

  possibleSelectors('performAction_').forEach(sel => {
    const index = selectors.indexOf(sel);
    selectors.splice(index, 1);
  });

  t.is(selectors.length, 0);
});

test('Test possible selectors for 2 underscores', t => {
  const possibleSelectors = require('./src/possible-selectors');

  const selectors = [
    'performAction_withObject_',
    'performAction:withObject_',
    'performAction_withObject:',
    'performAction:withObject:'
  ];

  possibleSelectors('performAction_withObject_').forEach(sel => {
    const index = selectors.indexOf(sel);
    selectors.splice(index, 1);
  });

  t.is(selectors.length, 0);
});

test('Test possible selectors for 3 underscores', t => {
  const possibleSelectors = require('./src/possible-selectors');

  const selectors = [
    'performAction:withObject_afterDelay:',
    'performAction:withObject_afterDelay_',
    'performAction:withObject:afterDelay_',
    'performAction_withObject:afterDelay:',
    'performAction_withObject:afterDelay_',
    'performAction_withObject_afterDelay:',
    'performAction:withObject:afterDelay:',
    'performAction_withObject_afterDelay_'
  ];

  possibleSelectors('performAction_withObject_afterDelay_').forEach(sel => {
    const index = selectors.indexOf(sel);
    selectors.splice(index, 1);
  });

  t.is(selectors.length, 0);
});

test('Test possible selectors for method with leading underscore and no other underscores', t => {
  const possibleSelectors = require('./src/possible-selectors');

  const selectors = [
    '_dateString',
    '_dateString'
  ];

  possibleSelectors('_dateString').forEach(sel => {
    const index = selectors.indexOf(sel);
    selectors.splice(index, 1);
  });

  t.is(selectors.length, 0);
});

test('Test possible selectors for method with leading underscore and other underscores', t => {
  const possibleSelectors = require('./src/possible-selectors');

  const selectors = [
    '_dateStringForTimeZone_',
    '_dateStringForTimeZone:',
    ':dateStringForTimeZone_',
    ':dateStringForTimeZone:'
  ];

  possibleSelectors('_dateStringForTimeZone_').forEach(sel => {
    const index = selectors.indexOf(sel);
    selectors.splice(index, 1);
  });

  t.is(selectors.length, 0);
});

test('description of method proxy', t => {
  const util = require('util');
  const NSDate = objc.NSDate;

  const dateMethod = NSDate.date;
  const description = util.inspect(dateMethod);

  t.is(description, '[objc.MethodProxy for date]');
});
<commit_msg>[test] class/instance proxy descriptions<commit_after>import test from 'ava';

const objc = require('./src/index.js');

test('string creation', t => {
  const NSString = objc.NSString;
  const string = NSString.stringWithString_('Hello World');
  t.is(String(string), 'Hello World');
});

test('primitive return values', t => {
  const NSString = objc.NSString;
  const string = NSString.stringWithString_('I am the doctor');
  const length = string.length();
  t.is(length, 15);
  t.is(typeof length, 'number');
});

test('load constant directly from `objc` module', t => {
  objc.import('AppKit');
  const NSFontAttributeName = objc.NSFontAttributeName;

  t.is(NSFontAttributeName, 'NSFont');
});

test('load constant w/out bundle', t => {
  objc.import('AppKit');
  const NSFontAttributeName = objc.constant('NSFontAttributeName');

  t.is(NSFontAttributeName, 'NSFont');
});

test('load constant w/ bundle', t => {
  objc.import('AppKit');
  const NSFontAttributeName = objc.constant('NSFontAttributeName', 'AppKit');

  t.is(NSFontAttributeName, 'NSFont');
});

test('load constant w/ full bundle name', t => {
  objc.import('AppKit');
  const NSFontAttributeName = objc.constant('NSFontAttributeName', 'com.apple.AppKit');

  t.is(NSFontAttributeName, 'NSFont');
});

test('get username using NSProcessInfo, convert to javascript string and compare the value to the username given by `os.userInfo()`', t => {
  const NSProcessInfo = objc.NSProcessInfo;
  const os = require('os');

  const processInfo = NSProcessInfo.processInfo();
  const username = processInfo.userName();

  t.is(String(username), os.userInfo().username);
});

test('primitive argument types', t => {
  const NSNumber = objc.NSNumber;

  const number = NSNumber.numberWithInt_(5);

  t.is(Number(number), 5);
});

test('inout parameters 1 (^@)', t => {
  const NSFileManager = objc.NSFileManager;
  const fm = NSFileManager.defaultManager();

  const filepath = '/Library/Caches/randomfilenamethatsurelydoesntexust.hey';
  fm.createFileAtPath_contents_attributes_(filepath, null, null);

  const error1 = objc.ref(null);
  const success1 = fm.removeItemAtPath_error_(filepath, error1);

  t.is(success1, true);
  t.is(typeof objc.deref(error1), 'undefined');

  const error2 = objc.ref(null);
  const success2 = fm.removeItemAtPath_error_(filepath, error2);

  t.is(success2, false);
  t.is(typeof objc.deref(error2), 'object');
});

test('inout parameters 2 (^@)', t => {
  const NSDictionary = objc.NSDictionary;
  const NSAppleScript = objc.NSAppleScript;
  const source = 'telll application "Safari" to get URL of current tab of window 1';

  const script = NSAppleScript.alloc().initWithSource_(source);

  const error = objc.ref(null);
  const success = script.compileAndReturnError_(error);

  t.is(success, false);
  t.is(objc.deref(error).isKindOfClass_(NSDictionary), true);
});

test('Automatic array conversion (JS array -> NSArray)', t => {
  const NSArray = objc.NSArray;

  const inputArray = ['I', 'am', 'the', 'doctor'];
  const array = NSArray.arrayWithArray_(inputArray);

  inputArray.forEach((object, index) => {
    const str1 = String(object);
    const str2 = String(array.objectAtIndex_(index));
    t.is(str1, str2);
  });
});

test('Iterate over a NSArray', t => {
  const NSArray = objc.NSArray;

  const inputArray = ['hey', 'missy', 'you', 'so', 'fine'];
  const array = NSArray.arrayWithArray_(inputArray);

  for (const element of array) {
    const index = inputArray.indexOf(String(element));
    inputArray.splice(index, 1);
  }

  t.is(inputArray.length, 0);
});

test('Test calling methods that contain underscores', t => {
  const NSDate = objc.NSDate;

  const now = NSDate.date();
  const web_RFC1123DateString = now._web_RFC1123DateString(); // eslint-disable-line camelcase

  t.is(typeof web_RFC1123DateString, 'object'); // eslint-disable-line camelcase
  t.is(web_RFC1123DateString.isKindOfClass_('NSString'), true); // eslint-disable-line camelcase
});

test('Test possible selectors for 0 underscores', t => {
  const possibleSelectors = require('./src/possible-selectors');

  const selectors = ['date'];

  possibleSelectors('date').forEach((_, index) => {
    selectors.splice(index, 1);
  });

  t.is(selectors.length, 0);
});

test('Test possible selectors for 1 underscore', t => {
  const possibleSelectors = require('./src/possible-selectors');

  const selectors = [
    'performAction:',
    'performAction_'
  ];

  possibleSelectors('performAction_').forEach(sel => {
    const index = selectors.indexOf(sel);
    selectors.splice(index, 1);
  });

  t.is(selectors.length, 0);
});

test('Test possible selectors for 2 underscores', t => {
  const possibleSelectors = require('./src/possible-selectors');

  const selectors = [
    'performAction_withObject_',
    'performAction:withObject_',
    'performAction_withObject:',
    'performAction:withObject:'
  ];

  possibleSelectors('performAction_withObject_').forEach(sel => {
    const index = selectors.indexOf(sel);
    selectors.splice(index, 1);
  });

  t.is(selectors.length, 0);
});

test('Test possible selectors for 3 underscores', t => {
  const possibleSelectors = require('./src/possible-selectors');

  const selectors = [
    'performAction:withObject_afterDelay:',
    'performAction:withObject_afterDelay_',
    'performAction:withObject:afterDelay_',
    'performAction_withObject:afterDelay:',
    'performAction_withObject:afterDelay_',
    'performAction_withObject_afterDelay:',
    'performAction:withObject:afterDelay:',
    'performAction_withObject_afterDelay_'
  ];

  possibleSelectors('performAction_withObject_afterDelay_').forEach(sel => {
    const index = selectors.indexOf(sel);
    selectors.splice(index, 1);
  });

  t.is(selectors.length, 0);
});

test('Test possible selectors for method with leading underscore and no other underscores', t => {
  const possibleSelectors = require('./src/possible-selectors');

  const selectors = [
    '_dateString',
    '_dateString'
  ];

  possibleSelectors('_dateString').forEach(sel => {
    const index = selectors.indexOf(sel);
    selectors.splice(index, 1);
  });

  t.is(selectors.length, 0);
});

test('Test possible selectors for method with leading underscore and other underscores', t => {
  const possibleSelectors = require('./src/possible-selectors');

  const selectors = [
    '_dateStringForTimeZone_',
    '_dateStringForTimeZone:',
    ':dateStringForTimeZone_',
    ':dateStringForTimeZone:'
  ];

  possibleSelectors('_dateStringForTimeZone_').forEach(sel => {
    const index = selectors.indexOf(sel);
    selectors.splice(index, 1);
  });

  t.is(selectors.length, 0);
});

test('description of class proxy', t => {
  const util = require('util');
  const NSDate = objc.NSDate;

  const description = util.inspect(NSDate);

  t.is(description, '[objc.ClassProxy NSDate]');
});

test('description of instance proxy', t => {
  const util = require('util');
  const string = objc.NSString.stringWithString_('the north remembers');

  const description = util.inspect(string);

  t.is(description, '[objc.InstanceProxy the north remembers]');
});

test('description of method proxy', t => {
  const util = require('util');
  const NSDate = objc.NSDate;

  const dateMethod = NSDate.date;
  const description = util.inspect(dateMethod);

  t.is(description, '[objc.MethodProxy for date]');
});
<|endoftext|>


<commit_before>"use strict";

const chai           = require( "chai" );
const chaiAsPromised = require( "chai-as-promised" );
const crypto         = require( "crypto" );
const expect         = chai.expect;

chai.use( chaiAsPromised );

describe( "reject-error", () => {
	const rejectError = require( "." );

	describe( "rejections", () => {
		it( "subject throws", () => {

			function subject() {
				throw new Error();
			}

			return expect( rejectError( subject ) ).to.eventually.be.rejected;
		} );
		it( "subject rejects", () => {

			function subject() {
				return Promise.reject( new Error() );
			}

			return expect( rejectError( subject ) ).to.eventually.be.rejected;
		} );
		it( "subject rejects with Bluebird", () => {

			function subject() {
				const Bluebird = require( "bluebird" );
				return Bluebird.reject( new Error() );
			}

			return expect( rejectError( subject ) ).to.eventually.be.rejected;
		} );
	} );

	describe( "resolutions", () => {
		it( "subject returns", () => {

			function subject() {
				return "foo";
			}

			return expect( rejectError( subject ) ).to.eventually.equal( "foo" );
		} );
		it( "subject resolves", () => {

			function subject() {
				return Promise.resolve( "foo" );
			}

			return expect( rejectError( subject ) ).to.eventually.equal( "foo" );
		} );
	} );

	describe( "bindings", () => {
		it( "uses correct this", () => {
			function subject() {
				return this.foo;
			}

			return expect( rejectError( subject ) ).to.eventually.be.rejected;
		} );

		it( "uses correct this", () => {
			const binding = {
				foo : "bar"
			};

			function subject() {
				return this.foo;
			}

			return expect( rejectError( subject, binding ) ).to.eventually.equal( "bar" );
		} );
	} );

	describe( "arguments", () => {
		it.only( "passes all arguments", () => {
			function subject( a, b, c ) {
				return a + b + c;
			}

			return expect( rejectError( subject, this, 1, 2, 4 ) ).to.eventually.equal( 7 );
		} );
	} )
} );
<commit_msg>[TEST] Re-enable all tests<commit_after>"use strict";

const chai           = require( "chai" );
const chaiAsPromised = require( "chai-as-promised" );
const crypto         = require( "crypto" );
const expect         = chai.expect;

chai.use( chaiAsPromised );

describe( "reject-error", () => {
	const rejectError = require( "." );

	describe( "rejections", () => {
		it( "subject throws", () => {

			function subject() {
				throw new Error();
			}

			return expect( rejectError( subject ) ).to.eventually.be.rejected;
		} );
		it( "subject rejects", () => {

			function subject() {
				return Promise.reject( new Error() );
			}

			return expect( rejectError( subject ) ).to.eventually.be.rejected;
		} );
		it( "subject rejects with Bluebird", () => {

			function subject() {
				const Bluebird = require( "bluebird" );
				return Bluebird.reject( new Error() );
			}

			return expect( rejectError( subject ) ).to.eventually.be.rejected;
		} );
	} );

	describe( "resolutions", () => {
		it( "subject returns", () => {

			function subject() {
				return "foo";
			}

			return expect( rejectError( subject ) ).to.eventually.equal( "foo" );
		} );
		it( "subject resolves", () => {

			function subject() {
				return Promise.resolve( "foo" );
			}

			return expect( rejectError( subject ) ).to.eventually.equal( "foo" );
		} );
	} );

	describe( "bindings", () => {
		it( "uses correct this", () => {
			function subject() {
				return this.foo;
			}

			return expect( rejectError( subject ) ).to.eventually.be.rejected;
		} );

		it( "uses correct this", () => {
			const binding = {
				foo : "bar"
			};

			function subject() {
				return this.foo;
			}

			return expect( rejectError( subject, binding ) ).to.eventually.equal( "bar" );
		} );
	} );

	describe( "arguments", () => {
		it( "passes all arguments", () => {
			function subject( a, b, c ) {
				return a + b + c;
			}

			return expect( rejectError( subject, this, 1, 2, 4 ) ).to.eventually.equal( 7 );
		} );
	} )
} );
<|endoftext|>


<commit_before>var querystring = require('querystring')
  , Emitter = require('events').EventEmitter
  , https = require('https')
  , http = require('http')
  , sha1 = require('./sha1')
  , URL = require('url')
  , util = require('util');

function extend(obj) {
  var args = Array.prototype.slice.call(arguments, 1);

  args.forEach(function(source) {
    for(var prop in source) {
      obj[prop] = source[prop];
    }
  });

  return obj;
}

var OAuth = function OAuth(options) {
  var that = this;

  if (!(this instanceof OAuth)) {
    return new(OAuth)(options);
  }

  this.token = !options.token? {}: {
    'key' : options.token.oauthToken,
    'secret' : options.token.oauthTokenSecret
  };

  this.consumer = {
    'key': options.appKey,
    'secret': options.appSecret
  };

  this.urls = {
    requestToken: null,
    accessToken: null,
    authorize: null
  };

  if (options.urls) {
    for (var k in this.urls) {
      if (options.urls.hasOwnProperty(k)) {
	this.urls[k] = options.urls[k];
      }
    }
  }

  this.headers = options.headers || {};

  Emitter.call(this);
};
util.inherits(OAuth, Emitter);

OAuth.prototype.addHeaders = function(headers) {
  extend(this.headers, headers);
  return this;
};

OAuth.prototype.request = function(method, url /* [data], [callback]*/) {
  var args = Array.prototype.slice.call(arguments, 2)
    , request;

  var callback = args.pop() || function() {}
    , data = args.shift();

  request = new(Request)(
    method, url, data, this.headers, this.consumer, this.token
  );
  request.on('error', this.emit.bind(this, 'error'));
  request.send(callback);

  return this;
};

OAuth.prototype.requestToken = function(/* [url], [callback]*/) {
  var args = Array.prototype.slice.call(arguments)
    , that = this;

  var callback = args.pop() || function() {}
    , url = args.shift();

  if (this.urls.requestToken && !url) {
    url = this.urls.requestToken;
  }

  this
    .addHeaders({'Content-Length': 0})
    .request('post', url, function(res) {
      res.setEncoding('utf8');
      res.on('data', function(data) {
	if (res.statusCode !== 200) {
	  callback(null, data);
	  return;
	}

	token = querystring.parse(data);
	that.token = {
	  'key' : token.oauth_token,
	  'secret' : token.oauth_token_secret
	};

	callback(null, token);
	return;
      });
    });
};

OAuth.prototype.accessToken = function() {
  var args = Array.prototype.slice.call(arguments)
    , that = this;

  var callback = args.pop() || function() {}
    , verifier = args.pop()
    , url = args.shift();

  if (this.urls.accessToken && !url) {
    url = this.urls.accessToken;
  }

  url = URL.parse(url);
  var query = url.query || null;

  url = [url.protocol, '//', url.hostname, url.pathname].join('');
  if (query) {
    query = querystring.parse(query);
    extend(query, {
      'oauth_verifier' : verifier
    });
  } else {
    query = {
      'oauth_verifier' : verifier
    };
  }

  url = [
    url, querystring.stringify(query)
  ].join('?');

  this
    .addHeaders({ 'Content-Length' : 0 })
    .request('post', url, function(res) {
      res.setEncoding('utf8');

      res.on('data', function(data){
	if (res.statusCode !== 200) {
	  callback(data, null);
	  return;
	}

	token = querystring.parse(data);
	that.token = {
	  'key': token.oauth_token,
	  'secret': token.oauth_token_secret
	};
	callback(null, token);
	return;
      });

    });
};

var Request = function Request(method, url, data, headers, consumer, token) {
  var that = this;

  if (!(this instanceof Request)) {
    return new(Request)(method, url, data, headers, consumer, token);
  }

  this.method = method.toLowerCase();
  this.url    = url;
  this.data   = data || {};
  this.consumer = consumer;
  this.token = token || {};

  this.headers = {};
  if (headers) {
    extend(this.headers, headers);
  }

  Emitter.call(this);
};
util.inherits(Request, Emitter);

Request.prototype.getNonce = function(length, base64) {
  var nonce = [], timestamp, char;

  base64 = (base64 !== undefined)? base64 : true;
  length = length? length : 32;

  timestamp = (+new(Date)).toString();
  nonce.push(timestamp);

  if (timestamp.length < length) {
    for (var i = 0; i <= (length-timestamp.length); i++) {
      char = String.fromCharCode(Math.floor(Math.random() * 26)+97);

      if (Math.floor(Math.random()*2))
	char = char.toUpperCase();

      nonce.push(char);
    }
  }

  nonce = nonce.join('');
  return ( base64 )?Buffer(nonce).toString('base64') : nonce;
};

Request.prototype.createSignature = function(oauth_query) {
  var query, sorted_query, base_string, that;

  this.method = this.method.toUpperCase();
  /*
    Parameter string
  */
  var keys = [];
  for (var key in this.url.query) {
    if (this.url.query.hasOwnProperty(key)) {
      keys.push(key);
    }
  }
  keys.sort();

  sorted_query = [];
  that = this;

  keys.forEach(function(key) {
    sorted_query.push([
      key, that.url.query[key]
    ]);
  });

  query = [];
  sorted_query.forEach(function(field) {
    query.push([
      querystring.escape(field[0]),
      querystring.escape(field[1])
    ].join('='));
  });

  query = query.join('&');
  query = query.replace(/\!/g, '%21');
  query = querystring.escape(query);

  /*
    Creating the signature base string
  */
  var base_url = querystring.escape(this.url.protocol+'//'+this.url.host+this.url.pathname);
  base_string = [
    this.method, base_url, query
  ].join('&');

  /*
    Getting a signing key.
  */
  var signing_key = [
    this.consumer.secret, ( this.token.secret )?this.token.secret: ''
  ].join('&');

  return sha1.HMACSHA1(signing_key, base_string);
};

Request.prototype.authHeader = function(oauth_query) {
  var auth_header = 'OAuth ', params = [];

  for (var key in oauth_query) {
    params.push(
      util.format('%s="%s"', key, querystring.escape(oauth_query[key]))
    );
  }

  auth_header += params.join(', ');
  return auth_header;
};

Request.prototype.send = function(callback) {
  this.emit('cat');
  var options, request, oauth_query, oauth_header, oauth_token;

  this.url = URL.parse(this.url);
  this.url.query = querystring.parse(this.url.query);
  oauth_query = {
    'oauth_consumer_key' : this.consumer.key,
    'oauth_signature_method' : 'HMAC-SHA1',
    'oauth_nonce' : this.getNonce(),
    'oauth_timestamp' : Math.round(+new(Date)/1000).toString(),
    'oauth_version' : '1.0'
  };

  /*
    This handles the 'oauth_callback' for the 'request token' step
  */
  oauth_header = extend(
    {}, !this.url.query.hasOwnProperty('oauth_callback')? oauth_query : extend(
      oauth_query, {
	'oauth_callback' : querystring.escape(this.url.query.oauth_callback)
      }
    )
  );

  /*
    And this handles the 'oauth_verifier' for the 'access token' step
  */
  oauth_header = extend(
    {}, !this.url.query.hasOwnProperty('oauth_verifier')? oauth_query : extend(
      oauth_query, {
	'oauth_verifier' : this.url.query.oauth_verifier
      }
    )
  );

  /*

   */

  if (this.token.key) {
    oauth_token = {
      'oauth_token' : this.token.key
    };

    extend(oauth_header, oauth_token);
    extend(this.url.query, oauth_token);
  }

  /*
    Adding oauth parameters to the query
  */
  oauth_query = extend(
    {}, extend(this.url.query, oauth_query));
  /*
    Extending the query with the data, if exists
  */
  if (this.method === 'get') {
    extend(this.url.query, this.data);
    this.data = {};
  }

  /*
    Adding the oauth_signature to the query
  */
  var signature = {
    'oauth_signature' : this.createSignature()
  };

  extend(this.url.query, signature);
  extend(oauth_header, signature);

  var path = [
    this.url.path,
    querystring.stringify(this.url.query)
  ].join('?');

  /*
    Adding oauth headers
  */
  extend(this.headers, {
    'Authorization': this.authHeader(oauth_header)
  });

  options = {
    'method' : this.method,
    'host' : this.url.hostname,
    'path' : this.url.path,
    'headers' : this.headers
  };

  request = ((this.url.protocol === 'https:')? https : http).request(options, callback);
  request.on('error', this.emit.bind(this, 'error'));
  request.end();
};

exports.Request = Request;
exports.OAuth = OAuth;
<commit_msg>Fixed accessToken callback call and documenting its signature<commit_after>var querystring = require('querystring')
  , Emitter = require('events').EventEmitter
  , https = require('https')
  , http = require('http')
  , sha1 = require('./sha1')
  , URL = require('url')
  , util = require('util');

function extend(obj) {
  var args = Array.prototype.slice.call(arguments, 1);

  args.forEach(function(source) {
    for(var prop in source) {
      obj[prop] = source[prop];
    }
  });

  return obj;
}

var OAuth = function OAuth(options) {
  var that = this;

  if (!(this instanceof OAuth)) {
    return new(OAuth)(options);
  }

  this.token = !options.token? {}: {
    'key' : options.token.oauthToken,
    'secret' : options.token.oauthTokenSecret
  };

  this.consumer = {
    'key': options.appKey,
    'secret': options.appSecret
  };

  this.urls = {
    requestToken: null,
    accessToken: null,
    authorize: null
  };

  if (options.urls) {
    for (var k in this.urls) {
      if (options.urls.hasOwnProperty(k)) {
	this.urls[k] = options.urls[k];
      }
    }
  }

  this.headers = options.headers || {};

  Emitter.call(this);
};
util.inherits(OAuth, Emitter);

OAuth.prototype.addHeaders = function(headers) {
  extend(this.headers, headers);
  return this;
};

OAuth.prototype.request = function(method, url /* [data], [callback]*/) {
  var args = Array.prototype.slice.call(arguments, 2)
    , request;

  var callback = args.pop() || function() {}
    , data = args.shift();

  request = new(Request)(
    method, url, data, this.headers, this.consumer, this.token
  );
  request.on('error', this.emit.bind(this, 'error'));
  request.send(callback);

  return this;
};

OAuth.prototype.requestToken = function(/* [url], [callback]*/) {
  var args = Array.prototype.slice.call(arguments)
    , that = this;

  var callback = args.pop() || function() {}
    , url = args.shift();

  if (this.urls.requestToken && !url) {
    url = this.urls.requestToken;
  }

  this
    .addHeaders({'Content-Length': 0})
    .request('post', url, function(res) {
      res.setEncoding('utf8');
      res.on('data', function(data) {
	if (res.statusCode !== 200) {
	  callback(null, data);
	  return;
	}

	token = querystring.parse(data);
	that.token = {
	  'key' : token.oauth_token,
	  'secret' : token.oauth_token_secret
	};

	callback(null, token);
	return;
      });
    });
};

OAuth.prototype.accessToken = function(/* [url], [verifier], [callback]*/) {
  var args = Array.prototype.slice.call(arguments)
    , that = this;

  var callback = args.pop() || function() {}
    , verifier = args.pop()
    , url = args.shift();

  if (this.urls.accessToken && !url) {
    url = this.urls.accessToken;
  }

  url = URL.parse(url);
  var query = url.query || {};

  url = [url.protocol, '//', url.hostname, url.pathname].join('');
  if (query) {
    query = querystring.parse(query);
    extend(query, {
      'oauth_verifier' : verifier
    });
  } else {
    query = {
      'oauth_verifier' : verifier
    };
  }

  url = [
    url, querystring.stringify(query)
  ].join('?');

  this
    .addHeaders({ 'Content-Length' : 0 })
    .request('post', url, function(res) {
      res.setEncoding('utf8');

      res.on('data', function(data) {
	if (res.statusCode !== 200) {
	  callback(null, data);
	  return;
	}

	token = querystring.parse(data);
	that.token = {
	  'key': token.oauth_token,
	  'secret': token.oauth_token_secret
	};
	callback(null, token);
	return;
      });
    });
};

var Request = function Request(method, url, data, headers, consumer, token) {
  var that = this;

  if (!(this instanceof Request)) {
    return new(Request)(method, url, data, headers, consumer, token);
  }

  this.method = method.toLowerCase();
  this.url    = url;
  this.data   = data || {};
  this.consumer = consumer;
  this.token = token || {};

  this.headers = {};
  if (headers) {
    extend(this.headers, headers);
  }

  Emitter.call(this);
};
util.inherits(Request, Emitter);

Request.prototype.getNonce = function(length, base64) {
  var nonce = [], timestamp, char;

  base64 = (base64 !== undefined)? base64 : true;
  length = length? length : 32;

  timestamp = (+new(Date)).toString();
  nonce.push(timestamp);

  if (timestamp.length < length) {
    for (var i = 0; i <= (length-timestamp.length); i++) {
      char = String.fromCharCode(Math.floor(Math.random() * 26)+97);

      if (Math.floor(Math.random()*2))
	char = char.toUpperCase();

      nonce.push(char);
    }
  }

  nonce = nonce.join('');
  return ( base64 )?Buffer(nonce).toString('base64') : nonce;
};

Request.prototype.createSignature = function(oauth_query) {
  var query, sorted_query, base_string, that;

  this.method = this.method.toUpperCase();
  /*
    Parameter string
  */
  var keys = [];
  for (var key in this.url.query) {
    if (this.url.query.hasOwnProperty(key)) {
      keys.push(key);
    }
  }
  keys.sort();

  sorted_query = [];
  that = this;

  keys.forEach(function(key) {
    sorted_query.push([
      key, that.url.query[key]
    ]);
  });

  query = [];
  sorted_query.forEach(function(field) {
    query.push([
      querystring.escape(field[0]),
      querystring.escape(field[1])
    ].join('='));
  });

  query = query.join('&');
  query = query.replace(/\!/g, '%21');
  query = querystring.escape(query);

  /*
    Creating the signature base string
  */
  var base_url = querystring.escape(this.url.protocol+'//'+this.url.host+this.url.pathname);
  base_string = [
    this.method, base_url, query
  ].join('&');

  /*
    Getting a signing key.
  */
  var signing_key = [
    this.consumer.secret, ( this.token.secret )?this.token.secret: ''
  ].join('&');

  return sha1.HMACSHA1(signing_key, base_string);
};

Request.prototype.authHeader = function(oauth_query) {
  var auth_header = 'OAuth ', params = [];

  for (var key in oauth_query) {
    params.push(
      util.format('%s="%s"', key, querystring.escape(oauth_query[key]))
    );
  }

  auth_header += params.join(', ');
  return auth_header;
};

Request.prototype.send = function(callback) {
  this.emit('cat');
  var options, request, oauth_query, oauth_header, oauth_token;

  this.url = URL.parse(this.url);
  this.url.query = querystring.parse(this.url.query);
  oauth_query = {
    'oauth_consumer_key' : this.consumer.key,
    'oauth_signature_method' : 'HMAC-SHA1',
    'oauth_nonce' : this.getNonce(),
    'oauth_timestamp' : Math.round(+new(Date)/1000).toString(),
    'oauth_version' : '1.0'
  };

  /*
    This handles the 'oauth_callback' for the 'request token' step
  */
  oauth_header = extend(
    {}, !this.url.query.hasOwnProperty('oauth_callback')? oauth_query : extend(
      oauth_query, {
	'oauth_callback' : querystring.escape(this.url.query.oauth_callback)
      }
    )
  );

  /*
    And this handles the 'oauth_verifier' for the 'access token' step
  */
  oauth_header = extend(
    {}, !this.url.query.hasOwnProperty('oauth_verifier')? oauth_query : extend(
      oauth_query, {
	'oauth_verifier' : this.url.query.oauth_verifier
      }
    )
  );

  /*

   */

  if (this.token.key) {
    oauth_token = {
      'oauth_token' : this.token.key
    };

    extend(oauth_header, oauth_token);
    extend(this.url.query, oauth_token);
  }

  /*
    Adding oauth parameters to the query
  */
  oauth_query = extend(
    {}, extend(this.url.query, oauth_query));
  /*
    Extending the query with the data, if exists
  */
  if (this.method === 'get') {
    extend(this.url.query, this.data);
    this.data = {};
  }

  /*
    Adding the oauth_signature to the query
  */
  var signature = {
    'oauth_signature' : this.createSignature()
  };

  extend(this.url.query, signature);
  extend(oauth_header, signature);

  var path = [
    this.url.path,
    querystring.stringify(this.url.query)
  ].join('?');

  /*
    Adding oauth headers
  */
  extend(this.headers, {
    'Authorization': this.authHeader(oauth_header)
  });

  options = {
    'method' : this.method,
    'host' : this.url.hostname,
    'path' : this.url.path,
    'headers' : this.headers
  };

  request = ((this.url.protocol === 'https:')? https : http).request(options, callback);
  request.on('error', this.emit.bind(this, 'error'));
  request.end();
};

exports.Request = Request;
exports.OAuth = OAuth;
<|endoftext|>


<commit_before>/* global describe */
/* global it */
/* global expect */

var λ = require('./lambada');

describe('lambada', function () {
    it('should return a function', function () {
        expect(typeof λ).toBe('function');
    });

    it('creates a unary function for a simple expression', function () {
        var f = λ('3 + x');
        expect(typeof f).toBe('function');
        expect(f(-10)).toBe(-7);
        expect(f(0)).toBe(3);
        expect(f(10)).toBe(13);
    });

    it('creates a binary function for a simple expression', function () {
        var f = λ('x + 2 * y');
        expect(typeof f).toBe('function');
        expect(f(3, 4)).toBe(11);
        expect(f(4, 3)).toBe(10);
        expect(f(2, 7)).toBe(16);
    });

    it('creates a function for a binary operator', function () {
        var f = λ('+');
        expect(typeof f).toBe('function');
        expect(f(3, 2)).toBe(5);
        expect(f(-3, 4)).toBe(1);
        expect(f(8, 8)).toBe(16);
    });

    it('creates a function for a partially applied binary operator', function () {
        var f = λ('+3');
        expect(typeof f).toBe('function');
        expect(f(-10)).toBe(-7);
        expect(f(0)).toBe(3);
        expect(f(10)).toBe(13);
    });
});
<commit_msg>Add tests from Functional Javascript<commit_after>/* global describe */
/* global it */
/* global expect */

var λ = require('./lambada');

describe('lambada', function () {
    it('should return a function', function () {
        expect(typeof λ).toBe('function');
    });

    it('creates a unary function for a simple expression', function () {
        var f = λ('3 + x');
        expect(typeof f).toBe('function');
        expect(f(-10)).toBe(-7);
        expect(f(0)).toBe(3);
        expect(f(10)).toBe(13);
    });

    it("passes Functional Javascript's tests", function () {
        expect(λ('x -> x + 1')(1)).toBe(2);
        expect(λ('x y -> x + 2*y')(1, 2)).toBe(5);
        expect(λ('x, y -> x + 2*y')(1, 2)).toBe(5);
        expect(λ('_ + 1')(1)).toBe(2);
        expect(λ('/2')(4)).toBe(2);
        expect(λ('2/')(4)).toBe(0.5);
        expect(λ('/')(2,4)).toBe(0.5);
        expect(λ('x + 1')(1)).toBe(2);
        expect(λ('x + 2*y')(1, 2)).toBe(5);
        expect(λ('y + 2*x')(1, 2)).toBe(5);
        expect(λ('x -> y -> x + 2*y')(1)(2)).toBe(5);
    });

    it('creates a binary function for a simple expression', function () {
        var f = λ('x + 2 * y');
        expect(typeof f).toBe('function');
        expect(f(3, 4)).toBe(11);
        expect(f(4, 3)).toBe(10);
        expect(f(2, 7)).toBe(16);
    });

    it('creates a function for a binary operator', function () {
        var f = λ('+');
        expect(typeof f).toBe('function');
        expect(f(3, 2)).toBe(5);
        expect(f(-3, 4)).toBe(1);
        expect(f(8, 8)).toBe(16);
    });

    it('creates a function for a partially applied binary operator', function () {
        var f = λ('+3');
        expect(typeof f).toBe('function');
        expect(f(-10)).toBe(-7);
        expect(f(0)).toBe(3);
        expect(f(10)).toBe(13);
    });
});
<|endoftext|>


<commit_before>/**
 * Module dependencies
 */

var passport = require('passport');
var envs = require('envs');
var OAuthStrategy = require('passport-oauth2').Strategy;

/**
 * Expose the simple auth methods
 */

module.exports = SimpleAuth;

function SimpleAuth(opts) {
  if (!(this instanceof SimpleAuth)) return new SimpleAuth(opts);
  this.opts = opts || {};
  this.name = this.opts.name || 'random name';
  this.register(this.opts);
};

SimpleAuth.prototype.register = function(opts) {
  var AUTH_URL = opts.authURL || envs('AUTH_URL');
  var AUTHORIZATION_URL = opts.authorizationPath || '/authorize';
  var TOKEN_URL = opts.tokenPath || '/token';

  var strategy = new OAuthStrategy({
    clientID: envs('OAUTH_CLIENT_ID'),
    clientSecret: envs('OAUTH_CLIENT_SECRET'),
    authorizationURL: AUTHORIZATION_URL,
    tokenURL: TOKEN_URL,
    skipUserProfile: true
  },
  function(accessToken, refreshToken, profile, done) {
    profile = profile || {};
    profile.accessToken = accessToken;
    profile.refreshToken = refreshToken;
    done(null, profile);
  });

  strategy.name = this.name;
  strategy._host = AUTH_URL;

  var _authenticate = strategy.authenticate;
  strategy.authenticate = function(req, options) {
    options = options || {};

    this._oauth2._baseSite = options.host || this._host;
    _authenticate.apply(this, arguments);
  };

  passport.use(strategy);
};

SimpleAuth.prototype.login = function(options) {
  var self = this;
  options = options || {};

  return function (req, res, next) {
    // If they're already signed in, don't do anything
    if (req.cookies._access_token) return next();

    // Setup the options for passport
    options.callbackURL = req.base + '/auth/callback';
    options.state = (req.get('referrer') || '/');
    options.host = req.get('x-auth-url');

    // Profile the call
    var done = req.metric.profile('login');

    return passport.authenticate(self.name, options, function(err, profile) {
      // End profiling
      done();

      // We've got an error
      if (err) return next(err);

      // TODO handle oauth errors - like access denied
      if (!profile.accessToken) return res.redirect(req.query.state);

      // Expose the profile
      req.user = profile;

      // Expose the access token
      // TODO set the expiration based on what the auth app told us
      res.cookie('_access_token', profile.accessToken, {
        secure: ~req.base.indexOf('https://')
      });

      res.redirect(req.query.state);
    })(req, res, next);
  };
};

SimpleAuth.prototype.logout = function() {
  return function(req, res, next) {
    // Clear the access token
    res.clearCookie('_access_token', {
      secure: ~req.base.indexOf('https://')
    });

    res.redirect((req.get('x-auth-url') || AUTH_URL) + '/logout');
  }
};

SimpleAuth.prototype.authenticate = function(restricted) {
  return restricted
    ? this.login()
    : noop;
};

function noop(req, res, next) {
  next();
};
<commit_msg>fix force login in oauth<commit_after>/**
 * Module dependencies
 */

var passport = require('passport');
var envs = require('envs');
var OAuthStrategy = require('passport-oauth2').Strategy;

/**
 * Expose the simple auth methods
 */

module.exports = SimpleAuth;

function SimpleAuth(opts) {
  if (!(this instanceof SimpleAuth)) return new SimpleAuth(opts);
  this.opts = opts || {};
  this.name = this.opts.name || 'random name';
  this.register(this.opts);
};

SimpleAuth.prototype.register = function(opts) {
  var AUTH_URL = opts.authURL || envs('AUTH_URL');
  var AUTHORIZATION_URL = opts.authorizationPath || '/authorize';
  var TOKEN_URL = opts.tokenPath || '/token';

  var strategy = new OAuthStrategy({
    clientID: envs('OAUTH_CLIENT_ID'),
    clientSecret: envs('OAUTH_CLIENT_SECRET'),
    authorizationURL: AUTHORIZATION_URL,
    tokenURL: TOKEN_URL,
    skipUserProfile: true
  },
  function(accessToken, refreshToken, profile, done) {
    profile = profile || {};
    profile.accessToken = accessToken;
    profile.refreshToken = refreshToken;
    done(null, profile);
  });

  strategy.name = this.name;
  strategy._host = AUTH_URL;

  var _authenticate = strategy.authenticate;
  strategy.authenticate = function(req, options) {
    options = options || {};

    this._oauth2._baseSite = options.host || this._host;
    _authenticate.apply(this, arguments);
  };

  passport.use(strategy);
};

SimpleAuth.prototype.login = function(options) {
  var self = this;
  options = options || {};

  return function (req, res, next) {
    // If they're already signed in, don't do anything
    if (req.cookies._access_token && !req.query.code) return next();

    // Setup the options for passport
    options.callbackURL = req.base + '/auth/callback';
    options.state = (req.get('referrer') || '/');
    options.host = req.get('x-auth-url');

    // Profile the call
    var done = req.metric.profile('login');

    return passport.authenticate(self.name, options, function(err, profile) {
      // End profiling
      done();

      // We've got an error
      if (err) return next(err);

      // TODO handle oauth errors - like access denied
      if (!profile.accessToken) return res.redirect(req.query.state);

      // Expose the profile
      req.user = profile;

      // Expose the access token
      // TODO set the expiration based on what the auth app told us
      res.cookie('_access_token', profile.accessToken, {
        secure: ~req.base.indexOf('https://')
      });

      res.redirect(req.query.state);
    })(req, res, next);
  };
};

SimpleAuth.prototype.logout = function() {
  return function(req, res, next) {
    // Clear the access token
    res.clearCookie('_access_token', {
      secure: ~req.base.indexOf('https://')
    });

    res.redirect((req.get('x-auth-url') || AUTH_URL) + '/logout');
  }
};

SimpleAuth.prototype.authenticate = function(restricted) {
  return restricted
    ? this.login()
    : noop;
};

function noop(req, res, next) {
  next();
};
<|endoftext|>


<commit_before>'use strict';

/* eslint no-magic-numbers: 1 */

var test = require('tape');
var isCallable = require('./');
var hasSymbols = typeof Symbol === 'function' && typeof Symbol('foo') === 'symbol';
var genFn = require('make-generator-function');
var arrowFn = require('make-arrow-function')();
var asyncFn;
var asyncArrowFn;
try {
  asyncFn = Function('return async function foo() {};')();
  asyncArrowFn = Function('return async () => {};')();
} catch (e) {/**/}
var forEach = require('foreach');

var noop = function () {};
var classFake = function classFake() { }; // eslint-disable-line func-name-matching
var returnClass = function () { return ' class '; };
var return3 = function () { return 3; };
/* for coverage */
noop();
classFake();
returnClass();
return3();
/* end for coverage */

var invokeFunction = function invokeFunctionString(str) {
	var result;
	try {
		/* eslint-disable no-new-func */
		var fn = Function(str);
		/* eslint-enable no-new-func */
		result = fn();
	} catch (e) {}
	return result;
};

var classConstructor = invokeFunction('"use strict"; return class Foo {}');

var commentedClass = invokeFunction('"use strict"; return class/*kkk*/\n//blah\n Bar\n//blah\n {}');

test('not callables', function (t) {
	t.test('non-number/string primitives', function (st) {
		st.notOk(isCallable(), 'undefined is not callable');
		st.notOk(isCallable(null), 'null is not callable');
		st.notOk(isCallable(false), 'false is not callable');
		st.notOk(isCallable(true), 'true is not callable');
		st.end();
	});

	t.notOk(isCallable([]), 'array is not callable');
	t.notOk(isCallable({}), 'object is not callable');
	t.notOk(isCallable(/a/g), 'regex literal is not callable');
	t.notOk(isCallable(new RegExp('a', 'g')), 'regex object is not callable');
	t.notOk(isCallable(new Date()), 'new Date() is not callable');

	t.test('numbers', function (st) {
		st.notOk(isCallable(42), 'number is not callable');
		st.notOk(isCallable(Object(42)), 'number object is not callable');
		st.notOk(isCallable(NaN), 'NaN is not callable');
		st.notOk(isCallable(Infinity), 'Infinity is not callable');
		st.end();
	});

	t.test('strings', function (st) {
		st.notOk(isCallable('foo'), 'string primitive is not callable');
		st.notOk(isCallable(Object('foo')), 'string object is not callable');
		st.end();
	});

	t.test('non-function with function in its [[Prototype]] chain', function (st) {
		var Foo = function Bar() {};
		Foo.prototype = noop;
		st.equal(true, isCallable(Foo), 'sanity check: Foo is callable');
		st.equal(false, isCallable(new Foo()), 'instance of Foo is not callable');
		st.end();
	});

	t.end();
});

test('@@toStringTag', { skip: !hasSymbols || !Symbol.toStringTag }, function (t) {
	var fakeFunction = {
		toString: function () { return String(return3); },
		valueOf: return3
	};
	fakeFunction[Symbol.toStringTag] = 'Function';
	t.equal(String(fakeFunction), String(return3));
	t.equal(Number(fakeFunction), return3());
	t.notOk(isCallable(fakeFunction), 'fake Function with @@toStringTag "Function" is not callable');
	t.end();
});

var typedArrayNames = [
	'Int8Array',
	'Uint8Array',
	'Uint8ClampedArray',
	'Int16Array',
	'Uint16Array',
	'Int32Array',
	'Uint32Array',
	'Float32Array',
	'Float64Array'
];

test('Functions', function (t) {
	t.ok(isCallable(noop), 'function is callable');
	t.ok(isCallable(classFake), 'function with name containing "class" is callable');
	t.ok(isCallable(returnClass), 'function with string " class " is callable');
	t.ok(isCallable(isCallable), 'isCallable is callable');
	t.end();
});

test('Typed Arrays', function (st) {
	forEach(typedArrayNames, function (typedArray) {
		/* istanbul ignore if : covered in node 0.6 */
		if (typeof global[typedArray] === 'undefined') {
			st.comment('# SKIP typed array "' + typedArray + '" not supported');
		} else {
			st.ok(isCallable(global[typedArray]), typedArray + ' is callable');
		}
	});
	st.end();
});

test('Generators', { skip: !genFn }, function (t) {
	t.ok(isCallable(genFn), 'generator function is callable');
	t.end();
});

test('Arrow functions', { skip: !arrowFn }, function (t) {
	t.ok(isCallable(arrowFn), 'arrow function is callable');
	t.end();
});

test('"Class" constructors', { skip: !classConstructor || !commentedClass }, function (t) {
	t.notOk(isCallable(classConstructor), 'class constructors are not callable');
	t.notOk(isCallable(commentedClass), 'class constructors with comments in the signature are not callable');
	t.end();
});

test('`async function`s', { skip: !asyncFn }, function (t) {
	t.ok(isCallable(asyncFn), '`async function`s are callable');
	t.ok(isCallable(asyncArrowFn), '`async` arrow functions are callable');
	t.end();
});
<commit_msg>[Tests] fix linting errors<commit_after>'use strict';

/* eslint no-magic-numbers: 1 */

var test = require('tape');
var isCallable = require('./');
var hasSymbols = typeof Symbol === 'function' && typeof Symbol('foo') === 'symbol';
var genFn = require('make-generator-function');
var arrowFn = require('make-arrow-function')();
var asyncFn;
var asyncArrowFn;
try {
	/* eslint no-new-func: 0 */
	asyncFn = Function('return async function foo() {};')();
	asyncArrowFn = Function('return async () => {};')();
} catch (e) { /**/ }
var forEach = require('foreach');

var noop = function () {};
var classFake = function classFake() { }; // eslint-disable-line func-name-matching
var returnClass = function () { return ' class '; };
var return3 = function () { return 3; };
/* for coverage */
noop();
classFake();
returnClass();
return3();
/* end for coverage */

var invokeFunction = function invokeFunctionString(str) {
	var result;
	try {
		/* eslint-disable no-new-func */
		var fn = Function(str);
		/* eslint-enable no-new-func */
		result = fn();
	} catch (e) {}
	return result;
};

var classConstructor = invokeFunction('"use strict"; return class Foo {}');

var commentedClass = invokeFunction('"use strict"; return class/*kkk*/\n//blah\n Bar\n//blah\n {}');

test('not callables', function (t) {
	t.test('non-number/string primitives', function (st) {
		st.notOk(isCallable(), 'undefined is not callable');
		st.notOk(isCallable(null), 'null is not callable');
		st.notOk(isCallable(false), 'false is not callable');
		st.notOk(isCallable(true), 'true is not callable');
		st.end();
	});

	t.notOk(isCallable([]), 'array is not callable');
	t.notOk(isCallable({}), 'object is not callable');
	t.notOk(isCallable(/a/g), 'regex literal is not callable');
	t.notOk(isCallable(new RegExp('a', 'g')), 'regex object is not callable');
	t.notOk(isCallable(new Date()), 'new Date() is not callable');

	t.test('numbers', function (st) {
		st.notOk(isCallable(42), 'number is not callable');
		st.notOk(isCallable(Object(42)), 'number object is not callable');
		st.notOk(isCallable(NaN), 'NaN is not callable');
		st.notOk(isCallable(Infinity), 'Infinity is not callable');
		st.end();
	});

	t.test('strings', function (st) {
		st.notOk(isCallable('foo'), 'string primitive is not callable');
		st.notOk(isCallable(Object('foo')), 'string object is not callable');
		st.end();
	});

	t.test('non-function with function in its [[Prototype]] chain', function (st) {
		var Foo = function Bar() {};
		Foo.prototype = noop;
		st.equal(true, isCallable(Foo), 'sanity check: Foo is callable');
		st.equal(false, isCallable(new Foo()), 'instance of Foo is not callable');
		st.end();
	});

	t.end();
});

test('@@toStringTag', { skip: !hasSymbols || !Symbol.toStringTag }, function (t) {
	var fakeFunction = {
		toString: function () { return String(return3); },
		valueOf: return3
	};
	fakeFunction[Symbol.toStringTag] = 'Function';
	t.equal(String(fakeFunction), String(return3));
	t.equal(Number(fakeFunction), return3());
	t.notOk(isCallable(fakeFunction), 'fake Function with @@toStringTag "Function" is not callable');
	t.end();
});

var typedArrayNames = [
	'Int8Array',
	'Uint8Array',
	'Uint8ClampedArray',
	'Int16Array',
	'Uint16Array',
	'Int32Array',
	'Uint32Array',
	'Float32Array',
	'Float64Array'
];

test('Functions', function (t) {
	t.ok(isCallable(noop), 'function is callable');
	t.ok(isCallable(classFake), 'function with name containing "class" is callable');
	t.ok(isCallable(returnClass), 'function with string " class " is callable');
	t.ok(isCallable(isCallable), 'isCallable is callable');
	t.end();
});

test('Typed Arrays', function (st) {
	forEach(typedArrayNames, function (typedArray) {
		/* istanbul ignore if : covered in node 0.6 */
		if (typeof global[typedArray] === 'undefined') {
			st.comment('# SKIP typed array "' + typedArray + '" not supported');
		} else {
			st.ok(isCallable(global[typedArray]), typedArray + ' is callable');
		}
	});
	st.end();
});

test('Generators', { skip: !genFn }, function (t) {
	t.ok(isCallable(genFn), 'generator function is callable');
	t.end();
});

test('Arrow functions', { skip: !arrowFn }, function (t) {
	t.ok(isCallable(arrowFn), 'arrow function is callable');
	t.end();
});

test('"Class" constructors', { skip: !classConstructor || !commentedClass }, function (t) {
	t.notOk(isCallable(classConstructor), 'class constructors are not callable');
	t.notOk(isCallable(commentedClass), 'class constructors with comments in the signature are not callable');
	t.end();
});

test('`async function`s', { skip: !asyncFn }, function (t) {
	t.ok(isCallable(asyncFn), '`async function`s are callable');
	t.ok(isCallable(asyncArrowFn), '`async` arrow functions are callable');
	t.end();
});
<|endoftext|>


<commit_before>var utils = require('zefti-utils');

function responseParser(p, r){
  var b = null;
  if (utils.type(r) === 'object'){
    b = {};
    for (var key in r) {
      if (!p[key]) continue;
      if (r[key] === 'string') {
        if (utils.type(p[key]) !== 'string') return errorHandler('string type did not match for: ' + key);
        b[key] = p[key]
      } else if (r[key]) === 'number') {
        if (utils.type(p[key]) !== 'number') return errorHandler('number type did not match for: ' + key);
        b[key] = p[key]
      } else if (utils.type(r[key]) === 'object' || utils.type(r[key]) === 'array') {
        if (utils.type(r[key]) !== utils.type(p[key])) return errorHandler('object check - the type did not match for key: ' + key);
        b[key] = responseHandler2(p[key], r[key]);
      } else {
        return errorHandler('The type of the key is unknown');
      }
    }
  } else if (utils.type(r) === 'array') {
    if(utils.type(p) !== 'array') return errorHandler('rules state array, payload is not an array: ' + key);
    b = [];
    p.forEach(function(item){
      if (utils.type(item) === 'string') {
        b.push(item)
      } else if (utils.type(item) === 'number'){
        b.push(item);
      } else if (utils.type(item) === 'object') {
        if (utils.type(item) !== utils.type(r[0])) return errorHandler('array check - r is not an object: ' + key);
        b.push(responseHandler2(item, r[0]));
      } else if (utils.type(p[key]) === 'array') {
        if (utils.type(item) !== utils.type(r[0])) return errorHandler('array check - r is not an array: ' + key);
        b.push(responseHandler2(item, r[0]));
      } else {
        return errorHandler('The type of the key is unknown, the type is: ' + utils.type(p[key]));
      }
    });
  } else if (utils.type(r) === 'string'){
    b = '';
  }
  return (b);
}

var errorHandler = function(err){
  res.status(500).send({ error: err });
};

modules.exports = function(options){
  if (typeof responseFieldsOption === 'string') {
    responseFields = config.response[responseFieldsOption];
  } else {
    responseFields = responseFieldsOption;
  }

  function responseHandler(payload, cb){
    var response = responseParser(payload, responseFields);
    payload.res.send(response);
  }

  return responseHandler;

};<commit_msg>stuff<commit_after><|endoftext|>


<commit_before>require('chai').should()
import postcss from 'postcss'
import fs from 'fs'
import path from 'path'

import nesting from 'postcss-nesting'
import plugin from './'

const run = (done, input, output, opts = {}) => {
  return postcss([nesting({ bubble: 'important' }), plugin(opts)])
    .process(input)
    .then(result => {
      result.warnings().length.should.be.equal(0)
      result.css.should.be.equal(output)
      done()
    })
    .catch(done)
}

const getFileContent = (dir, file) => {
  return fs.readFileSync(path.join(dir, file)).toString().trim()
}

const fixturesDir = path.join(__dirname, 'fixtures')
fs.readdirSync(fixturesDir).forEach(caseName => {
  if (caseName.includes('[notest]')) return

  const options = {
    extract: {
      important: `fixtures/${caseName}/extracted-actual.css`,
    },
  }

  const fixtureDir = path.join(fixturesDir, caseName)
  if (!fs.lstatSync(fixtureDir).isDirectory()) return
  it(caseName, done => {
    const input = getFileContent(fixtureDir, 'input.css')
    const output = getFileContent(fixtureDir, 'output.css')
    const extracted = getFileContent(fixtureDir, 'extracted.css')
    const extractedActual = getFileContent(fixtureDir, 'extracted-actual.css')
    extracted.should.be.equal(extractedActual)
    run(done, input, output, options)
  })
})
<commit_msg>Fix tests order<commit_after>require('chai').should()
import postcss from 'postcss'
import fs from 'fs'
import path from 'path'

import nesting from 'postcss-nesting'
import plugin from './'

const run = (done, input, output, opts = {}) => {
  return postcss([nesting({ bubble: 'important' }), plugin(opts)])
    .process(input)
    .then(result => {
      result.warnings().length.should.be.equal(0)
      result.css.should.be.equal(output)
      done()
    })
    .catch(done)
}

const getFileInDirectoryContent = dir => file => {
  return fs.readFileSync(path.join(dir, file)).toString().trim()
}

const fixturesDir = path.join(__dirname, 'fixtures')
fs.readdirSync(fixturesDir).forEach(caseName => {
  if (caseName.includes('[notest]')) return

  const fixtureDir = path.join(fixturesDir, caseName)
  if (!fs.lstatSync(fixtureDir).isDirectory()) return
  const getFile = getFileInDirectoryContent(fixtureDir)

  const options = {
    extract: {
      important: `fixtures/${caseName}/extracted-actual.css`,
    },
  }

  it(caseName, done => {
    const input = getFile('input.css')
    const output = getFile('output.css')
    run(done, input, output, options)

    const extracted = getFile('extracted.css')
    const extractedActual = getFile('extracted-actual.css')
    extracted.should.be.equal(extractedActual)
  })
})
<|endoftext|>


<commit_before>'use strict'
import test from 'ava'
import fn from './'
import ddoc from './commands/ddoc'
import deploy from './commands/deploy'

test('go', t => {
  const result = Object.keys(fn).sort()
  t.is(result[0], 'ddoc')
  t.is(result[1], 'deploy')
})

test('ddoc', async t => {
  const mod = { ddoc: (p) => Promise.resolve(`path: ${p}`) }
  const result = ddoc(mod, (o) => o)
  t.is(result.command, 'ddoc <ddocpath>')
  const h = await result.handler({ ddocpath: 'here' })
  t.is(h, 'path: here')
})

test('deploy', async t => {
  const mod = { deploy: (p, db) => Promise.resolve(`path: ${p}; db: ${db}`) }
  const result = deploy(mod, (o) => o)
  t.is(result.command, 'deploy <ddocpath>')
  const h = await result.handler({ db: 'hoho', ddocpath: 'here' })
  t.is(h, 'path: here; db: hoho')
})
<commit_msg>Improved test.<commit_after>'use strict'
import test from 'ava'
import fn from './'
import ddoc from './commands/ddoc'
import deploy from './commands/deploy'

test('go', t => {
  const result = Object.keys(fn)
  t.not(result.indexOf('ddoc'), -1)
  t.not(result.indexOf('deploy'), -1)
})

test('ddoc', async t => {
  const mod = { ddoc: (p) => Promise.resolve(`path: ${p}`) }
  const result = ddoc(mod, (o) => o)
  t.is(result.command, 'ddoc <ddocpath>')
  const h = await result.handler({ ddocpath: 'here' })
  t.is(h, 'path: here')
})

test('deploy', async t => {
  const mod = { deploy: (p, db) => Promise.resolve(`path: ${p}; db: ${db}`) }
  const result = deploy(mod, (o) => o)
  t.is(result.command, 'deploy <ddocpath>')
  const h = await result.handler({ db: 'hoho', ddocpath: 'here' })
  t.is(h, 'path: here; db: hoho')
})
<|endoftext|>


<commit_before>"use strict"

const formatsData = require('pokemon-showdown/data/formats-data').BattleFormatsData
const pokedex = require('pokemon-showdown/data/pokedex').BattlePokedex
const items = require('pokemon-showdown/data/items').BattleItems
const doublesFormatsData = Object.create(formatsData)
const formats = require('pokemon-showdown/config/formats').Formats

const formatHandlers = {
    '[Gen 7] Doubles OU': 'Uber',
    '[Gen 7] Doubles UU': 'OU',
}

const banlists = {}

for (const pokemonid in doublesFormatsData) {
    doublesFormatsData[pokemonid] = Object.create(doublesFormatsData[pokemonid])
    doublesFormatsData[pokemonid].tier = 'NU'
}

formats.forEach(function searchFormats(format) {
    if (!format.name) {
        return
    }
    const tier = formatHandlers[format.name]
    if (tier) {
        format.banlist.forEach(function applyBanlist(entry) {
            const id = toId(entry)
            const item = items[id]
            if (item && item.megaEvolves) {
                doublesFormatsData[toId(item.megaStone)].tier = tier
            }
            const pokemon = doublesFormatsData[id]
            if (pokemon) {
                pokemon.tier = tier
            }
        })
    }
})

function toId(name) {
    return name.toLowerCase().replace(/[^a-z0-9]/g, "")
}

function searchTier(formatsData, pokemonid, findMega) {
    const pokemon = pokedex[pokemonid]
    const tiers = {
        Uber: 0,
        OU: 1,
        UUBL: 1,
        UU: 2,
        RUBL: 2,
        RU: 3,
        NUBL: 3,
        NU: 4,
        PUBL: 4,
        PU: 5,
        New: 5,
        NFE: 5,
        LC: 5,
        'LC Uber': 5,
    }
    const reverseTier = ['Uber', 'OU', 'UU', 'RU', 'NU', 'PU']
    let evos = pokemon.evos || []
    if (findMega) {
        evos = evos.concat(pokemon.otherFormes || [])
    }
    const currentTier = formatsData[pokemonid].tier
    const toSearch = evos.map(function recursiveSearch(evo) {
        return searchTier(formatsData, evo, findMega)
    }).concat(currentTier)
    return reverseTier[Math.min.apply(Math, toSearch.map(function toTierValue(tier) {
        if (tier.charAt(0) === '(') {
            tier = tier.slice(1, -1)
        }
        return tiers[tier]
    }))]
}

function hasMega(pokemon) {
    if (pokemon.species === 'Rayquaza') {
        return false // too broken
    }
    if (pokemon.otherFormes) {
        for (const id of pokemon.otherFormes) {
            const forme = pokedex[id]
            if (forme.forme.substring(0, 4) === 'Mega') {
                return formatsData[id].tier !== 'Unreleased'
            }
        }
        return false
    }
    const evos = pokemon.evos || []
    for (const evo of evos) {
        if (hasMega(pokedex[evo])) {
            return true
        }
    }
    return false
}

function gen(num) {
    if (num <= 151) return 1
    if (num <= 251) return 2
    if (num <= 386) return 3
    if (num <= 493) return 4
    if (num <= 649) return 5
    if (num <= 721) return 6
    return 7
}

const banned = {
    burmy: 1, caterpie: 1, combee: 1, kricketot: 1, magikarp: 1, scatterbug: 1,
    sunkern: 1, tynamo: 1, weedle: 1, wurmple: 1, typenull: 1, cosmog: 1,
    poipole: 1, gligar: 1, sneasel: 1, ferroseed: 1,
}
const legendaries = {
    articuno: 1, zapdos: 1, moltres: 1, mewtwo: 1, mew: 1, raikou: 1,
    entei: 1, suicune: 1, lugia: 1, hooh: 1, celebi: 1, regirock: 1,
    regice: 1, registeel: 1, latias: 1, latios: 1, kyogre: 1, groudon: 1,
    rayquaza: 1, jirachi: 1, deoxys: 1, deoxysattack: 1, deoxysdefense: 1,
    deoxysspeed: 1, uxie: 1, mesprit: 1, azelf: 1, dialga: 1, palkia: 1,
    heatran: 1, regigigas: 1, manaphy: 1, giratina: 1, giratinaorigin: 1,
    cresselia: 1, darkrai: 1, shaymin: 1, shayminsky: 1, arceus: 1,
    victini: 1, cobalion: 1, terrakion: 1, virizion: 1, tornadus: 1,
    thundurus: 1, tornadustherian: 1, thundurustherian: 1, reshiram: 1,
    zekrom: 1, landorus: 1, landorustherian: 1, kyurem: 1, kyuremblack: 1,
    kyuremwhite: 1, keldeo: 1, meloetta: 1, genesect: 1, xerneas: 1,
    yveltal: 1, zygarde: 1, diancie: 1, hoopa: 1, hoopaunbound: 1,
    silvally: 1, tapukoko: 1, tapulele: 1, tapubulu: 1, tapufini: 1,
    solgaleo: 1, lunala: 1, nihilego: 1, buzzwole: 1, pheromosa: 1,
    xurkitree: 1, celesteela: 1, kartana: 1, guzzlord: 1, necrozma: 1,
    magearna: 1, marshadow: 1, naganadel: 1, stakataka: 1, blacephalon: 1,
    zeraora: 1
}

const fs = require('fs')
const output = fs.openSync('_data/pokemon.yml', 'w')

for (const pokemonid in formatsData) {
    const pokemon = pokedex[pokemonid]
    const format = formatsData[pokemonid]
    if (!legendaries[pokemonid] && (!pokemon || pokemon.prevo || !pokemon.evos || pokemon.forme || format.isNonstandard || banned[pokemonid])) continue

    const mega = false
    const tier = format.tier
    fs.writeSync(output, '- {name: ' + pokemon.species)
    fs.writeSync(output, ', legendary: ' + !!legendaries[pokemonid])
    const colors = new Map([[pokemon.color, pokemon.species]])
    for (const formeid of pokemon.otherFormes || []) {
        const formeColor = pokedex[formeid].color
        if (!colors.has(formeColor)) {
            colors.set(formeColor, pokedex[formeid].species)
        }
    }
    fs.writeSync(output, ', color: {')
    fs.writeSync(output, Array.from(colors).map(([color, specie]) => `${color}: ${specie}`).join(", "))
    fs.writeSync(output, '}, types: [' + pokemon.types.join(', ') + ']')
    const singlesTier = searchTier(formatsData, pokemonid, false)
    const doublesTier = searchTier(doublesFormatsData, pokemonid, false, [])
    fs.writeSync(output, ', tier: ' + singlesTier)
    fs.writeSync(output, ', doublesTier: ' + doublesTier)
    fs.writeSync(output, ', gen: ' + gen(pokemon.num))
    fs.writeSync(output, ', mega: ')
    if (hasMega(pokemon)) {
        fs.writeSync(output, '{tier: ' + searchTier(formatsData, pokemonid, true))
        fs.writeSync(output, ', doublesTier: ' + searchTier(formatsData, pokemonid, true))
        fs.writeSync(output, '}')
    } else {
        fs.writeSync(output, 'null')
    }
    fs.writeSync(output, '}\n')
}

fs.closeSync(output)
<commit_msg>Ban Pokemon basing on tiers, not using an explicit list<commit_after>"use strict"

const formatsData = require('pokemon-showdown/data/formats-data').BattleFormatsData
const pokedex = require('pokemon-showdown/data/pokedex').BattlePokedex
const items = require('pokemon-showdown/data/items').BattleItems
const doublesFormatsData = Object.create(formatsData)
const formats = require('pokemon-showdown/config/formats').Formats

const formatHandlers = {
    '[Gen 7] Doubles OU': 'Uber',
    '[Gen 7] Doubles UU': 'OU',
}

const banlists = {}

for (const pokemonid in doublesFormatsData) {
    doublesFormatsData[pokemonid] = Object.create(doublesFormatsData[pokemonid])
    doublesFormatsData[pokemonid].tier = 'NU'
}

formats.forEach(function searchFormats(format) {
    if (!format.name) {
        return
    }
    const tier = formatHandlers[format.name]
    if (tier) {
        format.banlist.forEach(function applyBanlist(entry) {
            const id = toId(entry)
            const item = items[id]
            if (item && item.megaEvolves) {
                doublesFormatsData[toId(item.megaStone)].tier = tier
            }
            const pokemon = doublesFormatsData[id]
            if (pokemon) {
                pokemon.tier = tier
            }
        })
    }
})

function toId(name) {
    return name.toLowerCase().replace(/[^a-z0-9]/g, "")
}

    const tiers = {
        Uber: 0,
        OU: 1,
        UUBL: 1,
        UU: 2,
        RUBL: 2,
        RU: 3,
        NUBL: 3,
        NU: 4,
        PUBL: 4,
        PU: 5,
        New: 5,
        NFE: 5,
        LC: 5,
        'LC Uber': 5,
    }

function searchTier(formatsData, pokemonid, findMega) {
    const pokemon = pokedex[pokemonid]
    const reverseTier = ['Uber', 'OU', 'UU', 'RU', 'NU', 'PU']
    let evos = pokemon.evos || []
    if (findMega) {
        evos = evos.concat(pokemon.otherFormes || [])
    }
    const currentTier = formatsData[pokemonid].tier
    const toSearch = evos.map(function recursiveSearch(evo) {
        return searchTier(formatsData, evo, findMega)
    }).concat(currentTier)
    return reverseTier[Math.min.apply(Math, toSearch.map(function toTierValue(tier) {
        if (tier.charAt(0) === '(') {
            tier = tier.slice(1, -1)
        }
        return tiers[tier]
    }))]
}

function hasMega(pokemon) {
    if (pokemon.species === 'Rayquaza') {
        return false // too broken
    }
    if (pokemon.otherFormes) {
        for (const id of pokemon.otherFormes) {
            const forme = pokedex[id]
            if (forme.forme.substring(0, 4) === 'Mega') {
                return formatsData[id].tier !== 'Unreleased'
            }
        }
        return false
    }
    const evos = pokemon.evos || []
    for (const evo of evos) {
        if (hasMega(pokedex[evo])) {
            return true
        }
    }
    return false
}

function gen(num) {
    if (num <= 151) return 1
    if (num <= 251) return 2
    if (num <= 386) return 3
    if (num <= 493) return 4
    if (num <= 649) return 5
    if (num <= 721) return 6
    return 7
}

const banned = {
    burmy: 1, caterpie: 1, combee: 1, kricketot: 1, magikarp: 1, scatterbug: 1,
    sunkern: 1, tynamo: 1, weedle: 1, wurmple: 1, typenull: 1, cosmog: 1,
    poipole: 1,
}
const legendaries = {
    articuno: 1, zapdos: 1, moltres: 1, mewtwo: 1, mew: 1, raikou: 1,
    entei: 1, suicune: 1, lugia: 1, hooh: 1, celebi: 1, regirock: 1,
    regice: 1, registeel: 1, latias: 1, latios: 1, kyogre: 1, groudon: 1,
    rayquaza: 1, jirachi: 1, deoxys: 1, deoxysattack: 1, deoxysdefense: 1,
    deoxysspeed: 1, uxie: 1, mesprit: 1, azelf: 1, dialga: 1, palkia: 1,
    heatran: 1, regigigas: 1, manaphy: 1, giratina: 1, giratinaorigin: 1,
    cresselia: 1, darkrai: 1, shaymin: 1, shayminsky: 1, arceus: 1,
    victini: 1, cobalion: 1, terrakion: 1, virizion: 1, tornadus: 1,
    thundurus: 1, tornadustherian: 1, thundurustherian: 1, reshiram: 1,
    zekrom: 1, landorus: 1, landorustherian: 1, kyurem: 1, kyuremblack: 1,
    kyuremwhite: 1, keldeo: 1, meloetta: 1, genesect: 1, xerneas: 1,
    yveltal: 1, zygarde: 1, diancie: 1, hoopa: 1, hoopaunbound: 1,
    silvally: 1, tapukoko: 1, tapulele: 1, tapubulu: 1, tapufini: 1,
    solgaleo: 1, lunala: 1, nihilego: 1, buzzwole: 1, pheromosa: 1,
    xurkitree: 1, celesteela: 1, kartana: 1, guzzlord: 1, necrozma: 1,
    magearna: 1, marshadow: 1, naganadel: 1, stakataka: 1, blacephalon: 1,
    zeraora: 1
}

const fs = require('fs')
const output = fs.openSync('_data/pokemon.yml', 'w')

for (const pokemonid in formatsData) {
    const pokemon = pokedex[pokemonid]
    const format = formatsData[pokemonid]
    if (!legendaries[pokemonid] && (!pokemon || pokemon.prevo || !pokemon.evos || pokemon.forme || format.isNonstandard || banned[pokemonid] || tiers[formatsData[pokemonid].tier] < 5)) continue

    const mega = false
    const tier = format.tier
    fs.writeSync(output, '- {name: ' + pokemon.species)
    fs.writeSync(output, ', legendary: ' + !!legendaries[pokemonid])
    const colors = new Map([[pokemon.color, pokemon.species]])
    for (const formeid of pokemon.otherFormes || []) {
        const formeColor = pokedex[formeid].color
        if (!colors.has(formeColor)) {
            colors.set(formeColor, pokedex[formeid].species)
        }
    }
    fs.writeSync(output, ', color: {')
    fs.writeSync(output, Array.from(colors).map(([color, specie]) => `${color}: ${specie}`).join(", "))
    fs.writeSync(output, '}, types: [' + pokemon.types.join(', ') + ']')
    const singlesTier = searchTier(formatsData, pokemonid, false)
    const doublesTier = searchTier(doublesFormatsData, pokemonid, false, [])
    fs.writeSync(output, ', tier: ' + singlesTier)
    fs.writeSync(output, ', doublesTier: ' + doublesTier)
    fs.writeSync(output, ', gen: ' + gen(pokemon.num))
    fs.writeSync(output, ', mega: ')
    if (hasMega(pokemon)) {
        fs.writeSync(output, '{tier: ' + searchTier(formatsData, pokemonid, true))
        fs.writeSync(output, ', doublesTier: ' + searchTier(formatsData, pokemonid, true))
        fs.writeSync(output, '}')
    } else {
        fs.writeSync(output, 'null')
    }
    fs.writeSync(output, '}\n')
}

fs.closeSync(output)
<|endoftext|>


<commit_before>/*
 * Copyright 2012 Sakai Foundation (SF) Licensed under the
 * Educational Community License, Version 2.0 (the "License"); you may
 * not use this file except in compliance with the License. You may
 * obtain a copy of the License at
 *
 *     http://www.osedu.org/licenses/ECL-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an "AS IS"
 * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing
 * permissions and limitations under the License.
 */

var argv = require('optimist')
    .usage('Run the Hilary tests.\nUsage: $0')
    .alias('m', 'module')
    .describe('m', 'Only run a specific module. Just specify the module name.')
    .argv;

var fs = require('fs');
var nodeunit = require('nodeunit');
var reporters = require('nodeunit/lib/reporters');

var cassandra = require('oae-util/lib/cassandra');
var OAE = require('oae-util/lib/OAE');
var tenantAPI = require('oae-tenants');

// The Cassandra connection config that should be used for unit tests, using
// a custom keyspace for just the tests
var config = {
    'hosts': ['127.0.0.1:9160'],
    'keyspace': 'oaeTest',
    'user': '',
    'pass': '',
    'system': '127.0.0.1:9160'
};

/**
 * Whenever an uncaught exception is encountered, we catch this here and
 * make sure that the process only quits when all of the necessary clean-up
 * has been done
 */
process.on('uncaughtException', function(err) {
  finishTests(err);
  return false;
});

/**
 * This is executed once all of the tests for all of the different modules have finished
 * running or when one of the tests has caused an error. It cleans up the test keypsace.
 * @param {Object}      err     Standard error object, containing the error message
 */
var finishTests = function(testErr) {
    // Log the error that has caused the scripts to fail
    if (testErr) {
        console.error(testErr.stack);
    }
    // Clean up after ourselves
    cassandra.dropKeyspace(config.keyspace, function(err) {
        if (err) {
            console.error(err);
        }
        // Finish the process
        process.exit(err || testErr ? 1 : 0);
    });

};

/**
 * Create 2 default tenants that can be used for testing our REST endpoints
 * @param {Object}      err     Standard error object, containing the error message for the
 *                              keyspace creation
 */
var setUpTenants = function(err) {
    if (err) {
        console.error(err);
        throw "Error on keyspace creation. Aborting unit tests.";
    }
    console.log("Cassandra set up, running tests.");

    tenantAPI.createTenant("camtest", "Cambridge University Test", "Cambridge University Description", 2001, "oae.cam.ac.uk", function() {
        tenantAPI.createTenant("gttest", "Georgia Tech Test", "Georgia Tech Description", 2002, "oae.gatech.edu", setUpTests);
    });
};

/**
 * Check whether or not we want to run the tests for 1 specific module or
 * all modules at the same time and then run the actual test(s)
 */
var setUpTests = function() {
    // Use the default test runner output.
    testrunner = reporters['default'];

    // Runs a set of tests.
    var runTests = function(files) {
        var options = {
            "error_prefix": "\u001B[31m",
            "error_suffix": "\u001B[39m",
            "ok_prefix": "\u001B[32m",
            "ok_suffix": "\u001B[39m",
            "bold_prefix": "\u001B[1m",
            "bold_suffix": "\u001B[22m",
            "assertion_prefix": "\u001B[35m",
            "assertion_suffix": "\u001B[39m"
        };
        testrunner.run(files, options, finishTests);
    };

    if (argv['module']) {
        // Single module.
        var file = 'node_modules/' + argv['module'] + '/tests';
        if (fs.existsSync(file)) {
            console.log("Running the tests for just the " + argv['module'] + " module.");
            runTests([file]);
        } else {
            console.log("\u001B[1m\u001B[31mCouldn't find that module.\u001B[39m\u001B[22m");
        }
    } else {
        // Run the tests for all the modules.
        OAE.getAvailableModules(function(modules) {
            var files = [];
            for (var i = 0; i < modules.length; i++) {
                var file = 'node_modules/' + modules[i] + '/tests';
                if (fs.existsSync(file)) {
                    files.push(file);
                } else {
                    console.warn("\u001B[1m\u001B[31mModule '" + modules[i] + "' has no tests.\u001B[39m\u001B[22m");
                }
            }

            // Run them.
            runTests(files);
        });
    }
};

// First set up the keyspace and all of the column families required
// for all of the different OAE modules
OAE.init(config, setUpTenants);<commit_msg>Making reference to 'OAE' module lower-case<commit_after>/*
 * Copyright 2012 Sakai Foundation (SF) Licensed under the
 * Educational Community License, Version 2.0 (the "License"); you may
 * not use this file except in compliance with the License. You may
 * obtain a copy of the License at
 *
 *     http://www.osedu.org/licenses/ECL-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an "AS IS"
 * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing
 * permissions and limitations under the License.
 */

var argv = require('optimist')
    .usage('Run the Hilary tests.\nUsage: $0')
    .alias('m', 'module')
    .describe('m', 'Only run a specific module. Just specify the module name.')
    .argv;

var fs = require('fs');
var nodeunit = require('nodeunit');
var reporters = require('nodeunit/lib/reporters');

var cassandra = require('oae-util/lib/cassandra');
var OAE = require('oae-util/lib/oae');
var tenantAPI = require('oae-tenants');

// The Cassandra connection config that should be used for unit tests, using
// a custom keyspace for just the tests
var config = {
    'hosts': ['127.0.0.1:9160'],
    'keyspace': 'oaeTest',
    'user': '',
    'pass': '',
    'system': '127.0.0.1:9160'
};

/**
 * Whenever an uncaught exception is encountered, we catch this here and
 * make sure that the process only quits when all of the necessary clean-up
 * has been done
 */
process.on('uncaughtException', function(err) {
  finishTests(err);
  return false;
});

/**
 * This is executed once all of the tests for all of the different modules have finished
 * running or when one of the tests has caused an error. It cleans up the test keypsace.
 * @param {Object}      err     Standard error object, containing the error message
 */
var finishTests = function(testErr) {
    // Log the error that has caused the scripts to fail
    if (testErr) {
        console.error(testErr.stack);
    }
    // Clean up after ourselves
    cassandra.dropKeyspace(config.keyspace, function(err) {
        if (err) {
            console.error(err);
        }
        // Finish the process
        process.exit(err || testErr ? 1 : 0);
    });

};

/**
 * Create 2 default tenants that can be used for testing our REST endpoints
 * @param {Object}      err     Standard error object, containing the error message for the
 *                              keyspace creation
 */
var setUpTenants = function(err) {
    if (err) {
        console.error(err);
        throw "Error on keyspace creation. Aborting unit tests.";
    }
    console.log("Cassandra set up, running tests.");

    tenantAPI.createTenant("camtest", "Cambridge University Test", "Cambridge University Description", 2001, "oae.cam.ac.uk", function() {
        tenantAPI.createTenant("gttest", "Georgia Tech Test", "Georgia Tech Description", 2002, "oae.gatech.edu", setUpTests);
    });
};

/**
 * Check whether or not we want to run the tests for 1 specific module or
 * all modules at the same time and then run the actual test(s)
 */
var setUpTests = function() {
    // Use the default test runner output.
    testrunner = reporters['default'];

    // Runs a set of tests.
    var runTests = function(files) {
        var options = {
            "error_prefix": "\u001B[31m",
            "error_suffix": "\u001B[39m",
            "ok_prefix": "\u001B[32m",
            "ok_suffix": "\u001B[39m",
            "bold_prefix": "\u001B[1m",
            "bold_suffix": "\u001B[22m",
            "assertion_prefix": "\u001B[35m",
            "assertion_suffix": "\u001B[39m"
        };
        testrunner.run(files, options, finishTests);
    };

    if (argv['module']) {
        // Single module.
        var file = 'node_modules/' + argv['module'] + '/tests';
        if (fs.existsSync(file)) {
            console.log("Running the tests for just the " + argv['module'] + " module.");
            runTests([file]);
        } else {
            console.log("\u001B[1m\u001B[31mCouldn't find that module.\u001B[39m\u001B[22m");
        }
    } else {
        // Run the tests for all the modules.
        OAE.getAvailableModules(function(modules) {
            var files = [];
            for (var i = 0; i < modules.length; i++) {
                var file = 'node_modules/' + modules[i] + '/tests';
                if (fs.existsSync(file)) {
                    files.push(file);
                } else {
                    console.warn("\u001B[1m\u001B[31mModule '" + modules[i] + "' has no tests.\u001B[39m\u001B[22m");
                }
            }

            // Run them.
            runTests(files);
        });
    }
};

// First set up the keyspace and all of the column families required
// for all of the different OAE modules
OAE.init(config, setUpTenants);
<|endoftext|>


<commit_before>const GitUrlParse = require("git-url-parse");
const get = require('./get');
const lget = require('lodash.get');
function getRepoUrl () {
    return lget(get.sync(),'remote.origin.url');
}

module.exports = getRepoUrl;<commit_msg>add docs<commit_after> /**
 * Get git url of current project.
 * @function getRepoUrl
 * @returns {String}
 */
const GitUrlParse = require("git-url-parse");
const get = require('./get');
const lget = require('lodash.get');
function getRepoUrl () {
    return lget(get.sync(),'remote.origin.url');
}

module.exports = getRepoUrl;<|endoftext|>