autobahn-browser
Version:
[BROWSER BUILD] An implementation of The Web Application Messaging Protocol (WAMP).
1,572 lines (1,254 loc) • 994 kB
JavaScript
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.autobahn = f()}})(function(){var define,module,exports;return (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){
///////////////////////////////////////////////////////////////////////////////
//
// AutobahnJS - http://autobahn.ws, http://wamp.ws
//
// A JavaScript library for WAMP ("The Web Application Messaging Protocol").
//
// Copyright (c) Crossbar.io Technologies GmbH and contributors
//
// Licensed under the MIT License.
// http://www.opensource.org/licenses/mit-license.php
//
///////////////////////////////////////////////////////////////////////////////
// require('assert') would be nice .. but it does not
// work with Google Closure after Browserify
var crypto = require('crypto-js');
// PBKDF2-base key derivation function for salted WAMP-CRA
//
function derive_key (secret, salt, iterations, keylen) {
var iterations = iterations || 1000;
var keylen = keylen || 32;
var config = {
keySize: keylen / 4,
iterations: iterations,
hasher: crypto.algo.SHA256
}
var key = crypto.PBKDF2(secret, salt, config);
return key.toString(crypto.enc.Base64);
}
function sign (key, challenge) {
return crypto.HmacSHA256(challenge, key).toString(crypto.enc.Base64);
}
exports.sign = sign;
exports.derive_key = derive_key;
},{"crypto-js":68}],2:[function(require,module,exports){
///////////////////////////////////////////////////////////////////////////////
//
// AutobahnJS - http://autobahn.ws, http://wamp.ws
//
// A JavaScript library for WAMP ("The Web Application Messaging Protocol").
//
// Copyright (c) Crossbar.io Technologies GmbH and contributors
//
// Licensed under the MIT License.
// http://www.opensource.org/licenses/mit-license.php
//
///////////////////////////////////////////////////////////////////////////////
var nacl = require('tweetnacl');
var util = require('../util.js');
var log = require('../log.js');
var connection = require('../connection.js');
function load_private_key (name, force_regenerate) {
var seed = util.atob(localStorage.getItem(name));
if (!seed || force_regenerate) {
seed = nacl.randomBytes(nacl.sign.seedLength);
localStorage.setItem(name, util.btoa(seed));
log.debug('new key seed "' + name + '" saved to local storage!');
} else {
log.debug('key seed "' + name + '" loaded from local storage!');
}
return nacl.sign.keyPair.fromSeed(seed);
}
exports.load_private_key = load_private_key;
function delete_private_key (name) {
// FIXME: poor man's secure erase
for (var i = 0; i < 5; ++i) {
seed = nacl.randomBytes(nacl.sign.seedLength);
localStorage.setItem(name, util.btoa(seed));
localStorage.setItem(name, '');
localStorage.setItem(name, null);
}
}
exports.delete_private_key = delete_private_key;
function sign_challenge (pkey, extra) {
var challenge = util.htob(extra.challenge);
var signature = nacl.sign.detached(challenge, pkey.secretKey);
var res = util.btoh(signature) + util.btoh(challenge);
return res;
}
exports.sign_challenge = sign_challenge;
function public_key (pkey) {
return util.btoh(pkey.publicKey);
}
exports.public_key = public_key;
function create_connection (config) {
var url = config.url;
var realm = config.realm;
var authid = config.authid;
var pkey = config.pkey;
var activation_code = config.activation_code;
var request_new_activation_code = config.request_new_activation_code;
var serializers = config.serializers;
if (config.debug) {
console.log(url);
console.log(realm);
console.log(authid);
console.log(pkey);
console.log(activation_code);
console.log(request_new_activation_code);
console.log(serializers);
}
function onchallenge (session, method, extra) {
// we only know how to process WAMP-cryptosign here!
if (method == "cryptosign") {
// and to do so, we let above helper sign the
// WAMP-cryptosign challenge as required
// and return a signature
return sign_challenge(pkey, extra);
} else {
throw "don't know how to authenticate using '" + method + "'";
}
}
authextra = {
// forward the client pubkey: this allows us to omit authid as
// the router can identify us with the pubkey already
pubkey: public_key(pkey),
// not yet implemented. a public key the router should provide
// a trustchain for it's public key. the trustroot can eg be
// hard-coded in the client, or come from a command line option.
trustroot: null,
// not yet implemented. for authenticating the router, this
// challenge will need to be signed by the router and send back
// in AUTHENTICATE for client to verify. A string with a hex
// encoded 32 bytes random value.
challenge: null,
// FIXME: at least on NodeJS, it should be possible to implement
// this additional security measure!
//channel_binding: 'tls-unique'
channel_binding: null,
// you should only provide an activation_code the very first time
// the key pair used is paired. a token can only be used exactly once
// and reusing it, even from the original client, will result in an error!
activation_code: activation_code,
// if true, request sending a new email with a new activation code
request_new_activation_code: request_new_activation_code
}
// now create a AutobahnJS Connection object
// with WAMP-cryptosign being the only configured
// authentication method:
var _connection = new connection.Connection({
// this MUST be given
url: url,
// this MAY be given - if not, then connect to global user realm
// if given, the user must have access permissions for the respective
// management realm (to which both users and fabric nodes are connected)
realm: realm,
// this MAY be given (but MUST be given on register/pairing)
authid: authid,
// this MUST be given
authmethods: ["cryptosign"],
// see above
onchallenge: onchallenge,
// see above
authextra: authextra,
// WAMP serializers to use
serializers: config.serializers
});
return _connection;
}
exports.create_connection = create_connection;
},{"../connection.js":6,"../log.js":7,"../util.js":20,"tweetnacl":151}],3:[function(require,module,exports){
///////////////////////////////////////////////////////////////////////////////
//
// AutobahnJS - http://autobahn.ws, http://wamp.ws
//
// A JavaScript library for WAMP ("The Web Application Messaging Protocol").
//
// Copyright (c) Crossbar.io Technologies GmbH and contributors
//
// Licensed under the MIT License.
// http://www.opensource.org/licenses/mit-license.php
//
///////////////////////////////////////////////////////////////////////////////
function auth(session, user, extra) {
// Persona Issues:
//
// Chrome: https://github.com/mozilla/persona/issues/4083
// IE11: https://groups.google.com/forum/#!topic/mozilla.dev.identity/keEkVpvfLA8
var d = session.defer();
navigator.id.watch({
loggedInUser: user,
onlogin: function (assertion) {
// A user has logged in! Here you need to:
// 1. Send the assertion to your backend for verification and to create a session.
// 2. Update your UI.
d.resolve(assertion);
},
onlogout: function() {
// A user has logged out! Here you need to:
// Tear down the user's session by redirecting the user or making a call to your backend.
// Also, make sure loggedInUser will get set to null on the next page load.
// (That's a literal JavaScript null. Not false, 0, or undefined. null.)
session.leave("wamp.close.logout");
}
});
if (d.promise.then) {
// whenjs has the actual user promise in an attribute
return d.promise;
} else {
return d;
}
}
exports.auth = auth;
},{}],4:[function(require,module,exports){
(function (global){(function (){
///////////////////////////////////////////////////////////////////////////////
//
// AutobahnJS - http://autobahn.ws, http://wamp.ws
//
// A JavaScript library for WAMP ("The Web Application Messaging Protocol").
//
// Copyright (c) Crossbar.io Technologies GmbH and contributors
//
// Licensed under the MIT License.
// http://www.opensource.org/licenses/mit-license.php
//
///////////////////////////////////////////////////////////////////////////////
// Polyfills for <= IE9
require('./polyfill.js');
var pjson = require('../package.json');
let when;
let HAS_WHEN;
try {
when = require('when');
HAS_WHEN = true;
} catch (e) {
HAS_WHEN = false;
}
var msgpack = require('msgpack5');
var cbor = require('cbor');
var nacl = require('tweetnacl');
if ('AUTOBAHN_DEBUG' in global && AUTOBAHN_DEBUG) {
// https://github.com/cujojs/when/blob/master/docs/api.md#whenmonitor
require('when/monitor/console');
if ('console' in global) {
console.log("AutobahnJS debug enabled");
}
}
var util = require('./util.js');
var log = require('./log.js');
var session = require('./session.js');
var connection = require('./connection.js');
var configure = require('./configure.js');
var serializer = require('./serializer.js');
var persona = require('./auth/persona.js');
var cra = require('./auth/cra.js');
var cryptosign = require('./auth/cryptosign.js');
exports.version = pjson.version;
exports.transports = configure.transports;
exports.Connection = connection.Connection;
exports.Session = session.Session;
exports.Invocation = session.Invocation;
exports.Event = session.Event;
exports.Result = session.Result;
exports.Error = session.Error;
exports.Subscription = session.Subscription;
exports.Registration = session.Registration;
exports.Publication = session.Publication;
exports.serializer = serializer;
exports.auth_persona = persona.auth;
exports.auth_cra = cra;
exports.auth_cryptosign = cryptosign;
if (HAS_WHEN) {
exports.when = when;
}
exports.msgpack = msgpack;
exports.cbor = cbor;
exports.nacl = nacl;
exports.util = util;
exports.log = log;
}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"../package.json":180,"./auth/cra.js":1,"./auth/cryptosign.js":2,"./auth/persona.js":3,"./configure.js":5,"./connection.js":6,"./log.js":7,"./polyfill.js":8,"./serializer.js":16,"./session.js":17,"./util.js":20,"cbor":48,"msgpack5":110,"tweetnacl":151,"when":178,"when/monitor/console":176}],5:[function(require,module,exports){
///////////////////////////////////////////////////////////////////////////////
//
// AutobahnJS - http://autobahn.ws, http://wamp.ws
//
// A JavaScript library for WAMP ("The Web Application Messaging Protocol").
//
// Copyright (c) Crossbar.io Technologies GmbH and contributors
//
// Licensed under the MIT License.
// http://www.opensource.org/licenses/mit-license.php
//
///////////////////////////////////////////////////////////////////////////////
function Transports() {
this._repository = {};
}
Transports.prototype.register = function (name, factory) {
this._repository[name] = factory;
};
Transports.prototype.isRegistered = function (name) {
return this._repository[name] ? true : false;
};
Transports.prototype.get = function (name) {
if (this._repository[name] !== undefined) {
return this._repository[name];
} else {
throw "no such transport: " + name;
}
}
Transports.prototype.list = function() {
var items = [];
for (var name in this._repository) {
items.push(name);
}
return items;
};
var _transports = new Transports();
// register default transports
var websocket = require('./transport/websocket.js');
_transports.register("websocket", websocket.Factory);
var longpoll = require('./transport/longpoll.js');
_transports.register("longpoll", longpoll.Factory);
var rawsocket = require('./transport/rawsocket.js');
_transports.register("rawsocket", rawsocket.Factory);
exports.transports = _transports;
},{"./transport/longpoll.js":18,"./transport/rawsocket.js":44,"./transport/websocket.js":19}],6:[function(require,module,exports){
///////////////////////////////////////////////////////////////////////////////
//
// AutobahnJS - http://autobahn.ws, http://wamp.ws
//
// A JavaScript library for WAMP ("The Web Application Messaging Protocol").
//
// Copyright (c) Crossbar.io Technologies GmbH and contributors
//
// Licensed under the MIT License.
// http://www.opensource.org/licenses/mit-license.php
//
///////////////////////////////////////////////////////////////////////////////
var session = require('./session.js');
var util = require('./util.js');
var log = require('./log.js');
var autobahn = require('./autobahn.js');
var Connection = function (options) {
var self = this;
self._options = options;
// Deferred factory
//
self._defer = util.deferred_factory(options);
// WAMP transport
//
// backward compatiblity
if (!self._options.transports) {
self._options.transports = [
{
type: 'websocket',
url: self._options.url,
tlsConfiguration: self._options.tlsConfiguration
}
];
}
self._transport_factories = [];
self._init_transport_factories();
// WAMP session
//
self._session = null;
self._session_close_reason = null;
self._session_close_message = null;
// automatic reconnection configuration
//
// enable automatic reconnect if host is unreachable
if (self._options.retry_if_unreachable !== undefined) {
self._retry_if_unreachable = self._options.retry_if_unreachable;
} else {
self._retry_if_unreachable = true;
}
// maximum number of reconnection attempts
self._max_retries = typeof self._options.max_retries !== 'undefined' ? self._options.max_retries : 15;
// initial retry delay in seconds
self._initial_retry_delay = typeof self._options.initial_retry_delay !== 'undefined' ? self._options.initial_retry_delay : 1.5;
// maximum seconds between reconnection attempts
self._max_retry_delay = self._options.max_retry_delay || 300;
// the growth factor applied to the retry delay on each retry cycle
self._retry_delay_growth = self._options.retry_delay_growth || 1.5;
// the SD of a Gaussian to jitter the delay on each retry cycle
// as a fraction of the mean
self._retry_delay_jitter = self._options.retry_delay_jitter || 0.1;
// reconnection tracking
//
// total number of successful connections
self._connect_successes = 0;
// controls if we should try to reconnect
self._retry = false;
// current number of reconnect cycles we went through
self._retry_count = 0;
// the current retry delay
self._retry_delay = self._initial_retry_delay;
// flag indicating if we are currently in a reconnect cycle
self._is_retrying = false;
// when retrying, this is the timer object returned from window.setTimeout()
self._retry_timer = null;
};
Connection.prototype._create_transport = function () {
var self = this;
for (var i = 0; i < this._transport_factories.length; ++i) {
var transport_factory = this._transport_factories[i];
log.debug("trying to create WAMP transport of type: " + transport_factory.type);
try {
var transport = transport_factory.create();
if (transport) {
log.debug("using WAMP transport type: " + transport_factory.type);
return transport;
}
} catch (e) {
var error_message = "could not create WAMP transport '" + transport_factory.type + "': ";
util.handle_error(self._options.on_internal_error, e, error_message);
}
}
log.warn('could not create any WAMP transport');
return null;
};
Connection.prototype._init_transport_factories = function () {
// WAMP transport
//
var self = this;
var transports, transport_options, transport_factory, transport_factory_klass;
util.assert(this._options.transports, "No transport.factory specified");
transports = this._options.transports;
//if(typeof transports === "object") {
// this._options.transports = [transports];
//}
for(var i = 0; i < this._options.transports.length; ++i) {
// cascading transports until we find one which works
transport_options = this._options.transports[i];
if (!transport_options.url) {
// defaulting to options.url if none is provided
transport_options.url = this._options.url;
}
if (!transport_options.serializers) {
transport_options.serializers = this._options.serializers;
}
if (!transport_options.protocols) {
transport_options.protocols = this._options.protocols;
}
util.assert(transport_options.type, "No transport.type specified");
util.assert(typeof transport_options.type === "string", "transport.type must be a string");
try {
transport_factory_klass = autobahn.transports.get(transport_options.type);
if (transport_factory_klass) {
transport_factory = new transport_factory_klass(transport_options);
this._transport_factories.push(transport_factory);
}
} catch (exc) {
util.handle_error(self._options.on_internal_error, exc);
}
}
};
Connection.prototype._autoreconnect_reset_timer = function () {
var self = this;
if (self._retry_timer) {
clearTimeout(self._retry_timer);
}
self._retry_timer = null;
}
Connection.prototype._autoreconnect_reset = function () {
var self = this;
self._autoreconnect_reset_timer();
self._retry_count = 0;
self._retry_delay = self._initial_retry_delay;
self._is_retrying = false;
}
Connection.prototype._autoreconnect_advance = function () {
var self = this;
// jitter retry delay
if (self._retry_delay_jitter) {
self._retry_delay = util.rand_normal(self._retry_delay, self._retry_delay * self._retry_delay_jitter);
}
// cap the retry delay
if (self._retry_delay > self._max_retry_delay) {
self._retry_delay = self._max_retry_delay;
}
// count number of retries
self._retry_count += 1;
var res;
if (self._retry && (self._max_retries === -1 || self._retry_count <= self._max_retries)) {
res = {
count: self._retry_count,
delay: self._retry_delay,
will_retry: true
};
} else {
res = {
count: null,
delay: null,
will_retry: false
}
}
// retry delay growth for next retry cycle
if (self._retry_delay_growth) {
self._retry_delay = self._retry_delay * self._retry_delay_growth;
}
return res;
}
Connection.prototype.open = function () {
var self = this;
if (self._transport) {
throw "connection already open (or opening)";
}
self._autoreconnect_reset();
self._retry = true;
function retry () {
// create a WAMP transport
try {
self._transport = self._create_transport();
} catch (e) {
util.handle_error(self._options.on_internal_error, e);
}
if (!self._transport) {
// failed to create a WAMP transport
self._retry = false;
if (self.onclose) {
var details = {
reason: null,
message: null,
retry_delay: null,
retry_count: null,
will_retry: false
};
self.onclose("unsupported", details);
}
return;
}
// create a new WAMP session using the WebSocket connection as transport
self._session = new session.Session(self._transport, self._defer, self._options.onchallenge, self._options.on_user_error, self._options.on_internal_error);
self._session_close_reason = null;
self._session_close_message = null;
self._transport.onopen = function () {
// reset auto-reconnect timer and tracking
self._autoreconnect_reset();
// log successful connections
self._connect_successes += 1;
// start WAMP session
self._session.join(self._options.realm, self._options.authmethods, self._options.authid, self._options.authextra);
};
self._session.onjoin = function (details) {
if (self.onopen) {
try {
// forward transport info ..
details.transport = self._transport.info;
self.onopen(self._session, details);
} catch (e) {
util.handle_error(self._options.on_user_error, e, "Exception raised from app code while firing Connection.onopen()");
}
}
};
//
// ... WAMP session is now attached to realm.
//
self._session.onleave = function (reason, details) {
self._session_close_reason = reason;
self._session_close_message = details.message || "";
self._retry = false;
self._transport.close();
};
self._transport.onclose = function (evt) {
// remove any pending reconnect timer
self._autoreconnect_reset_timer();
self._transport = null;
var reason = null;
if (self._connect_successes === 0) {
reason = "unreachable";
if (!self._retry_if_unreachable) {
self._retry = false;
}
} else if (!evt.wasClean) {
reason = "lost";
} else {
reason = "closed";
}
var next_retry = self._autoreconnect_advance();
var details = {
reason: self._session_close_reason,
message: self._session_close_message,
retry_delay: next_retry.delay,
retry_count: next_retry.count,
will_retry: next_retry.will_retry
};
log.warn("connection closed", reason, details);
// fire app code handler
//
if (self.onclose) {
try {
// Connection.onclose() allows to cancel any subsequent retry attempt
var stop_retrying = self.onclose(reason, details);
} catch (e) {
util.handle_error(self._options.on_user_error, e, "Exception raised from app code while firing Connection.onclose()");
}
}
// reset session info
//
if (self._session) {
self._session._id = null;
self._session = null;
self._session_close_reason = null;
self._session_close_message = null;
}
// automatic reconnection
//
if (self._retry && !stop_retrying) {
if (next_retry.will_retry) {
self._is_retrying = true;
log.warn("auto-reconnecting in " + next_retry.delay + "s ..");
self._retry_timer = setTimeout(retry, next_retry.delay * 1000);
} else {
log.warn("giving up trying to auto-reconnect!");
}
} else {
log.warn("auto-reconnect disabled!", self._retry, stop_retrying);
}
}
}
retry();
};
Connection.prototype.close = function (reason, message) {
var self = this;
if (!self._transport && !self._is_retrying) {
throw "connection already closed";
}
// the app wants to close .. don't retry
self._retry = false;
if (self._session && self._session.isOpen) {
// if there is an open session, close that first.
self._session.leave(reason, message);
} else if (self._transport) {
// no session active: just close the transport
self._transport.close();
}
};
Object.defineProperty(Connection.prototype, "defer", {
get: function () {
return this._defer;
}
});
Object.defineProperty(Connection.prototype, "session", {
get: function () {
return this._session;
}
});
Object.defineProperty(Connection.prototype, "isOpen", {
get: function () {
if (this._session && this._session.isOpen) {
return true;
} else {
return false;
}
}
});
Object.defineProperty(Connection.prototype, "isConnected", {
get: function () {
if (this._transport) {
return true;
} else {
return false;
}
}
});
Object.defineProperty(Connection.prototype, "transport", {
get: function () {
if (this._transport) {
return this._transport;
} else {
return {info: {type: 'none', url: null, protocol: null}};
}
}
});
Object.defineProperty(Connection.prototype, "isRetrying", {
get: function () {
return this._is_retrying;
}
});
exports.Connection = Connection;
},{"./autobahn.js":4,"./log.js":7,"./session.js":17,"./util.js":20}],7:[function(require,module,exports){
(function (global){(function (){
///////////////////////////////////////////////////////////////////////////////
//
// AutobahnJS - http://autobahn.ws, http://wamp.ws
//
// A JavaScript library for WAMP ("The Web Application Messaging Protocol").
//
// Copyright (c) Crossbar.io Technologies GmbH and contributors
//
// Licensed under the MIT License.
// http://www.opensource.org/licenses/mit-license.php
//
///////////////////////////////////////////////////////////////////////////////
let debug = function () {};
if ('AUTOBAHN_DEBUG' in global && AUTOBAHN_DEBUG && 'console' in global) {
debug = function () {
console.log.apply(console, arguments);
}
}
let warn = console.warn.bind(console);
exports.debug = debug;
exports.warn = warn;
}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{}],8:[function(require,module,exports){
require('./polyfill/object.js');
require('./polyfill/array.js');
require('./polyfill/string.js');
require('./polyfill/function.js');
require('./polyfill/console.js');
require('./polyfill/typedarray.js');
require('./polyfill/json.js');
},{"./polyfill/array.js":9,"./polyfill/console.js":10,"./polyfill/function.js":11,"./polyfill/json.js":12,"./polyfill/object.js":13,"./polyfill/string.js":14,"./polyfill/typedarray.js":15}],9:[function(require,module,exports){
if ( 'function' !== typeof Array.prototype.reduce ) {
Array.prototype.reduce = function( callback /*, initialValue*/ ) {
'use strict';
var len, t, value, k;
if ( null === this || 'undefined' === typeof this ) {
throw new TypeError(
'Array.prototype.reduce called on null or undefined' );
}
if ( 'function' !== typeof callback ) {
throw new TypeError( callback + ' is not a function' );
}
t = Object( this );
len = t.length >>> 0;
k = 0;
if ( arguments.length >= 2 ) {
value = arguments[1];
} else {
while ( k < len && ! k in t ) k++;
if ( k >= len )
throw new TypeError('Reduce of empty array with no initial value');
value = t[ k++ ];
}
for ( ; k < len ; k++ ) {
if ( k in t ) {
value = callback( value, t[k], k, t );
}
}
return value;
};
}
// Add ECMA262-5 Array methods if not supported natively
//
if (!('indexOf' in Array.prototype)) {
Array.prototype.indexOf= function(find, i /*opt*/) {
if (i===undefined) i= 0;
if (i<0) i+= this.length;
if (i<0) i= 0;
for (var n= this.length; i<n; i++)
if (i in this && this[i]===find)
return i;
return -1;
};
}
if (!('lastIndexOf' in Array.prototype)) {
Array.prototype.lastIndexOf= function(find, i /*opt*/) {
if (i===undefined) i= this.length-1;
if (i<0) i+= this.length;
if (i>this.length-1) i= this.length-1;
for (i++; i-->0;) /* i++ because from-argument is sadly inclusive */
if (i in this && this[i]===find)
return i;
return -1;
};
}
if (!('forEach' in Array.prototype)) {
Array.prototype.forEach= function(action, that /*opt*/) {
for (var i= 0, n= this.length; i<n; i++)
if (i in this)
action.call(that, this[i], i, this);
};
}
if (!('map' in Array.prototype)) {
Array.prototype.map= function(mapper, that /*opt*/) {
var other= new Array(this.length);
for (var i= 0, n= this.length; i<n; i++)
if (i in this)
other[i]= mapper.call(that, this[i], i, this);
return other;
};
}
if (!('filter' in Array.prototype)) {
Array.prototype.filter= function(filter, that /*opt*/) {
var other= [], v;
for (var i=0, n= this.length; i<n; i++)
if (i in this && filter.call(that, v= this[i], i, this))
other.push(v);
return other;
};
}
if (!('every' in Array.prototype)) {
Array.prototype.every= function(tester, that /*opt*/) {
for (var i= 0, n= this.length; i<n; i++)
if (i in this && !tester.call(that, this[i], i, this))
return false;
return true;
};
}
if (!('some' in Array.prototype)) {
Array.prototype.some= function(tester, that /*opt*/) {
for (var i= 0, n= this.length; i<n; i++)
if (i in this && tester.call(that, this[i], i, this))
return true;
return false;
};
}
if ( 'function' !== typeof Array.prototype.reduceRight ) {
Array.prototype.reduceRight = function( callback /*, initialValue*/ ) {
'use strict';
if ( null === this || 'undefined' === typeof this ) {
throw new TypeError(
'Array.prototype.reduce called on null or undefined' );
}
if ( 'function' !== typeof callback ) {
throw new TypeError( callback + ' is not a function' );
}
var t = Object( this ), len = t.length >>> 0, k = len - 1, value;
if ( arguments.length >= 2 ) {
value = arguments[1];
} else {
while ( k >= 0 && ! k in t ) k--;
if ( k < 0 )
throw new TypeError('Reduce of empty array with no initial value');
value = t[ k-- ];
}
for ( ; k >= 0 ; k-- ) {
if ( k in t ) {
value = callback( value, t[k], k, t );
}
}
return value;
};
}
},{}],10:[function(require,module,exports){
(function(console) {
/*********************************************************************************************
* Make sure console exists because IE blows up if it's not open and you attempt to access it
* Create some dummy functions if we need to, so we don't have to if/else everything
*********************************************************************************************/
console||(console = window.console = {
// all this "a, b, c, d, e" garbage is to make the IDEs happy, since they can't do variable argument lists
/**
* @param a
* @param [b]
* @param [c]
* @param [d]
* @param [e]
*/
log: function(a, b, c, d, e) {},
/**
* @param a
* @param [b]
* @param [c]
* @param [d]
* @param [e]
*/
info: function(a, b, c, d, e) {},
/**
* @param a
* @param [b]
* @param [c]
* @param [d]
* @param [e]
*/
warn: function(a, b, c, d, e) {},
/**
* @param a
* @param [b]
* @param [c]
* @param [d]
* @param [e]
*/
error: function(a, b, c, d, e) {},
assert: function(test, message) {}
});
// IE 9 won't allow us to call console.log.apply (WTF IE!) It also reports typeof(console.log) as 'object' (UNH!)
// but together, those two errors can be useful in allowing us to fix stuff so it works right
if( typeof(console.log) === 'object' ) {
// Array.forEach doesn't work in IE 8 so don't try that :(
console.log = Function.prototype.call.bind(console.log, console);
console.info = Function.prototype.call.bind(console.info, console);
console.warn = Function.prototype.call.bind(console.warn, console);
console.error = Function.prototype.call.bind(console.error, console);
console.debug = Function.prototype.call.bind(console.info, console);
}
/**
* Support group and groupEnd functions
*/
('group' in console) ||
(console.group = function(msg) {
console.info("\n--- "+msg+" ---\n");
});
('groupEnd' in console) ||
(console.groupEnd = function() {
console.log("\n");
});
('assert' in console) ||
(console.assert = function(test, message) {
if (!test) {
try {
// attempt to preserve the stack
throw new Error("assertion failed: " + message);
} catch(error) {
setTimeout(function(){
throw error;
}, 0);
}
}
});
/**
* Support time and timeEnd functions
*/
('time' in console) ||
(function() {
var trackedTimes = {};
console.time = function(msg) {
trackedTimes[msg] = new Date().getTime();
};
console.timeEnd = function(msg) {
var end = new Date().getTime(), time = (msg in trackedTimes)? end - trackedTimes[msg] : 0;
console.info(msg+': '+time+'ms')
};
}());
})(typeof console !== 'undefined' ? console : undefined);
},{}],11:[function(require,module,exports){
if (!Function.prototype.bind) {
//credits: taken from bind_even_never in this discussion: https://prototype.lighthouseapp.com/projects/8886/tickets/215-optimize-bind-bindaseventlistener#ticket-215-9
Function.prototype.bind = function(context) {
var fn = this, args = Array.prototype.slice.call(arguments, 1);
return function(){
return fn.apply(context, Array.prototype.concat.apply(args, arguments));
};
};
}
},{}],12:[function(require,module,exports){
/*
json2.js
2014-02-04
Public Domain.
NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
See http://www.JSON.org/js.html
This code should be minified before deployment.
See http://javascript.crockford.com/jsmin.html
USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO
NOT CONTROL.
This file creates a global JSON object containing two methods: stringify
and parse.
JSON.stringify(value, replacer, space)
value any JavaScript value, usually an object or array.
replacer an optional parameter that determines how object
values are stringified for objects. It can be a
function or an array of strings.
space an optional parameter that specifies the indentation
of nested structures. If it is omitted, the text will
be packed without extra whitespace. If it is a number,
it will specify the number of spaces to indent at each
level. If it is a string (such as '\t' or ' '),
it contains the characters used to indent at each level.
This method produces a JSON text from a JavaScript value.
When an object value is found, if the object contains a toJSON
method, its toJSON method will be called and the result will be
stringified. A toJSON method does not serialize: it returns the
value represented by the name/value pair that should be serialized,
or undefined if nothing should be serialized. The toJSON method
will be passed the key associated with the value, and this will be
bound to the value
For example, this would serialize Dates as ISO strings.
Date.prototype.toJSON = function (key) {
function f(n) {
// Format integers to have at least two digits.
return n < 10 ? '0' + n : n;
}
return this.getUTCFullYear() + '-' +
f(this.getUTCMonth() + 1) + '-' +
f(this.getUTCDate()) + 'T' +
f(this.getUTCHours()) + ':' +
f(this.getUTCMinutes()) + ':' +
f(this.getUTCSeconds()) + 'Z';
};
You can provide an optional replacer method. It will be passed the
key and value of each member, with this bound to the containing
object. The value that is returned from your method will be
serialized. If your method returns undefined, then the member will
be excluded from the serialization.
If the replacer parameter is an array of strings, then it will be
used to select the members to be serialized. It filters the results
such that only members with keys listed in the replacer array are
stringified.
Values that do not have JSON representations, such as undefined or
functions, will not be serialized. Such values in objects will be
dropped; in arrays they will be replaced with null. You can use
a replacer function to replace those with JSON values.
JSON.stringify(undefined) returns undefined.
The optional space parameter produces a stringification of the
value that is filled with line breaks and indentation to make it
easier to read.
If the space parameter is a non-empty string, then that string will
be used for indentation. If the space parameter is a number, then
the indentation will be that many spaces.
Example:
text = JSON.stringify(['e', {pluribus: 'unum'}]);
// text is '["e",{"pluribus":"unum"}]'
text = JSON.stringify(['e', {pluribus: 'unum'}], null, '\t');
// text is '[\n\t"e",\n\t{\n\t\t"pluribus": "unum"\n\t}\n]'
text = JSON.stringify([new Date()], function (key, value) {
return this[key] instanceof Date ?
'Date(' + this[key] + ')' : value;
});
// text is '["Date(---current time---)"]'
JSON.parse(text, reviver)
This method parses a JSON text to produce an object or array.
It can throw a SyntaxError exception.
The optional reviver parameter is a function that can filter and
transform the results. It receives each of the keys and values,
and its return value is used instead of the original value.
If it returns what it received, then the structure is not modified.
If it returns undefined then the member is deleted.
Example:
// Parse the text. Values that look like ISO date strings will
// be converted to Date objects.
myData = JSON.parse(text, function (key, value) {
var a;
if (typeof value === 'string') {
a =
/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value);
if (a) {
return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4],
+a[5], +a[6]));
}
}
return value;
});
myData = JSON.parse('["Date(09/09/2001)"]', function (key, value) {
var d;
if (typeof value === 'string' &&
value.slice(0, 5) === 'Date(' &&
value.slice(-1) === ')') {
d = new Date(value.slice(5, -1));
if (d) {
return d;
}
}
return value;
});
This is a reference implementation. You are free to copy, modify, or
redistribute.
*/
/*jslint evil: true, regexp: true */
/*members "", "\b", "\t", "\n", "\f", "\r", "\"", JSON, "\\", apply,
call, charCodeAt, getUTCDate, getUTCFullYear, getUTCHours,
getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join,
lastIndex, length, parse, prototype, push, replace, slice, stringify,
test, toJSON, toString, valueOf
*/
// Create a JSON object only if one does not already exist. We create the
// methods in a closure to avoid creating global variables.
if (typeof JSON !== 'object') {
JSON = {};
}
(function () {
'use strict';
function f(n) {
// Format integers to have at least two digits.
return n < 10 ? '0' + n : n;
}
if (typeof Date.prototype.toJSON !== 'function') {
Date.prototype.toJSON = function () {
return isFinite(this.valueOf())
? this.getUTCFullYear() + '-' +
f(this.getUTCMonth() + 1) + '-' +
f(this.getUTCDate()) + 'T' +
f(this.getUTCHours()) + ':' +
f(this.getUTCMinutes()) + ':' +
f(this.getUTCSeconds()) + 'Z'
: null;
};
String.prototype.toJSON =
Number.prototype.toJSON =
Boolean.prototype.toJSON = function () {
return this.valueOf();
};
}
var cx,
escapable,
gap,
indent,
meta,
rep;
function quote(string) {
// If the string contains no control characters, no quote characters, and no
// backslash characters, then we can safely slap some quotes around it.
// Otherwise we must also replace the offending characters with safe escape
// sequences.
escapable.lastIndex = 0;
return escapable.test(string) ? '"' + string.replace(escapable, function (a) {
var c = meta[a];
return typeof c === 'string'
? c
: '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
}) + '"' : '"' + string + '"';
}
function str(key, holder) {
// Produce a string from holder[key].
var i, // The loop counter.
k, // The member key.
v, // The member value.
length,
mind = gap,
partial,
value = holder[key];
// If the value has a toJSON method, call it to obtain a replacement value.
if (value && typeof value === 'object' &&
typeof value.toJSON === 'function') {
value = value.toJSON(key);
}
// If we were called with a replacer function, then call the replacer to
// obtain a replacement value.
if (typeof rep === 'function') {
value = rep.call(holder, key, value);
}
// What happens next depends on the value's type.
switch (typeof value) {
case 'string':
return quote(value);
case 'number':
// JSON numbers must be finite. Encode non-finite numbers as null.
return isFinite(value) ? String(value) : 'null';
case 'boolean':
case 'null':
// If the value is a boolean or null, convert it to a string. Note:
// typeof null does not produce 'null'. The case is included here in
// the remote chance that this gets fixed someday.
return String(value);
// If the type is 'object', we might be dealing with an object or an array or
// null.
case 'object':
// Due to a specification blunder in ECMAScript, typeof null is 'object',
// so watch out for that case.
if (!value) {
return 'null';
}
// Make an array to hold the partial results of stringifying this object value.
gap += indent;
partial = [];
// Is the value an array?
if (Object.prototype.toString.apply(value) === '[object Array]') {
// The value is an array. Stringify every element. Use null as a placeholder
// for non-JSON values.
length = value.length;
for (i = 0; i < length; i += 1) {
partial[i] = str(i, value) || 'null';
}
// Join all of the elements together, separated with commas, and wrap them in
// brackets.
v = partial.length === 0
? '[]'
: gap
? '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']'
: '[' + partial.join(',') + ']';
gap = mind;
return v;
}
// If the replacer is an array, use it to select the members to be stringified.
if (rep && typeof rep === 'object') {
length = rep.length;
for (i = 0; i < length; i += 1) {
if (typeof rep[i] === 'string') {
k = rep[i];
v = str(k, value);
if (v) {
partial.push(quote(k) + (gap ? ': ' : ':') + v);
}
}
}
} else {
// Otherwise, iterate through all of the keys in the object.
for (k in value) {
if (Object.prototype.hasOwnProperty.call(value, k)) {
v = str(k, value);
if (v) {
partial.push(quote(k) + (gap ? ': ' : ':') + v);
}
}
}
}
// Join all of the member texts together, separated with commas,
// and wrap them in braces.
v = partial.length === 0
? '{}'
: gap
? '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}'
: '{' + partial.join(',') + '}';
gap = mind;
return v;
}
}
// If the JSON object does not yet have a stringify method, give it one.
if (typeof JSON.stringify !== 'function') {
escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g;
meta = { // table of character substitutions
'\b': '\\b',
'\t': '\\t',
'\n': '\\n',
'\f': '\\f',
'\r': '\\r',
'"' : '\\"',
'\\': '\\\\'
};
JSON.stringify = function (value, replacer, space) {
// The stringify method takes a value and an optional replacer, and an optional
// space parameter, and returns a JSON text. The replacer can be a function
// that can replace values, or an array of strings that will select the keys.
// A default replacer method can be provided. Use of the space parameter can
// produce text that is more easily readable.
var i;
gap = '';
indent = '';
// If the space parameter is a number, make an indent string containing that
// many spaces.
if (typeof space === 'number') {
for (i = 0; i < space; i += 1) {
indent += ' ';
}
// If the space parameter is a string, it will be used as the indent string.
} else if (typeof space === 'string') {
indent = space;
}
// If there is a replacer, it must be a function or an array.
// Otherwise, throw an error.
rep = replacer;
if (replacer && typeof replacer !== 'function' &&
(typeof replacer !== 'object' ||
typeof replacer.length !== 'number')) {
throw new Error('JSON.stringify');
}
// Make a fake root object containing our value under the key of ''.
// Return the result of stringifying the value.
return str('', {'': value});
};
}
// If the JSON object does not yet have a parse method, give it one.
if (typeof JSON.parse !== 'function') {
cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g;
JSON.parse = function (text, reviver) {
// The parse method takes a text and an optional reviver function, and returns
// a JavaScript value if the text is a valid JSON text.
var j;
function walk(holder, key) {
// The walk method is used to recursively walk the resulting structure so
// that modifications can be made.
var k, v, value = holder[key];
if (value && typeof value === 'object') {
for (k in value) {
if (Object.prototype.hasOwnProperty.call(value, k)) {
v = walk(value, k);
if (v !== undefined) {
value[k] = v;
} else {
delete value[k];
}
}