UNPKG

pdfer-login-imacros

Version:

Login to the pdfer service using iMacros for Firefox

1,916 lines (1,622 loc) 103 kB
;(function(e,t,n,r){function i(r){if(!n[r]){if(!t[r]){if(e)return e(r);throw new Error("Cannot find module '"+r+"'")}var s=n[r]={exports:{}};t[r][0](function(e){var n=t[r][1][e];return i(n?n:e)},s,s.exports)}return n[r].exports}for(var s=0;s<r.length;s++)i(r[s]);return i})(typeof require!=="undefined"&&require,{1:[function(require,module,exports){var should = require('should'); var readFile = require('imacros-read-file'); var login = require('../index'); iimPlay('CODE: URL GOTO=http://www.google.com'); runTests(function (err, reply) { if (err) { alert('check test suite fails with error: ' + JSON.stringify(err)); return false; } iimDisplay('Success! Checks test suite passes'); }); function runTests(cb) { iimDisplay('running login tests'); var filePath = 'file:///users/noah/src/node/docparse/scrapers/imacros/pdfer/login/test/config.json' iimDisplay('loading config file'); loadConfigFile(filePath, function (err, config) { iimDisplay('config file loaded'); if (err) { return cb(err); } iimDisplay('performing login'); login(config, function (err, reply) { iimDisplay('login complete'); if (err) { return cb(err); } login(config, cb); }); }); } function loadConfigFile(filePath, cb) { readFile(filePath, function (err, reply) { if (err) { return cb(err); } var data = JSON.parse(reply); cb(null, data); }); } },{"should":2,"imacros-read-file":3,"../index":4}],2:[function(require,module,exports){/*! * Should * Copyright(c) 2010-2012 TJ Holowaychuk <tj@vision-media.ca> * MIT Licensed */ /** * Module dependencies. */ var util = require('util') , http = require('http') , assert = require('assert') , AssertionError = assert.AssertionError , statusCodes = http.STATUS_CODES , eql = require('./eql') , i = util.inspect; /** * Expose assert as should. * * This allows you to do things like below * without require()ing the assert module. * * should.equal(foo.bar, undefined); * */ exports = module.exports = assert; /** * Assert _obj_ exists, with optional message. * * @param {Mixed} obj * @param {String} [msg] * @api public */ exports.exist = exports.exists = function(obj, msg){ if (null == obj) { throw new AssertionError({ message: msg || ('expected ' + i(obj) + ' to exist') , stackStartFunction: exports.exist }); } }; /** * Asserts _obj_ does not exist, with optional message. * * @param {Mixed} obj * @param {String} [msg] * @api public */ exports.not = {}; exports.not.exist = exports.not.exists = function(obj, msg){ if (null != obj) { throw new AssertionError({ message: msg || ('expected ' + i(obj) + ' to not exist') , stackStartFunction: exports.not.exist }); } }; /** * Expose api via `Object#should`. * * @api public */ Object.defineProperty(Object.prototype, 'should', { set: function(){}, get: function(){ return new Assertion(this.valueOf() == this ? this.valueOf() : this); }, configurable: true }); /** * Initialize a new `Assertion` with the given _obj_. * * @param {Mixed} obj * @api private */ var Assertion = exports.Assertion = function Assertion(obj) { this.obj = obj; }; /** * Prototype. */ Assertion.prototype = { /** * HACK: prevents double require() from failing. */ exports: exports, /** * Assert _expr_ with the given _msg_ and _negatedMsg_. * * @param {Boolean} expr * @param {String} msg * @param {String} negatedMsg * @param {Object} expected * @api private */ assert: function(expr, msg, negatedMsg, expected, showDiff){ var msg = this.negate ? negatedMsg : msg , ok = this.negate ? !expr : expr , obj = this.obj; if (ok) return; var err = new AssertionError({ message: msg.call(this) , actual: obj , expected: expected , stackStartFunction: this.assert , negated: this.negate }); err.showDiff = showDiff; throw err; }, /** * Dummy getter. * * @api public */ get an() { return this; }, /** * Dummy getter. * * @api public */ get and() { return this; }, /** * Dummy getter. * * @api public */ get be() { return this; }, /** * Dummy getter. * * @api public */ get have() { return this; }, /** * Dummy getter. * * @api public */ get with() { return this; }, /** * Negation modifier. * * @api public */ get not() { this.negate = true; return this; }, /** * Get object inspection string. * * @return {String} * @api private */ get inspect() { return i(this.obj); }, /** * Assert instanceof `Arguments`. * * @api public */ get arguments() { this.assert( '[object Arguments]' == Object.prototype.toString.call(this.obj) , function(){ return 'expected ' + this.inspect + ' to be arguments' } , function(){ return 'expected ' + this.inspect + ' to not be arguments' }); return this; }, /** * Assert that an object is empty aka length of 0. * * @api public */ get empty() { this.obj.should.have.property('length'); this.assert( 0 === this.obj.length , function(){ return 'expected ' + this.inspect + ' to be empty' } , function(){ return 'expected ' + this.inspect + ' not to be empty' }); return this; }, /** * Assert ok. * * @api public */ get ok() { this.assert( this.obj , function(){ return 'expected ' + this.inspect + ' to be truthy' } , function(){ return 'expected ' + this.inspect + ' to be falsey' }); return this; }, /** * Assert true. * * @api public */ get true() { this.assert( true === this.obj , function(){ return 'expected ' + this.inspect + ' to be true' } , function(){ return 'expected ' + this.inspect + ' not to be true' }); return this; }, /** * Assert false. * * @api public */ get false() { this.assert( false === this.obj , function(){ return 'expected ' + this.inspect + ' to be false' } , function(){ return 'expected ' + this.inspect + ' not to be false' }); return this; }, /** * Assert equal. * * @param {Mixed} val * @param {String} description * @api public */ eql: function(val, desc){ this.assert( eql(val, this.obj) , function(){ return 'expected ' + this.inspect + ' to equal ' + i(val) + (desc ? " | " + desc : "") } , function(){ return 'expected ' + this.inspect + ' to not equal ' + i(val) + (desc ? " | " + desc : "") } , val , true); return this; }, /** * Assert strict equal. * * @param {Mixed} val * @param {String} description * @api public */ equal: function(val, desc){ this.assert( val === this.obj , function(){ return 'expected ' + this.inspect + ' to equal ' + i(val) + (desc ? " | " + desc : "") } , function(){ return 'expected ' + this.inspect + ' to not equal ' + i(val) + (desc ? " | " + desc : "") } , val); return this; }, /** * Assert within start to finish (inclusive). * * @param {Number} start * @param {Number} finish * @param {String} description * @api public */ within: function(start, finish, desc){ var range = start + '..' + finish; this.assert( this.obj >= start && this.obj <= finish , function(){ return 'expected ' + this.inspect + ' to be within ' + range + (desc ? " | " + desc : "") } , function(){ return 'expected ' + this.inspect + ' to not be within ' + range + (desc ? " | " + desc : "") }); return this; }, /** * Assert within value +- delta (inclusive). * * @param {Number} value * @param {Number} delta * @param {String} description * @api public */ approximately: function(value, delta, description) { return this.within(value - delta, value + delta, description); }, /** * Assert typeof. * * @param {Mixed} type * @param {String} description * @api public */ a: function(type, desc){ this.assert( type == typeof this.obj , function(){ return 'expected ' + this.inspect + ' to be a ' + type + (desc ? " | " + desc : "") } , function(){ return 'expected ' + this.inspect + ' not to be a ' + type + (desc ? " | " + desc : "") }) return this; }, /** * Assert instanceof. * * @param {Function} constructor * @param {String} description * @api public */ instanceof: function(constructor, desc){ var name = constructor.name; this.assert( this.obj instanceof constructor , function(){ return 'expected ' + this.inspect + ' to be an instance of ' + name + (desc ? " | " + desc : "") } , function(){ return 'expected ' + this.inspect + ' not to be an instance of ' + name + (desc ? " | " + desc : "") }); return this; }, /** * Assert numeric value above _n_. * * @param {Number} n * @param {String} description * @api public */ above: function(n, desc){ this.assert( this.obj > n , function(){ return 'expected ' + this.inspect + ' to be above ' + n + (desc ? " | " + desc : "") } , function(){ return 'expected ' + this.inspect + ' to be below ' + n + (desc ? " | " + desc : "") }); return this; }, /** * Assert numeric value below _n_. * * @param {Number} n * @param {String} description * @api public */ below: function(n, desc){ this.assert( this.obj < n , function(){ return 'expected ' + this.inspect + ' to be below ' + n + (desc ? " | " + desc : "") } , function(){ return 'expected ' + this.inspect + ' to be above ' + n + (desc ? " | " + desc : "") }); return this; }, /** * Assert string value matches _regexp_. * * @param {RegExp} regexp * @param {String} description * @api public */ match: function(regexp, desc){ this.assert( regexp.exec(this.obj) , function(){ return 'expected ' + this.inspect + ' to match ' + regexp + (desc ? " | " + desc : "") } , function(){ return 'expected ' + this.inspect + ' not to match ' + regexp + (desc ? " | " + desc : "") }); return this; }, /** * Assert property "length" exists and has value of _n_. * * @param {Number} n * @param {String} description * @api public */ length: function(n, desc){ this.obj.should.have.property('length'); var len = this.obj.length; this.assert( n == len , function(){ return 'expected ' + this.inspect + ' to have a length of ' + n + ' but got ' + len + (desc ? " | " + desc : "") } , function(){ return 'expected ' + this.inspect + ' to not have a length of ' + len + (desc ? " | " + desc : "") }); return this; }, /** * Assert property _name_ exists, with optional _val_. * * @param {String} name * @param {Mixed} [val] * @param {String} description * @api public */ property: function(name, val, desc){ if (this.negate && undefined !== val) { if (undefined === this.obj[name]) { throw new Error(this.inspect + ' has no property ' + i(name) + (desc ? " | " + desc : "")); } } else { this.assert( undefined !== this.obj[name] , function(){ return 'expected ' + this.inspect + ' to have a property ' + i(name) + (desc ? " | " + desc : "") } , function(){ return 'expected ' + this.inspect + ' to not have a property ' + i(name) + (desc ? " | " + desc : "") }); } if (undefined !== val) { this.assert( val === this.obj[name] , function(){ return 'expected ' + this.inspect + ' to have a property ' + i(name) + ' of ' + i(val) + ', but got ' + i(this.obj[name]) + (desc ? " | " + desc : "") } , function(){ return 'expected ' + this.inspect + ' to not have a property ' + i(name) + ' of ' + i(val) + (desc ? " | " + desc : "") }); } this.obj = this.obj[name]; return this; }, /** * Assert own property _name_ exists. * * @param {String} name * @param {String} description * @api public */ ownProperty: function(name, desc){ this.assert( this.obj.hasOwnProperty(name) , function(){ return 'expected ' + this.inspect + ' to have own property ' + i(name) + (desc ? " | " + desc : "") } , function(){ return 'expected ' + this.inspect + ' to not have own property ' + i(name) + (desc ? " | " + desc : "") }); this.obj = this.obj[name]; return this; }, /** * Assert that `obj` is present via `.indexOf()`. * * @param {Mixed} obj * @param {String} description * @api public */ include: function(obj, desc){ if (obj.constructor == Object){ var cmp = {}; for (var key in obj) cmp[key] = this.obj[key]; this.assert( eql(cmp, obj) , function(){ return 'expected ' + this.inspect + ' to include an object equal to ' + i(obj) + (desc ? " | " + desc : "") } , function(){ return 'expected ' + this.inspect + ' to not include an object equal to ' + i(obj) + (desc ? " | " + desc : "") }); } else { this.assert( ~this.obj.indexOf(obj) , function(){ return 'expected ' + this.inspect + ' to include ' + i(obj) + (desc ? " | " + desc : "") } , function(){ return 'expected ' + this.inspect + ' to not include ' + i(obj) + (desc ? " | " + desc : "") }); } return this; }, /** * Assert that an object equal to `obj` is present. * * @param {Array} obj * @param {String} description * @api public */ includeEql: function(obj, desc){ this.assert( this.obj.some(function(item) { return eql(obj, item); }) , function(){ return 'expected ' + this.inspect + ' to include an object equal to ' + i(obj) + (desc ? " | " + desc : "") } , function(){ return 'expected ' + this.inspect + ' to not include an object equal to ' + i(obj) + (desc ? " | " + desc : "") }); return this; }, /** * Assert that the array contains _obj_. * * @param {Mixed} obj * @api public */ contain: function(obj){ console.warn('should.contain() is deprecated, use should.include()'); this.obj.should.be.an.instanceof(Array); this.assert( ~this.obj.indexOf(obj) , function(){ return 'expected ' + this.inspect + ' to contain ' + i(obj) } , function(){ return 'expected ' + this.inspect + ' to not contain ' + i(obj) }); return this; }, /** * Assert exact keys or inclusion of keys by using * the `.include` modifier. * * @param {Array|String ...} keys * @api public */ keys: function(keys){ var str , ok = true; keys = keys instanceof Array ? keys : Array.prototype.slice.call(arguments); if (!keys.length) throw new Error('keys required'); var actual = Object.keys(this.obj) , len = keys.length; // make sure they're all present ok = keys.every(function(key){ return ~actual.indexOf(key); }); // matching length ok = ok && keys.length == actual.length; // key string if (len > 1) { keys = keys.map(function(key){ return i(key); }); var last = keys.pop(); str = keys.join(', ') + ', and ' + last; } else { str = i(keys[0]); } // message str = 'have ' + (len > 1 ? 'keys ' : 'key ') + str; this.assert( ok , function(){ return 'expected ' + this.inspect + ' to ' + str } , function(){ return 'expected ' + this.inspect + ' to not ' + str }); return this; }, /** * Assert that header `field` has the given `val`. * * @param {String} field * @param {String} val * @return {Assertion} for chaining * @api public */ header: function(field, val){ this.obj.should .have.property('headers').and .have.property(field.toLowerCase(), val); return this; }, /** * Assert `.statusCode` of `code`. * * @param {Number} code * @return {Assertion} for chaining * @api public */ status: function(code){ this.obj.should.have.property('statusCode'); var status = this.obj.statusCode; this.assert( code == status , function(){ return 'expected response code of ' + code + ' ' + i(statusCodes[code]) + ', but got ' + status + ' ' + i(statusCodes[status]) } , function(){ return 'expected to not respond with ' + code + ' ' + i(statusCodes[code]) }); return this; }, /** * Assert that this response has content-type: application/json. * * @return {Assertion} for chaining * @api public */ get json() { this.obj.should.have.property('headers'); this.obj.headers.should.have.property('content-type'); this.obj.headers['content-type'].should.include('application/json'); return this; }, /** * Assert that this response has content-type: text/html. * * @return {Assertion} for chaining * @api public */ get html() { this.obj.should.have.property('headers'); this.obj.headers.should.have.property('content-type'); this.obj.headers['content-type'].should.include('text/html'); return this; }, /** * Assert that this function will or will not * throw an exception. * * @return {Assertion} for chaining * @api public */ throw: function(message){ var fn = this.obj , err = {} , errorInfo = '' , ok = true; try { fn(); ok = false; } catch (e) { err = e; } if (ok) { if ('string' == typeof message) { ok = message == err.message; } else if (message instanceof RegExp) { ok = message.test(err.message); } else if ('function' == typeof message) { ok = err instanceof message; } if (message && !ok) { if ('string' == typeof message) { errorInfo = " with a message matching '" + message + "', but got '" + err.message + "'"; } else if (message instanceof RegExp) { errorInfo = " with a message matching " + message + ", but got '" + err.message + "'"; } else if ('function' == typeof message) { errorInfo = " of type " + message.name + ", but got " + err.constructor.name; } } } this.assert( ok , function(){ return 'expected an exception to be thrown' + errorInfo } , function(){ return 'expected no exception to be thrown, got "' + err.message + '"' }); return this; } }; /** * Aliases. */ (function alias(name, as){ Assertion.prototype[as] = Assertion.prototype[name]; return alias; }) ('instanceof', 'instanceOf') ('throw', 'throwError') ('length', 'lengthOf') ('keys', 'key') ('ownProperty', 'haveOwnProperty') ('above', 'greaterThan') ('below', 'lessThan'); },{"util":5,"http":6,"assert":7,"./eql":8}],5:[function(require,module,exports){var events = require('events'); exports.isArray = isArray; exports.isDate = function(obj){return Object.prototype.toString.call(obj) === '[object Date]'}; exports.isRegExp = function(obj){return Object.prototype.toString.call(obj) === '[object RegExp]'}; exports.print = function () {}; exports.puts = function () {}; exports.debug = function() {}; exports.inspect = function(obj, showHidden, depth, colors) { var seen = []; var stylize = function(str, styleType) { // http://en.wikipedia.org/wiki/ANSI_escape_code#graphics var styles = { 'bold' : [1, 22], 'italic' : [3, 23], 'underline' : [4, 24], 'inverse' : [7, 27], 'white' : [37, 39], 'grey' : [90, 39], 'black' : [30, 39], 'blue' : [34, 39], 'cyan' : [36, 39], 'green' : [32, 39], 'magenta' : [35, 39], 'red' : [31, 39], 'yellow' : [33, 39] }; var style = { 'special': 'cyan', 'number': 'blue', 'boolean': 'yellow', 'undefined': 'grey', 'null': 'bold', 'string': 'green', 'date': 'magenta', // "name": intentionally not styling 'regexp': 'red' }[styleType]; if (style) { return '\033[' + styles[style][0] + 'm' + str + '\033[' + styles[style][1] + 'm'; } else { return str; } }; if (! colors) { stylize = function(str, styleType) { return str; }; } function format(value, recurseTimes) { // Provide a hook for user-specified inspect functions. // Check that value is an object with an inspect function on it if (value && typeof value.inspect === 'function' && // Filter out the util module, it's inspect function is special value !== exports && // Also filter out any prototype objects using the circular check. !(value.constructor && value.constructor.prototype === value)) { return value.inspect(recurseTimes); } // Primitive types cannot have properties switch (typeof value) { case 'undefined': return stylize('undefined', 'undefined'); case 'string': var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') .replace(/'/g, "\\'") .replace(/\\"/g, '"') + '\''; return stylize(simple, 'string'); case 'number': return stylize('' + value, 'number'); case 'boolean': return stylize('' + value, 'boolean'); } // For some reason typeof null is "object", so special case here. if (value === null) { return stylize('null', 'null'); } // Look up the keys of the object. var visible_keys = Object_keys(value); var keys = showHidden ? Object_getOwnPropertyNames(value) : visible_keys; // Functions without properties can be shortcutted. if (typeof value === 'function' && keys.length === 0) { if (isRegExp(value)) { return stylize('' + value, 'regexp'); } else { var name = value.name ? ': ' + value.name : ''; return stylize('[Function' + name + ']', 'special'); } } // Dates without properties can be shortcutted if (isDate(value) && keys.length === 0) { return stylize(value.toUTCString(), 'date'); } var base, type, braces; // Determine the object type if (isArray(value)) { type = 'Array'; braces = ['[', ']']; } else { type = 'Object'; braces = ['{', '}']; } // Make functions say that they are functions if (typeof value === 'function') { var n = value.name ? ': ' + value.name : ''; base = (isRegExp(value)) ? ' ' + value : ' [Function' + n + ']'; } else { base = ''; } // Make dates with properties first say the date if (isDate(value)) { base = ' ' + value.toUTCString(); } if (keys.length === 0) { return braces[0] + base + braces[1]; } if (recurseTimes < 0) { if (isRegExp(value)) { return stylize('' + value, 'regexp'); } else { return stylize('[Object]', 'special'); } } seen.push(value); var output = keys.map(function(key) { var name, str; if (value.__lookupGetter__) { if (value.__lookupGetter__(key)) { if (value.__lookupSetter__(key)) { str = stylize('[Getter/Setter]', 'special'); } else { str = stylize('[Getter]', 'special'); } } else { if (value.__lookupSetter__(key)) { str = stylize('[Setter]', 'special'); } } } if (visible_keys.indexOf(key) < 0) { name = '[' + key + ']'; } if (!str) { if (seen.indexOf(value[key]) < 0) { if (recurseTimes === null) { str = format(value[key]); } else { str = format(value[key], recurseTimes - 1); } if (str.indexOf('\n') > -1) { if (isArray(value)) { str = str.split('\n').map(function(line) { return ' ' + line; }).join('\n').substr(2); } else { str = '\n' + str.split('\n').map(function(line) { return ' ' + line; }).join('\n'); } } } else { str = stylize('[Circular]', 'special'); } } if (typeof name === 'undefined') { if (type === 'Array' && key.match(/^\d+$/)) { return str; } name = JSON.stringify('' + key); if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { name = name.substr(1, name.length - 2); name = stylize(name, 'name'); } else { name = name.replace(/'/g, "\\'") .replace(/\\"/g, '"') .replace(/(^"|"$)/g, "'"); name = stylize(name, 'string'); } } return name + ': ' + str; }); seen.pop(); var numLinesEst = 0; var length = output.reduce(function(prev, cur) { numLinesEst++; if (cur.indexOf('\n') >= 0) numLinesEst++; return prev + cur.length + 1; }, 0); if (length > 50) { output = braces[0] + (base === '' ? '' : base + '\n ') + ' ' + output.join(',\n ') + ' ' + braces[1]; } else { output = braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; } return output; } return format(obj, (typeof depth === 'undefined' ? 2 : depth)); }; function isArray(ar) { return ar instanceof Array || Array.isArray(ar) || (ar && ar !== Object.prototype && isArray(ar.__proto__)); } function isRegExp(re) { return re instanceof RegExp || (typeof re === 'object' && Object.prototype.toString.call(re) === '[object RegExp]'); } function isDate(d) { if (d instanceof Date) return true; if (typeof d !== 'object') return false; var properties = Date.prototype && Object_getOwnPropertyNames(Date.prototype); var proto = d.__proto__ && Object_getOwnPropertyNames(d.__proto__); return JSON.stringify(proto) === JSON.stringify(properties); } function pad(n) { return n < 10 ? '0' + n.toString(10) : n.toString(10); } var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; // 26 Feb 16:19:34 function timestamp() { var d = new Date(); var time = [pad(d.getHours()), pad(d.getMinutes()), pad(d.getSeconds())].join(':'); return [d.getDate(), months[d.getMonth()], time].join(' '); } exports.log = function (msg) {}; exports.pump = null; var Object_keys = Object.keys || function (obj) { var res = []; for (var key in obj) res.push(key); return res; }; var Object_getOwnPropertyNames = Object.getOwnPropertyNames || function (obj) { var res = []; for (var key in obj) { if (Object.hasOwnProperty.call(obj, key)) res.push(key); } return res; }; var Object_create = Object.create || function (prototype, properties) { // from es5-shim var object; if (prototype === null) { object = { '__proto__' : null }; } else { if (typeof prototype !== 'object') { throw new TypeError( 'typeof prototype[' + (typeof prototype) + '] != \'object\'' ); } var Type = function () {}; Type.prototype = prototype; object = new Type(); object.__proto__ = prototype; } if (typeof properties !== 'undefined' && Object.defineProperties) { Object.defineProperties(object, properties); } return object; }; exports.inherits = function(ctor, superCtor) { ctor.super_ = superCtor; ctor.prototype = Object_create(superCtor.prototype, { constructor: { value: ctor, enumerable: false, writable: true, configurable: true } }); }; var formatRegExp = /%[sdj%]/g; exports.format = function(f) { if (typeof f !== 'string') { var objects = []; for (var i = 0; i < arguments.length; i++) { objects.push(exports.inspect(arguments[i])); } return objects.join(' '); } var i = 1; var args = arguments; var len = args.length; var str = String(f).replace(formatRegExp, function(x) { if (x === '%%') return '%'; if (i >= len) return x; switch (x) { case '%s': return String(args[i++]); case '%d': return Number(args[i++]); case '%j': return JSON.stringify(args[i++]); default: return x; } }); for(var x = args[i]; i < len; x = args[++i]){ if (x === null || typeof x !== 'object') { str += ' ' + x; } else { str += ' ' + exports.inspect(x); } } return str; }; },{"events":9}],9:[function(require,module,exports){(function(process){if (!process.EventEmitter) process.EventEmitter = function () {}; var EventEmitter = exports.EventEmitter = process.EventEmitter; var isArray = typeof Array.isArray === 'function' ? Array.isArray : function (xs) { return Object.prototype.toString.call(xs) === '[object Array]' } ; function indexOf (xs, x) { if (xs.indexOf) return xs.indexOf(x); for (var i = 0; i < xs.length; i++) { if (x === xs[i]) return i; } return -1; } // By default EventEmitters will print a warning if more than // 10 listeners are added to it. This is a useful default which // helps finding memory leaks. // // Obviously not all Emitters should be limited to 10. This function allows // that to be increased. Set to zero for unlimited. var defaultMaxListeners = 10; EventEmitter.prototype.setMaxListeners = function(n) { if (!this._events) this._events = {}; this._events.maxListeners = n; }; EventEmitter.prototype.emit = function(type) { // If there is no 'error' event listener then throw. if (type === 'error') { if (!this._events || !this._events.error || (isArray(this._events.error) && !this._events.error.length)) { if (arguments[1] instanceof Error) { throw arguments[1]; // Unhandled 'error' event } else { throw new Error("Uncaught, unspecified 'error' event."); } return false; } } if (!this._events) return false; var handler = this._events[type]; if (!handler) return false; if (typeof handler == 'function') { switch (arguments.length) { // fast cases case 1: handler.call(this); break; case 2: handler.call(this, arguments[1]); break; case 3: handler.call(this, arguments[1], arguments[2]); break; // slower default: var args = Array.prototype.slice.call(arguments, 1); handler.apply(this, args); } return true; } else if (isArray(handler)) { var args = Array.prototype.slice.call(arguments, 1); var listeners = handler.slice(); for (var i = 0, l = listeners.length; i < l; i++) { listeners[i].apply(this, args); } return true; } else { return false; } }; // EventEmitter is defined in src/node_events.cc // EventEmitter.prototype.emit() is also defined there. EventEmitter.prototype.addListener = function(type, listener) { if ('function' !== typeof listener) { throw new Error('addListener only takes instances of Function'); } if (!this._events) this._events = {}; // To avoid recursion in the case that type == "newListeners"! Before // adding it to the listeners, first emit "newListeners". this.emit('newListener', type, listener); if (!this._events[type]) { // Optimize the case of one listener. Don't need the extra array object. this._events[type] = listener; } else if (isArray(this._events[type])) { // Check for listener leak if (!this._events[type].warned) { var m; if (this._events.maxListeners !== undefined) { m = this._events.maxListeners; } else { m = defaultMaxListeners; } if (m && m > 0 && this._events[type].length > m) { this._events[type].warned = true; console.error('(node) warning: possible EventEmitter memory ' + 'leak detected. %d listeners added. ' + 'Use emitter.setMaxListeners() to increase limit.', this._events[type].length); console.trace(); } } // If we've already got an array, just append. this._events[type].push(listener); } else { // Adding the second element, need to change to array. this._events[type] = [this._events[type], listener]; } return this; }; EventEmitter.prototype.on = EventEmitter.prototype.addListener; EventEmitter.prototype.once = function(type, listener) { var self = this; self.on(type, function g() { self.removeListener(type, g); listener.apply(this, arguments); }); return this; }; EventEmitter.prototype.removeListener = function(type, listener) { if ('function' !== typeof listener) { throw new Error('removeListener only takes instances of Function'); } // does not use listeners(), so no side effect of creating _events[type] if (!this._events || !this._events[type]) return this; var list = this._events[type]; if (isArray(list)) { var i = indexOf(list, listener); if (i < 0) return this; list.splice(i, 1); if (list.length == 0) delete this._events[type]; } else if (this._events[type] === listener) { delete this._events[type]; } return this; }; EventEmitter.prototype.removeAllListeners = function(type) { if (arguments.length === 0) { this._events = {}; return this; } // does not use listeners(), so no side effect of creating _events[type] if (type && this._events && this._events[type]) this._events[type] = null; return this; }; EventEmitter.prototype.listeners = function(type) { if (!this._events) this._events = {}; if (!this._events[type]) this._events[type] = []; if (!isArray(this._events[type])) { this._events[type] = [this._events[type]]; } return this._events[type]; }; })(require("__browserify_process")) },{"__browserify_process":10}],10:[function(require,module,exports){// shim for using process in browser var process = module.exports = {}; process.nextTick = (function () { var canSetImmediate = typeof window !== 'undefined' && window.setImmediate; var canPost = typeof window !== 'undefined' && window.postMessage && window.addEventListener ; if (canSetImmediate) { return function (f) { return window.setImmediate(f) }; } if (canPost) { var queue = []; window.addEventListener('message', function (ev) { if (ev.source === window && ev.data === 'process-tick') { ev.stopPropagation(); if (queue.length > 0) { var fn = queue.shift(); fn(); } } }, true); return function nextTick(fn) { queue.push(fn); window.postMessage('process-tick', '*'); }; } return function nextTick(fn) { setTimeout(fn, 0); }; })(); process.title = 'browser'; process.browser = true; process.env = {}; process.argv = []; process.binding = function (name) { throw new Error('process.binding is not supported'); } // TODO(shtylman) process.cwd = function () { return '/' }; process.chdir = function (dir) { throw new Error('process.chdir is not supported'); }; },{}],6:[function(require,module,exports){var http = module.exports; var EventEmitter = require('events').EventEmitter; var Request = require('./lib/request'); http.request = function (params, cb) { if (!params) params = {}; if (!params.host) params.host = window.location.host.split(':')[0]; if (!params.port) params.port = window.location.port; var req = new Request(new xhrHttp, params); if (cb) req.on('response', cb); return req; }; http.get = function (params, cb) { params.method = 'GET'; var req = http.request(params, cb); req.end(); return req; }; http.Agent = function () {}; http.Agent.defaultMaxSockets = 4; var xhrHttp = (function () { if (typeof window === 'undefined') { throw new Error('no window object present'); } else if (window.XMLHttpRequest) { return window.XMLHttpRequest; } else if (window.ActiveXObject) { var axs = [ 'Msxml2.XMLHTTP.6.0', 'Msxml2.XMLHTTP.3.0', 'Microsoft.XMLHTTP' ]; for (var i = 0; i < axs.length; i++) { try { var ax = new(window.ActiveXObject)(axs[i]); return function () { if (ax) { var ax_ = ax; ax = null; return ax_; } else { return new(window.ActiveXObject)(axs[i]); } }; } catch (e) {} } throw new Error('ajax not supported in this browser') } else { throw new Error('ajax not supported in this browser'); } })(); },{"events":9,"./lib/request":11}],11:[function(require,module,exports){var Stream = require('stream'); var Response = require('./response'); var concatStream = require('concat-stream') var Request = module.exports = function (xhr, params) { var self = this; self.writable = true; self.xhr = xhr; self.body = concatStream() var uri = params.host + ':' + params.port + (params.path || '/'); xhr.open( params.method || 'GET', (params.scheme || 'http') + '://' + uri, true ); if (params.headers) { var keys = objectKeys(params.headers); for (var i = 0; i < keys.length; i++) { var key = keys[i]; if (!self.isSafeRequestHeader(key)) return; var value = params.headers[key]; if (isArray(value)) { for (var j = 0; j < value.length; j++) { xhr.setRequestHeader(key, value[j]); } } else xhr.setRequestHeader(key, value) } } var res = new Response; res.on('close', function () { self.emit('close'); }); res.on('ready', function () { self.emit('response', res); }); xhr.onreadystatechange = function () { res.handle(xhr); }; }; Request.prototype = new Stream; Request.prototype.setHeader = function (key, value) { if (isArray(value)) { for (var i = 0; i < value.length; i++) { this.xhr.setRequestHeader(key, value[i]); } } else { this.xhr.setRequestHeader(key, value); } }; Request.prototype.write = function (s) { this.body.write(s); }; Request.prototype.destroy = function (s) { this.xhr.abort(); this.emit('close'); }; Request.prototype.end = function (s) { if (s !== undefined) this.body.write(s); this.body.end() this.xhr.send(this.body.getBody()); }; // Taken from http://dxr.mozilla.org/mozilla/mozilla-central/content/base/src/nsXMLHttpRequest.cpp.html Request.unsafeHeaders = [ "accept-charset", "accept-encoding", "access-control-request-headers", "access-control-request-method", "connection", "content-length", "cookie", "cookie2", "content-transfer-encoding", "date", "expect", "host", "keep-alive", "origin", "referer", "te", "trailer", "transfer-encoding", "upgrade", "user-agent", "via" ]; Request.prototype.isSafeRequestHeader = function (headerName) { if (!headerName) return false; return indexOf(Request.unsafeHeaders, headerName.toLowerCase()) === -1; }; var objectKeys = Object.keys || function (obj) { var keys = []; for (var key in obj) keys.push(key); return keys; }; var isArray = Array.isArray || function (xs) { return Object.prototype.toString.call(xs) === '[object Array]'; }; var indexOf = function (xs, x) { if (xs.indexOf) return xs.indexOf(x); for (var i = 0; i < xs.length; i++) { if (xs[i] === x) return i; } return -1; }; },{"stream":12,"./response":13,"concat-stream":14}],12:[function(require,module,exports){var events = require('events'); var util = require('util'); function Stream() { events.EventEmitter.call(this); } util.inherits(Stream, events.EventEmitter); module.exports = Stream; // Backwards-compat with node 0.4.x Stream.Stream = Stream; Stream.prototype.pipe = function(dest, options) { var source = this; function ondata(chunk) { if (dest.writable) { if (false === dest.write(chunk) && source.pause) { source.pause(); } } } source.on('data', ondata); function ondrain() { if (source.readable && source.resume) { source.resume(); } } dest.on('drain', ondrain); // If the 'end' option is not supplied, dest.end() will be called when // source gets the 'end' or 'close' events. Only dest.end() once, and // only when all sources have ended. if (!dest._isStdio && (!options || options.end !== false)) { dest._pipeCount = dest._pipeCount || 0; dest._pipeCount++; source.on('end', onend); source.on('close', onclose); } var didOnEnd = false; function onend() { if (didOnEnd) return; didOnEnd = true; dest._pipeCount--; // remove the listeners cleanup(); if (dest._pipeCount > 0) { // waiting for other incoming streams to end. return; } dest.end(); } function onclose() { if (didOnEnd) return; didOnEnd = true; dest._pipeCount--; // remove the listeners cleanup(); if (dest._pipeCount > 0) { // waiting for other incoming streams to end. return; } dest.destroy(); } // don't leave dangling pipes when there are errors. function onerror(er) { cleanup(); if (this.listeners('error').length === 0) { throw er; // Unhandled stream error in pipe. } } source.on('error', onerror); dest.on('error', onerror); // remove all the event listeners that were added. function cleanup() { source.removeListener('data', ondata); dest.removeListener('drain', ondrain); source.removeListener('end', onend); source.removeListener('close', onclose); source.removeListener('error', onerror); dest.removeListener('error', onerror); source.removeListener('end', cleanup); source.removeListener('close', cleanup); dest.removeListener('end', cleanup); dest.removeListener('close', cleanup); } source.on('end', cleanup); source.on('close', cleanup); dest.on('end', cleanup); dest.on('close', cleanup); dest.emit('pipe', source); // Allow for unix-like usage: A.pipe(B).pipe(C) return dest; }; },{"events":9,"util":5}],13:[function(require,module,exports){var Stream = require('stream'); var Response = module.exports = function (res) { this.offset = 0; this.readable = true; }; Response.prototype = new Stream; var capable = { streaming : true, status2 : true }; function parseHeaders (res) { var lines = res.getAllResponseHeaders().split(/\r?\n/); var headers = {}; for (var i = 0; i < lines.length; i++) { var line = lines[i]; if (line === '') continue; var m = line.match(/^([^:]+):\s*(.*)/); if (m) { var key = m[1].toLowerCase(), value = m[2]; if (headers[key] !== undefined) { if (isArray(headers[key])) { headers[key].push(value); } else { headers[key] = [ headers[key], value ]; } } else { headers[key] = value; } } else { headers[line] = true; } } return headers; } Response.prototype.getResponse = function (xhr) { var respType = String(xhr.responseType).toLowerCase(); if (respType === 'blob') return xhr.responseBlob; if (respType === 'arraybuffer') return xhr.response; return xhr.responseText; } Response.prototype.getHeader = function (key) { return this.headers[key.toLowerCase()]; }; Response.prototype.handle = function (res) { if (res.readyState === 2 && capable.status2) { try { this.statusCode = res.status; this.headers = parseHeaders(res); } catch (err) { capable.status2 = false; } if (capable.status2) { this.emit('ready'); } } else if (capable.streaming && res.readyState === 3) { try { if (!this.statusCode) { this.statusCode = res.status; this.headers = parseHeaders(res); this.emit('ready'); } } catch (err) {} try { this._emitData(res); } catch (err) { capable.streaming = false; } } else if (res.readyState === 4) { if (!this.statusCode) { this.statusCode = res.status; this.emit('ready'); } this._emitData(res); if (res.error) { this.emit('error', this.getResponse(res)); } else this.emit('end'); this.emit('close'); } }; Response.prototype._emitData = function (res) { var respBody = this.getResponse(res); if (respBody.toString().match(/ArrayBuffer/)) { this.emit('data', new Uint8Array(respBody, this.offset)); this.offset = respBody.byteLength; return; } if (respBody.length > this.offset) { this.emit('data', respBody.slice(this.offset)); this.offset = respBody.length; } }; var isArray = Array.isArray || function (xs) { return Object.prototype.toString.call(xs) === '[object Array]'; }; },{"stream":12}],14:[function(require,module,exports){var stream = require('stream') var util = require('util') function ConcatStream(cb) { stream.Stream.call(this) this.writable = true if (cb) this.cb = cb this.body = [] if (this.cb) this.on('error', cb) } util.inherits(ConcatStream, stream.Stream) ConcatStream.prototype.write = function(chunk) { this.body.push(chunk) } ConcatStream.prototype.arrayConcat = function(arrs) { if (arrs.length === 0) return [] if (arrs.length === 1) return arrs[0] return arrs.reduce(function (a, b) { return a.concat(b) }) } ConcatStream.prototype.isArray = function(arr) { var isArray = Array.isArray(arr) var isTypedArray = arr.toString().match(/Array/) return isArray || isTypedArray } ConcatStream.prototype.getBody = function () { if (this.body.length === 0) return if (typeof(this.body[0]) === "string") return this.body.join('') if (this.isArray(this.body[0])) return this.arrayConcat(this.body) if (typeof(Buffer) !== "undefined" && Buffer.isBuffer(this.body[0])) { return Buffer.concat(this.body) } return this.body } ConcatStream.prototype.end = function() { if (this.cb) this.cb(false, this.getBody()) } module.exports = function(cb) { return new ConcatStream(cb) } module.exports.ConcatStream = ConcatStream },{"stream":12,"util":5}],7:[function(require,module,exports){// UTILITY var util = require('util'); var Buffer = require("buffer").Buffer; var pSlice = Array.prototype.slice; function objectKeys(object) { if (Object.keys) return Object.keys(object); var result = []; for (var name in object) { if (Object.prototype.hasOwnProperty.call(object, name)) { result.push(name); } } return result; } // 1. The assert module provides functions that throw // AssertionError's when particular conditions are not met. The // assert module must conform to the following interface. var assert = module.exports = ok; // 2. The AssertionError is defined in assert. // new assert.AssertionError({ message: message, // actual: actual, // expected: expected }) assert.AssertionError = function AssertionError(options) { this.name = 'AssertionError'; this.message = options.message; this.actual = options.actual; this.expected = options.expected; this.operator = options.operator; var stackStartFunction = options.stackStartFunction || fail; if (Error.captureStackTrace) { Error.captureStackTrace(this, stackStartFunction); } }; util.inherits(assert.AssertionError, Error); function replacer(key, value) { if (value === undefined) { return '' + value; } if (typeof value === 'number' && (isNaN(value) || !isFinite(value))) { return value.toString(); } if (typeof value === 'function' || value instanceof RegExp) { return value.toString(); } return value; } function truncate(s, n) { if (typeof s == 'string') { return s.length < n ? s : s.slice(0, n); } else { return s; } } assert.AssertionError.prototype.toString = function() { if (this.message) { return [this.name + ':', this.message].join(' '); } else { return [ this.name + ':', truncate(JSON.stringify(this.actual, replacer), 128), this.operator, truncate(JSON.stringify(this.expected, replacer), 128) ].join(' '); } }; // assert.AssertionError instanceof Error assert.AssertionError.__proto__ = Error.prototype; // At present only the three keys mentioned above are used and // understood by the spec. Implementations or sub modules can pass // other keys to the AssertionError's constructor - they will be // ignored. // 3. All of the following functions must throw an AssertionError // when a correspo