From 53e22b792699750d7c767fdbfe60cc787ff96ea5 Mon Sep 17 00:00:00 2001 From: dustinlarimer Date: Thu, 9 Jul 2015 15:38:00 -0700 Subject: [PATCH] v3.2.6 Release --- dist/keen-query.js | 2265 ++++++++++++++++ dist/keen-query.min.js | 1 + dist/keen-tracker.js | 2410 +++++++++++++++++ dist/keen-tracker.min.js | 5 + dist/keen.js | 5346 ++++++++++++++++++++++++++++++++++++++ dist/keen.min.js | 29 + 6 files changed, 10056 insertions(+) create mode 100644 dist/keen-query.js create mode 100644 dist/keen-query.min.js create mode 100644 dist/keen-tracker.js create mode 100644 dist/keen-tracker.min.js create mode 100644 dist/keen.js create mode 100644 dist/keen.min.js diff --git a/dist/keen-query.js b/dist/keen-query.js new file mode 100644 index 0000000..1ddace3 --- /dev/null +++ b/dist/keen-query.js @@ -0,0 +1,2265 @@ +(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;ohey!'], { type: "text/html"})) + * .end(callback); + * ``` + * + * @param {String} field + * @param {Blob|File} file + * @param {String} filename + * @return {Request} for chaining + * @api public + */ +Request.prototype.attach = function(field, file, filename){ + if (!this._formData) this._formData = new FormData(); + this._formData.append(field, file, filename); + return this; +}; +/** + * Send `data`, defaulting the `.type()` to "json" when + * an object is given. + * + * Examples: + * + * + * request.get('/search') + * .end(callback) + * + * + * request.get('/search') + * .send({ search: 'query' }) + * .send({ range: '1..5' }) + * .send({ order: 'desc' }) + * .end(callback) + * + * + * request.post('/user') + * .type('json') + * .send('{"name":"tj"}) + * .end(callback) + * + * + * request.post('/user') + * .send({ name: 'tj' }) + * .end(callback) + * + * + * request.post('/user') + * .type('form') + * .send('name=tj') + * .end(callback) + * + * + * request.post('/user') + * .type('form') + * .send({ name: 'tj' }) + * .end(callback) + * + * + * request.post('/user') + * .send('name=tobi') + * .send('species=ferret') + * .end(callback) + * + * @param {String|Object} data + * @return {Request} for chaining + * @api public + */ +Request.prototype.send = function(data){ + var obj = isObject(data); + var type = this.getHeader('Content-Type'); + if (obj && isObject(this._data)) { + for (var key in data) { + this._data[key] = data[key]; + } + } else if ('string' == typeof data) { + if (!type) this.type('form'); + type = this.getHeader('Content-Type'); + if ('application/x-www-form-urlencoded' == type) { + this._data = this._data + ? this._data + '&' + data + : data; + } else { + this._data = (this._data || '') + data; + } + } else { + this._data = data; + } + if (!obj) return this; + if (!type) this.type('json'); + return this; +}; +/** + * Invoke the callback with `err` and `res` + * and handle arity check. + * + * @param {Error} err + * @param {Response} res + * @api private + */ +Request.prototype.callback = function(err, res){ + var fn = this._callback; + this.clearTimeout(); + if (2 == fn.length) return fn(err, res); + if (err) return this.emit('error', err); + fn(res); +}; +/** + * Invoke callback with x-domain error. + * + * @api private + */ +Request.prototype.crossDomainError = function(){ + var err = new Error('Origin is not allowed by Access-Control-Allow-Origin'); + err.crossDomain = true; + this.callback(err); +}; +/** + * Invoke callback with timeout error. + * + * @api private + */ +Request.prototype.timeoutError = function(){ + var timeout = this._timeout; + var err = new Error('timeout of ' + timeout + 'ms exceeded'); + err.timeout = timeout; + this.callback(err); +}; +/** + * Enable transmission of cookies with x-domain requests. + * + * Note that for this to work the origin must not be + * using "Access-Control-Allow-Origin" with a wildcard, + * and also must set "Access-Control-Allow-Credentials" + * to "true". + * + * @api public + */ +Request.prototype.withCredentials = function(){ + this._withCredentials = true; + return this; +}; +/** + * Initiate request, invoking callback `fn(res)` + * with an instanceof `Response`. + * + * @param {Function} fn + * @return {Request} for chaining + * @api public + */ +Request.prototype.end = function(fn){ + var self = this; + var xhr = this.xhr = getXHR(); + var query = this._query.join('&'); + var timeout = this._timeout; + var data = this._formData || this._data; + this._callback = fn || noop; + xhr.onreadystatechange = function(){ + if (4 != xhr.readyState) return; + if (0 == xhr.status) { + if (self.aborted) return self.timeoutError(); + return self.crossDomainError(); + } + self.emit('end'); + }; + if (xhr.upload) { + xhr.upload.onprogress = function(e){ + e.percent = e.loaded / e.total * 100; + self.emit('progress', e); + }; + } + if (timeout && !this._timer) { + this._timer = setTimeout(function(){ + self.abort(); + }, timeout); + } + if (query) { + query = request.serializeObject(query); + this.url += ~this.url.indexOf('?') + ? '&' + query + : '?' + query; + } + xhr.open(this.method, this.url, true); + if (this._withCredentials) xhr.withCredentials = true; + if ('GET' != this.method && 'HEAD' != this.method && 'string' != typeof data && !isHost(data)) { + var serialize = request.serialize[this.getHeader('Content-Type')]; + if (serialize) data = serialize(data); + } + for (var field in this.header) { + if (null == this.header[field]) continue; + xhr.setRequestHeader(field, this.header[field]); + } + this.emit('request', this); + xhr.send(data); + return this; +}; +/** + * Expose `Request`. + */ +request.Request = Request; +/** + * Issue a request: + * + * Examples: + * + * request('GET', '/users').end(callback) + * request('/users').end(callback) + * request('/users', callback) + * + * @param {String} method + * @param {String|Function} url or callback + * @return {Request} + * @api public + */ +function request(method, url) { + if ('function' == typeof url) { + return new Request('GET', method).end(url); + } + if (1 == arguments.length) { + return new Request('GET', method); + } + return new Request(method, url); +} +/** + * GET `url` with optional callback `fn(res)`. + * + * @param {String} url + * @param {Mixed|Function} data or fn + * @param {Function} fn + * @return {Request} + * @api public + */ +request.get = function(url, data, fn){ + var req = request('GET', url); + if ('function' == typeof data) fn = data, data = null; + if (data) req.query(data); + if (fn) req.end(fn); + return req; +}; +/** + * HEAD `url` with optional callback `fn(res)`. + * + * @param {String} url + * @param {Mixed|Function} data or fn + * @param {Function} fn + * @return {Request} + * @api public + */ +request.head = function(url, data, fn){ + var req = request('HEAD', url); + if ('function' == typeof data) fn = data, data = null; + if (data) req.send(data); + if (fn) req.end(fn); + return req; +}; +/** + * DELETE `url` with optional callback `fn(res)`. + * + * @param {String} url + * @param {Function} fn + * @return {Request} + * @api public + */ +request.del = function(url, fn){ + var req = request('DELETE', url); + if (fn) req.end(fn); + return req; +}; +/** + * PATCH `url` with optional `data` and callback `fn(res)`. + * + * @param {String} url + * @param {Mixed} data + * @param {Function} fn + * @return {Request} + * @api public + */ +request.patch = function(url, data, fn){ + var req = request('PATCH', url); + if ('function' == typeof data) fn = data, data = null; + if (data) req.send(data); + if (fn) req.end(fn); + return req; +}; +/** + * POST `url` with optional `data` and callback `fn(res)`. + * + * @param {String} url + * @param {Mixed} data + * @param {Function} fn + * @return {Request} + * @api public + */ +request.post = function(url, data, fn){ + var req = request('POST', url); + if ('function' == typeof data) fn = data, data = null; + if (data) req.send(data); + if (fn) req.end(fn); + return req; +}; +/** + * PUT `url` with optional `data` and callback `fn(res)`. + * + * @param {String} url + * @param {Mixed|Function} data or fn + * @param {Function} fn + * @return {Request} + * @api public + */ +request.put = function(url, data, fn){ + var req = request('PUT', url); + if ('function' == typeof data) fn = data, data = null; + if (data) req.send(data); + if (fn) req.end(fn); + return req; +}; +/** + * Expose `request`. + */ +module.exports = request; +},{"emitter":6,"reduce":7}],6:[function(require,module,exports){ +/** + * Expose `Emitter`. + */ +module.exports = Emitter; +/** + * Initialize a new `Emitter`. + * + * @api public + */ +function Emitter(obj) { + if (obj) return mixin(obj); +}; +/** + * Mixin the emitter properties. + * + * @param {Object} obj + * @return {Object} + * @api private + */ +function mixin(obj) { + for (var key in Emitter.prototype) { + obj[key] = Emitter.prototype[key]; + } + return obj; +} +/** + * Listen on the given `event` with `fn`. + * + * @param {String} event + * @param {Function} fn + * @return {Emitter} + * @api public + */ +Emitter.prototype.on = +Emitter.prototype.addEventListener = function(event, fn){ + this._callbacks = this._callbacks || {}; + (this._callbacks[event] = this._callbacks[event] || []) + .push(fn); + return this; +}; +/** + * Adds an `event` listener that will be invoked a single + * time then automatically removed. + * + * @param {String} event + * @param {Function} fn + * @return {Emitter} + * @api public + */ +Emitter.prototype.once = function(event, fn){ + var self = this; + this._callbacks = this._callbacks || {}; + function on() { + self.off(event, on); + fn.apply(this, arguments); + } + on.fn = fn; + this.on(event, on); + return this; +}; +/** + * Remove the given callback for `event` or all + * registered callbacks. + * + * @param {String} event + * @param {Function} fn + * @return {Emitter} + * @api public + */ +Emitter.prototype.off = +Emitter.prototype.removeListener = +Emitter.prototype.removeAllListeners = +Emitter.prototype.removeEventListener = function(event, fn){ + this._callbacks = this._callbacks || {}; + if (0 == arguments.length) { + this._callbacks = {}; + return this; + } + var callbacks = this._callbacks[event]; + if (!callbacks) return this; + if (1 == arguments.length) { + delete this._callbacks[event]; + return this; + } + var cb; + for (var i = 0; i < callbacks.length; i++) { + cb = callbacks[i]; + if (cb === fn || cb.fn === fn) { + callbacks.splice(i, 1); + break; + } + } + return this; +}; +/** + * Emit `event` with the given args. + * + * @param {String} event + * @param {Mixed} ... + * @return {Emitter} + */ +Emitter.prototype.emit = function(event){ + this._callbacks = this._callbacks || {}; + var args = [].slice.call(arguments, 1) + , callbacks = this._callbacks[event]; + if (callbacks) { + callbacks = callbacks.slice(0); + for (var i = 0, len = callbacks.length; i < len; ++i) { + callbacks[i].apply(this, args); + } + } + return this; +}; +/** + * Return array of callbacks for `event`. + * + * @param {String} event + * @return {Array} + * @api public + */ +Emitter.prototype.listeners = function(event){ + this._callbacks = this._callbacks || {}; + return this._callbacks[event] || []; +}; +/** + * Check if this emitter has `event` handlers. + * + * @param {String} event + * @return {Boolean} + * @api public + */ +Emitter.prototype.hasListeners = function(event){ + return !! this.listeners(event).length; +}; +},{}],7:[function(require,module,exports){ +/** + * Reduce `arr` with `fn`. + * + * @param {Array} arr + * @param {Function} fn + * @param {Mixed} initial + * + * TODO: combatible error handling? + */ +module.exports = function(arr, fn, initial){ + var idx = 0; + var len = arr.length; + var curr = arguments.length == 3 + ? initial + : arr[idx++]; + while (idx < len) { + curr = fn.call(null, curr, arr[idx], ++idx, arr); + } + return curr; +}; +},{}],8:[function(require,module,exports){ +var Emitter = require('component-emitter'); +Emitter.prototype.trigger = Emitter.prototype.emit; +module.exports = Emitter; +},{"component-emitter":4}],9:[function(require,module,exports){ +module.exports = function(){ + return "undefined" == typeof window ? "server" : "browser"; +}; +},{}],10:[function(require,module,exports){ +var each = require('../utils/each'), + JSON2 = require('JSON2'); +module.exports = function(params){ + var query = []; + each(params, function(value, key){ + if ('string' !== typeof value) { + value = JSON2.stringify(value); + } + query.push(key + '=' + encodeURIComponent(value)); + }); + return '?' + query.join('&'); +}; +},{"../utils/each":21,"JSON2":2}],11:[function(require,module,exports){ +module.exports = function(){ + return new Date().getTimezoneOffset() * -60; +}; +},{}],12:[function(require,module,exports){ +module.exports = function(){ + if ("undefined" !== typeof window) { + if (navigator.userAgent.indexOf('MSIE') !== -1 || navigator.appVersion.indexOf('Trident/') > 0) { + return 2000; + } + } + return 16000; +}; +},{}],13:[function(require,module,exports){ +module.exports = function() { + var root = "undefined" == typeof window ? this : window; + if (root.XMLHttpRequest && ("file:" != root.location.protocol || !root.ActiveXObject)) { + return new XMLHttpRequest; + } else { + try { return new ActiveXObject("Microsoft.XMLHTTP"); } catch(e) {} + try { return new ActiveXObject("Msxml2.XMLHTTP.6.0"); } catch(e) {} + try { return new ActiveXObject("Msxml2.XMLHTTP.3.0"); } catch(e) {} + try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch(e) {} + } + return false; +}; +},{}],14:[function(require,module,exports){ +module.exports = function(err, res, callback) { + var cb = callback || function() {}; + if (res && !res.ok) { + var is_err = res.body && res.body.error_code; + err = new Error(is_err ? res.body.message : 'Unknown error occurred'); + err.code = is_err ? res.body.error_code : 'UnknownError'; + } + if (err) { + cb(err, null); + } + else { + cb(null, res.body); + } + return; +}; +},{}],15:[function(require,module,exports){ +var superagent = require('superagent'); +var each = require('../utils/each'), + getXHR = require('./get-xhr-object'); +module.exports = function(type, opts){ + return function(request) { + var __super__ = request.constructor.prototype.end; + if ( 'undefined' === typeof window ) return; + request.requestType = request.requestType || {}; + request.requestType['type'] = type; + request.requestType['options'] = request.requestType['options'] || { + async: true, + success: { + responseText: '{ "created": true }', + status: 201 + }, + error: { + responseText: '{ "error_code": "ERROR", "message": "Request failed" }', + status: 404 + } + }; + if (opts) { + if ( 'boolean' === typeof opts.async ) { + request.requestType['options'].async = opts.async; + } + if ( opts.success ) { + extend(request.requestType['options'].success, opts.success); + } + if ( opts.error ) { + extend(request.requestType['options'].error, opts.error); + } + } + request.end = function(fn){ + var self = this, + reqType = (this.requestType) ? this.requestType['type'] : 'xhr', + query, + timeout; + if ( ('GET' !== self['method'] || 'xhr' === reqType) && self.requestType['options'].async ) { + __super__.call(self, fn); + return; + } + query = self._query.join('&'); + timeout = self._timeout; + self._callback = fn || noop; + if (timeout && !self._timer) { + self._timer = setTimeout(function(){ + abortRequest.call(self); + }, timeout); + } + if (query) { + query = superagent.serializeObject(query); + self.url += ~self.url.indexOf('?') ? '&' + query : '?' + query; + } + self.emit('request', self); + if ( !self.requestType['options'].async ) { + sendXhrSync.call(self); + } + else if ( 'jsonp' === reqType ) { + sendJsonp.call(self); + } + else if ( 'beacon' === reqType ) { + sendBeacon.call(self); + } + return self; + }; + return request; + }; +}; +function sendXhrSync(){ + var xhr = getXHR(); + if (xhr) { + xhr.open('GET', this.url, false); + xhr.send(null); + } + return this; +} +function sendJsonp(){ + var self = this, + timestamp = new Date().getTime(), + script = document.createElement('script'), + parent = document.getElementsByTagName('head')[0], + callbackName = 'keenJSONPCallback', + loaded = false; + callbackName += timestamp; + while (callbackName in window) { + callbackName += 'a'; + } + window[callbackName] = function(response) { + if (loaded === true) return; + loaded = true; + handleSuccess.call(self, response); + cleanup(); + }; + script.src = self.url + '&jsonp=' + callbackName; + parent.appendChild(script); + script.onreadystatechange = function() { + if (loaded === false && self.readyState === 'loaded') { + loaded = true; + handleError.call(self); + cleanup(); + } + }; + script.onerror = function() { + if (loaded === false) { + loaded = true; + handleError.call(self); + cleanup(); + } + }; + function cleanup(){ + window[callbackName] = undefined; + try { + delete window[callbackName]; + } catch(e){} + parent.removeChild(script); + } +} +function sendBeacon(){ + var self = this, + img = document.createElement('img'), + loaded = false; + img.onload = function() { + loaded = true; + if ('naturalHeight' in this) { + if (this.naturalHeight + this.naturalWidth === 0) { + this.onerror(); + return; + } + } else if (this.width + this.height === 0) { + this.onerror(); + return; + } + handleSuccess.call(self); + }; + img.onerror = function() { + loaded = true; + handleError.call(self); + }; + img.src = self.url + '&c=clv1'; +} +function handleSuccess(res){ + var opts = this.requestType['options']['success'], + response = ''; + xhrShim.call(this, opts); + if (res) { + try { + response = JSON.stringify(res); + } catch(e) {} + } + else { + response = opts['responseText']; + } + this.xhr.responseText = response; + this.xhr.status = opts['status']; + this.emit('end'); +} +function handleError(){ + var opts = this.requestType['options']['error']; + xhrShim.call(this, opts); + this.xhr.responseText = opts['responseText']; + this.xhr.status = opts['status']; + this.emit('end'); +} +function abortRequest(){ + this.aborted = true; + this.clearTimeout(); + this.emit('abort'); +} +function xhrShim(opts){ + this.xhr = { + getAllResponseHeaders: function(){ return ''; }, + getResponseHeader: function(){ return 'application/json'; }, + responseText: opts['responseText'], + status: opts['status'] + }; + return this; +} +},{"../utils/each":21,"./get-xhr-object":13,"superagent":5}],16:[function(require,module,exports){ +var root = 'undefined' !== typeof window ? window : this; +var previous_Keen = root.Keen; +var Emitter = require('./helpers/emitter-shim'); +function Keen(config) { + this.configure(config || {}); + Keen.trigger('client', this); +} +Keen.debug = false; +Keen.enabled = true; +Keen.loaded = true; +Keen.version = '3.2.6'; +Emitter(Keen); +Emitter(Keen.prototype); +Keen.prototype.configure = function(cfg){ + var config = cfg || {}; + if (config['host']) { + config['host'].replace(/.*?:\/\//g, ''); + } + if (config.protocol && config.protocol === 'auto') { + config['protocol'] = location.protocol.replace(/:/g, ''); + } + this.config = { + projectId : config.projectId, + writeKey : config.writeKey, + readKey : config.readKey, + masterKey : config.masterKey, + requestType : config.requestType || 'jsonp', + host : config['host'] || 'api.keen.io/3.0', + protocol : config['protocol'] || 'https', + globalProperties: null + }; + if (Keen.debug) { + this.on('error', Keen.log); + } + this.trigger('ready'); +}; +Keen.prototype.projectId = function(str){ + if (!arguments.length) return this.config.projectId; + this.config.projectId = (str ? String(str) : null); + return this; +}; +Keen.prototype.masterKey = function(str){ + if (!arguments.length) return this.config.masterKey; + this.config.masterKey = (str ? String(str) : null); + return this; +}; +Keen.prototype.readKey = function(str){ + if (!arguments.length) return this.config.readKey; + this.config.readKey = (str ? String(str) : null); + return this; +}; +Keen.prototype.writeKey = function(str){ + if (!arguments.length) return this.config.writeKey; + this.config.writeKey = (str ? String(str) : null); + return this; +}; +Keen.prototype.url = function(path){ + if (!this.projectId()) { + this.trigger('error', 'Client is missing projectId property'); + return; + } + return this.config.protocol + '://' + this.config.host + '/projects/' + this.projectId() + path; +}; +Keen.log = function(message) { + if (Keen.debug && typeof console == 'object') { + console.log('[Keen IO]', message); + } +}; +Keen.noConflict = function(){ + root.Keen = previous_Keen; + return Keen; +}; +Keen.ready = function(fn){ + if (Keen.loaded) { + fn(); + } else { + Keen.once('ready', fn); + } +}; +module.exports = Keen; +},{"./helpers/emitter-shim":8}],17:[function(require,module,exports){ +var request = require('superagent'); +var getQueryString = require('../helpers/get-query-string'), + handleResponse = require('../helpers/superagent-handle-response'), + requestTypes = require('../helpers/superagent-request-types'); +module.exports = function(url, params, api_key, callback){ + var reqType = this.config.requestType, + data = params || {}; + if (reqType === 'beacon') { + reqType = 'jsonp'; + } + data['api_key'] = data['api_key'] || api_key; + request + .get(url+getQueryString(data)) + .use(requestTypes(reqType)) + .end(function(err, res){ + handleResponse(err, res, callback); + callback = null; + }); +}; +},{"../helpers/get-query-string":10,"../helpers/superagent-handle-response":14,"../helpers/superagent-request-types":15,"superagent":5}],18:[function(require,module,exports){ +var Request = require("../request"); +module.exports = function(query, callback) { + var queries = [], + cb = callback, + request; + if (query instanceof Array) { + queries = query; + } else { + queries.push(query); + } + request = new Request(this, queries, cb).refresh(); + cb = callback = null; + return request; +}; +},{"../request":20}],19:[function(require,module,exports){ +var each = require("./utils/each"), + extend = require("./utils/extend"), + getTimezoneOffset = require("./helpers/get-timezone-offset"), + getQueryString = require("./helpers/get-query-string"); +var Emitter = require('./helpers/emitter-shim'); +function Query(){ + this.configure.apply(this, arguments); +}; +Emitter(Query.prototype); +Query.prototype.configure = function(analysisType, params) { + this.analysis = analysisType; + this.params = this.params || {}; + this.set(params); + if (this.params.timezone === void 0) { + this.params.timezone = getTimezoneOffset(); + } + return this; +}; +Query.prototype.set = function(attributes) { + var self = this; + each(attributes, function(v, k){ + var key = k, value = v; + if (k.match(new RegExp("[A-Z]"))) { + key = k.replace(/([A-Z])/g, function($1) { return "_"+$1.toLowerCase(); }); + } + self.params[key] = value; + if (value instanceof Array) { + each(value, function(dv, index){ + if (dv instanceof Array == false && typeof dv === "object") { + each(dv, function(deepValue, deepKey){ + if (deepKey.match(new RegExp("[A-Z]"))) { + var _deepKey = deepKey.replace(/([A-Z])/g, function($1) { return "_"+$1.toLowerCase(); }); + delete self.params[key][index][deepKey]; + self.params[key][index][_deepKey] = deepValue; + } + }); + } + }); + } + }); + return self; +}; +Query.prototype.get = function(attribute) { + var key = attribute; + if (key.match(new RegExp("[A-Z]"))) { + key = key.replace(/([A-Z])/g, function($1) { return "_"+$1.toLowerCase(); }); + } + if (this.params) { + return this.params[key] || null; + } +}; +Query.prototype.addFilter = function(property, operator, value) { + this.params.filters = this.params.filters || []; + this.params.filters.push({ + "property_name": property, + "operator": operator, + "property_value": value + }); + return this; +}; +module.exports = Query; +},{"./helpers/emitter-shim":8,"./helpers/get-query-string":10,"./helpers/get-timezone-offset":11,"./utils/each":21,"./utils/extend":22}],20:[function(require,module,exports){ +var each = require("./utils/each"), + extend = require("./utils/extend"), + sendQuery = require("./utils/sendQuery"); +var Keen = require("./"); +var Emitter = require('./helpers/emitter-shim'); +function Request(client, queries, callback){ + var cb = callback; + this.config = { + timeout: 300 * 1000 + }; + this.configure(client, queries, cb); + cb = callback = null; +}; +Emitter(Request.prototype); +Request.prototype.configure = function(client, queries, callback){ + var cb = callback; + extend(this, { + "client" : client, + "queries" : queries, + "data" : {}, + "callback" : cb + }); + cb = callback = null; + return this; +}; +Request.prototype.timeout = function(ms){ + if (!arguments.length) return this.config.timeout; + this.config.timeout = (!isNaN(parseInt(ms)) ? parseInt(ms) : null); + return this; +}; +Request.prototype.refresh = function(){ + var self = this, + completions = 0, + response = [], + errored = false; + var handleResponse = function(err, res, index){ + if (err) { + self.trigger("error", err); + if (self.callback) { + self.callback(err, null); + } + errored = true; + return; + } + response[index] = res; + completions++; + if (completions == self.queries.length && !errored) { + self.data = (self.queries.length == 1) ? response[0] : response; + self.trigger("complete", null, self.data); + if (self.callback) { + self.callback(null, self.data); + } + } + }; + each(self.queries, function(query, index){ + var path; + var cbSequencer = function(err, res){ + handleResponse(err, res, index); + }; + if (query instanceof Keen.Query) { + path = "/queries/" + query.analysis; + sendQuery.call(self, path, query.params, cbSequencer); + } + else if ( Object.prototype.toString.call(query) === "[object String]" ) { + path = "/saved_queries/" + encodeURIComponent(query) + "/result"; + sendQuery.call(self, path, null, cbSequencer); + } + else { + var res = { + statusText: "Bad Request", + responseText: { message: "Error: Query " + (+index+1) + " of " + self.queries.length + " for project " + self.client.projectId() + " is not a valid request" } + }; + self.trigger("error", res.responseText.message); + if (self.callback) { + self.callback(res.responseText.message, null); + } + } + }); + return this; +}; +module.exports = Request; +},{"./":16,"./helpers/emitter-shim":8,"./utils/each":21,"./utils/extend":22,"./utils/sendQuery":24}],21:[function(require,module,exports){ +module.exports = function(o, cb, s){ + var n; + if (!o){ + return 0; + } + s = !s ? o : s; + if (o instanceof Array){ + for (n=0; n0){return 2000}}return 16000}},{}],13:[function(b,c,a){c.exports=function(){var d="undefined"==typeof window?this:window;if(d.XMLHttpRequest&&("file:"!=d.location.protocol||!d.ActiveXObject)){return new XMLHttpRequest}else{try{return new ActiveXObject("Microsoft.XMLHTTP")}catch(f){}try{return new ActiveXObject("Msxml2.XMLHTTP.6.0")}catch(f){}try{return new ActiveXObject("Msxml2.XMLHTTP.3.0")}catch(f){}try{return new ActiveXObject("Msxml2.XMLHTTP")}catch(f){}}return false}},{}],14:[function(b,c,a){c.exports=function(h,g,i){var f=i||function(){};if(g&&!g.ok){var d=g.body&&g.body.error_code;h=new Error(d?g.body.message:"Unknown error occurred");h.code=d?g.body.error_code:"UnknownError"}if(h){f(h,null)}else{f(null,g.body)}return}},{}],15:[function(f,b,g){var n=f("superagent");var l=f("../utils/each"),a=f("./get-xhr-object");b.exports=function(o,p){return function(q){var r=q.constructor.prototype.end;if("undefined"===typeof window){return}q.requestType=q.requestType||{};q.requestType.type=o;q.requestType.options=q.requestType.options||{async:true,success:{responseText:'{ "created": true }',status:201},error:{responseText:'{ "error_code": "ERROR", "message": "Request failed" }',status:404}};if(p){if("boolean"===typeof p.async){q.requestType.options.async=p.async}if(p.success){extend(q.requestType.options.success,p.success)}if(p.error){extend(q.requestType.options.error,p.error)}}q.end=function(u){var t=this,s=(this.requestType)?this.requestType.type:"xhr",w,v;if(("GET"!==t.method||"xhr"===s)&&t.requestType.options.async){r.call(t,u);return}w=t._query.join("&");v=t._timeout;t._callback=u||noop;if(v&&!t._timer){t._timer=setTimeout(function(){h.call(t)},v)}if(w){w=n.serializeObject(w);t.url+=~t.url.indexOf("?")?"&"+w:"?"+w}t.emit("request",t);if(!t.requestType.options.async){k.call(t)}else{if("jsonp"===s){j.call(t)}else{if("beacon"===s){i.call(t)}}}return t};return q}};function k(){var o=a();if(o){o.open("GET",this.url,false);o.send(null)}return this}function j(){var p=this,t=new Date().getTime(),o=document.createElement("script"),s=document.getElementsByTagName("head")[0],u="keenJSONPCallback",q=false;u+=t;while(u in window){u+="a"}window[u]=function(v){if(q===true){return}q=true;d.call(p,v);r()};o.src=p.url+"&jsonp="+u;s.appendChild(o);o.onreadystatechange=function(){if(q===false&&p.readyState==="loaded"){q=true;c.call(p);r()}};o.onerror=function(){if(q===false){q=true;c.call(p);r()}};function r(){window[u]=undefined;try{delete window[u]}catch(v){}s.removeChild(o)}}function i(){var p=this,o=document.createElement("img"),q=false;o.onload=function(){q=true;if("naturalHeight" in this){if(this.naturalHeight+this.naturalWidth===0){this.onerror();return}}else{if(this.width+this.height===0){this.onerror();return}}d.call(p)};o.onerror=function(){q=true;c.call(p)};o.src=p.url+"&c=clv1"}function d(p){var q=this.requestType.options["success"],o="";m.call(this,q);if(p){try{o=JSON.stringify(p)}catch(r){}}else{o=q.responseText}this.xhr.responseText=o;this.xhr.status=q.status;this.emit("end")}function c(){var o=this.requestType.options["error"];m.call(this,o);this.xhr.responseText=o.responseText;this.xhr.status=o.status;this.emit("end")}function h(){this.aborted=true;this.clearTimeout();this.emit("abort")}function m(o){this.xhr={getAllResponseHeaders:function(){return""},getResponseHeader:function(){return"application/json"},responseText:o.responseText,status:o.status};return this}},{"../utils/each":21,"./get-xhr-object":13,superagent:5}],16:[function(d,f,c){var b="undefined"!==typeof window?window:this;var h=b.Keen;var g=d("./helpers/emitter-shim");function a(i){this.configure(i||{});a.trigger("client",this)}a.debug=false;a.enabled=true;a.loaded=true;a.version="3.2.6";g(a);g(a.prototype);a.prototype.configure=function(i){var j=i||{};if(j.host){j.host.replace(/.*?:\/\//g,"")}if(j.protocol&&j.protocol==="auto"){j.protocol=location.protocol.replace(/:/g,"")}this.config={projectId:j.projectId,writeKey:j.writeKey,readKey:j.readKey,masterKey:j.masterKey,requestType:j.requestType||"jsonp",host:j.host||"api.keen.io/3.0",protocol:j.protocol||"https",globalProperties:null};if(a.debug){this.on("error",a.log)}this.trigger("ready")};a.prototype.projectId=function(i){if(!arguments.length){return this.config.projectId}this.config.projectId=(i?String(i):null);return this};a.prototype.masterKey=function(i){if(!arguments.length){return this.config.masterKey}this.config.masterKey=(i?String(i):null);return this};a.prototype.readKey=function(i){if(!arguments.length){return this.config.readKey}this.config.readKey=(i?String(i):null);return this};a.prototype.writeKey=function(i){if(!arguments.length){return this.config.writeKey}this.config.writeKey=(i?String(i):null);return this};a.prototype.url=function(i){if(!this.projectId()){this.trigger("error","Client is missing projectId property");return}return this.config.protocol+"://"+this.config.host+"/projects/"+this.projectId()+i};a.log=function(i){if(a.debug&&typeof console=="object"){console.log("[Keen IO]",i)}};a.noConflict=function(){b.Keen=h;return a};a.ready=function(i){if(a.loaded){i()}else{a.once("ready",i)}};f.exports=a},{"./helpers/emitter-shim":8}],17:[function(d,f,c){var h=d("superagent");var b=d("../helpers/get-query-string"),g=d("../helpers/superagent-handle-response"),a=d("../helpers/superagent-request-types");f.exports=function(j,m,l,n){var i=this.config.requestType,k=m||{};if(i==="beacon"){i="jsonp"}k.api_key=k.api_key||l;h.get(j+b(k)).use(a(i)).end(function(p,o){g(p,o,n);n=null})}},{"../helpers/get-query-string":10,"../helpers/superagent-handle-response":14,"../helpers/superagent-request-types":15,superagent:5}],18:[function(b,d,a){var c=b("../request");d.exports=function(i,j){var g=[],f=j,h;if(i instanceof Array){g=i}else{g.push(i)}h=new c(this,g,f).refresh();f=j=null;return h}},{"../request":20}],19:[function(c,a,d){var j=c("./utils/each"),h=c("./utils/extend"),g=c("./helpers/get-timezone-offset"),b=c("./helpers/get-query-string");var i=c("./helpers/emitter-shim");function f(){this.configure.apply(this,arguments)}i(f.prototype);f.prototype.configure=function(k,l){this.analysis=k;this.params=this.params||{};this.set(l);if(this.params.timezone===void 0){this.params.timezone=g()}return this};f.prototype.set=function(l){var k=this;j(l,function(n,m){var o=m,p=n;if(m.match(new RegExp("[A-Z]"))){o=m.replace(/([A-Z])/g,function(q){return"_"+q.toLowerCase()})}k.params[o]=p;if(p instanceof Array){j(p,function(r,q){if(r instanceof Array==false&&typeof r==="object"){j(r,function(t,s){if(s.match(new RegExp("[A-Z]"))){var u=s.replace(/([A-Z])/g,function(v){return"_"+v.toLowerCase()});delete k.params[o][q][s];k.params[o][q][u]=t}})}})}});return k};f.prototype.get=function(l){var k=l;if(k.match(new RegExp("[A-Z]"))){k=k.replace(/([A-Z])/g,function(m){return"_"+m.toLowerCase()})}if(this.params){return this.params[k]||null}};f.prototype.addFilter=function(m,k,l){this.params.filters=this.params.filters||[];this.params.filters.push({property_name:m,operator:k,property_value:l});return this};a.exports=f},{"./helpers/emitter-shim":8,"./helpers/get-query-string":10,"./helpers/get-timezone-offset":11,"./utils/each":21,"./utils/extend":22}],20:[function(c,b,d){var j=c("./utils/each"),h=c("./utils/extend"),g=c("./utils/sendQuery");var f=c("./");var i=c("./helpers/emitter-shim");function a(l,m,n){var k=n;this.config={timeout:300*1000};this.configure(l,m,k);k=n=null}i(a.prototype);a.prototype.configure=function(l,m,n){var k=n;h(this,{client:l,queries:m,data:{},callback:k});k=n=null;return this};a.prototype.timeout=function(k){if(!arguments.length){return this.config.timeout}this.config.timeout=(!isNaN(parseInt(k))?parseInt(k):null);return this};a.prototype.refresh=function(){var m=this,k=0,l=[],o=false;var n=function(r,q,p){if(r){m.trigger("error",r);if(m.callback){m.callback(r,null)}o=true;return}l[p]=q;k++;if(k==m.queries.length&&!o){m.data=(m.queries.length==1)?l[0]:l;m.trigger("complete",null,m.data);if(m.callback){m.callback(null,m.data)}}};j(m.queries,function(s,q){var t;var p=function(v,u){n(v,u,q)};if(s instanceof f.Query){t="/queries/"+s.analysis;g.call(m,t,s.params,p)}else{if(Object.prototype.toString.call(s)==="[object String]"){t="/saved_queries/"+encodeURIComponent(s)+"/result";g.call(m,t,null,p)}else{var r={statusText:"Bad Request",responseText:{message:"Error: Query "+(+q+1)+" of "+m.queries.length+" for project "+m.client.projectId()+" is not a valid request"}};m.trigger("error",r.responseText.message);if(m.callback){m.callback(r.responseText.message,null)}}}});return this};b.exports=a},{"./":16,"./helpers/emitter-shim":8,"./utils/each":21,"./utils/extend":22,"./utils/sendQuery":24}],21:[function(b,c,a){c.exports=function(g,d,f){var h;if(!g){return 0}f=!f?g:f;if(g instanceof Array){for(h=0;hhey!'], { type: "text/html"})) + * .end(callback); + * ``` + * + * @param {String} field + * @param {Blob|File} file + * @param {String} filename + * @return {Request} for chaining + * @api public + */ +Request.prototype.attach = function(field, file, filename){ + if (!this._formData) this._formData = new FormData(); + this._formData.append(field, file, filename); + return this; +}; +/** + * Send `data`, defaulting the `.type()` to "json" when + * an object is given. + * + * Examples: + * + * + * request.get('/search') + * .end(callback) + * + * + * request.get('/search') + * .send({ search: 'query' }) + * .send({ range: '1..5' }) + * .send({ order: 'desc' }) + * .end(callback) + * + * + * request.post('/user') + * .type('json') + * .send('{"name":"tj"}) + * .end(callback) + * + * + * request.post('/user') + * .send({ name: 'tj' }) + * .end(callback) + * + * + * request.post('/user') + * .type('form') + * .send('name=tj') + * .end(callback) + * + * + * request.post('/user') + * .type('form') + * .send({ name: 'tj' }) + * .end(callback) + * + * + * request.post('/user') + * .send('name=tobi') + * .send('species=ferret') + * .end(callback) + * + * @param {String|Object} data + * @return {Request} for chaining + * @api public + */ +Request.prototype.send = function(data){ + var obj = isObject(data); + var type = this.getHeader('Content-Type'); + if (obj && isObject(this._data)) { + for (var key in data) { + this._data[key] = data[key]; + } + } else if ('string' == typeof data) { + if (!type) this.type('form'); + type = this.getHeader('Content-Type'); + if ('application/x-www-form-urlencoded' == type) { + this._data = this._data + ? this._data + '&' + data + : data; + } else { + this._data = (this._data || '') + data; + } + } else { + this._data = data; + } + if (!obj) return this; + if (!type) this.type('json'); + return this; +}; +/** + * Invoke the callback with `err` and `res` + * and handle arity check. + * + * @param {Error} err + * @param {Response} res + * @api private + */ +Request.prototype.callback = function(err, res){ + var fn = this._callback; + this.clearTimeout(); + if (2 == fn.length) return fn(err, res); + if (err) return this.emit('error', err); + fn(res); +}; +/** + * Invoke callback with x-domain error. + * + * @api private + */ +Request.prototype.crossDomainError = function(){ + var err = new Error('Origin is not allowed by Access-Control-Allow-Origin'); + err.crossDomain = true; + this.callback(err); +}; +/** + * Invoke callback with timeout error. + * + * @api private + */ +Request.prototype.timeoutError = function(){ + var timeout = this._timeout; + var err = new Error('timeout of ' + timeout + 'ms exceeded'); + err.timeout = timeout; + this.callback(err); +}; +/** + * Enable transmission of cookies with x-domain requests. + * + * Note that for this to work the origin must not be + * using "Access-Control-Allow-Origin" with a wildcard, + * and also must set "Access-Control-Allow-Credentials" + * to "true". + * + * @api public + */ +Request.prototype.withCredentials = function(){ + this._withCredentials = true; + return this; +}; +/** + * Initiate request, invoking callback `fn(res)` + * with an instanceof `Response`. + * + * @param {Function} fn + * @return {Request} for chaining + * @api public + */ +Request.prototype.end = function(fn){ + var self = this; + var xhr = this.xhr = getXHR(); + var query = this._query.join('&'); + var timeout = this._timeout; + var data = this._formData || this._data; + this._callback = fn || noop; + xhr.onreadystatechange = function(){ + if (4 != xhr.readyState) return; + if (0 == xhr.status) { + if (self.aborted) return self.timeoutError(); + return self.crossDomainError(); + } + self.emit('end'); + }; + if (xhr.upload) { + xhr.upload.onprogress = function(e){ + e.percent = e.loaded / e.total * 100; + self.emit('progress', e); + }; + } + if (timeout && !this._timer) { + this._timer = setTimeout(function(){ + self.abort(); + }, timeout); + } + if (query) { + query = request.serializeObject(query); + this.url += ~this.url.indexOf('?') + ? '&' + query + : '?' + query; + } + xhr.open(this.method, this.url, true); + if (this._withCredentials) xhr.withCredentials = true; + if ('GET' != this.method && 'HEAD' != this.method && 'string' != typeof data && !isHost(data)) { + var serialize = request.serialize[this.getHeader('Content-Type')]; + if (serialize) data = serialize(data); + } + for (var field in this.header) { + if (null == this.header[field]) continue; + xhr.setRequestHeader(field, this.header[field]); + } + this.emit('request', this); + xhr.send(data); + return this; +}; +/** + * Expose `Request`. + */ +request.Request = Request; +/** + * Issue a request: + * + * Examples: + * + * request('GET', '/users').end(callback) + * request('/users').end(callback) + * request('/users', callback) + * + * @param {String} method + * @param {String|Function} url or callback + * @return {Request} + * @api public + */ +function request(method, url) { + if ('function' == typeof url) { + return new Request('GET', method).end(url); + } + if (1 == arguments.length) { + return new Request('GET', method); + } + return new Request(method, url); +} +/** + * GET `url` with optional callback `fn(res)`. + * + * @param {String} url + * @param {Mixed|Function} data or fn + * @param {Function} fn + * @return {Request} + * @api public + */ +request.get = function(url, data, fn){ + var req = request('GET', url); + if ('function' == typeof data) fn = data, data = null; + if (data) req.query(data); + if (fn) req.end(fn); + return req; +}; +/** + * HEAD `url` with optional callback `fn(res)`. + * + * @param {String} url + * @param {Mixed|Function} data or fn + * @param {Function} fn + * @return {Request} + * @api public + */ +request.head = function(url, data, fn){ + var req = request('HEAD', url); + if ('function' == typeof data) fn = data, data = null; + if (data) req.send(data); + if (fn) req.end(fn); + return req; +}; +/** + * DELETE `url` with optional callback `fn(res)`. + * + * @param {String} url + * @param {Function} fn + * @return {Request} + * @api public + */ +request.del = function(url, fn){ + var req = request('DELETE', url); + if (fn) req.end(fn); + return req; +}; +/** + * PATCH `url` with optional `data` and callback `fn(res)`. + * + * @param {String} url + * @param {Mixed} data + * @param {Function} fn + * @return {Request} + * @api public + */ +request.patch = function(url, data, fn){ + var req = request('PATCH', url); + if ('function' == typeof data) fn = data, data = null; + if (data) req.send(data); + if (fn) req.end(fn); + return req; +}; +/** + * POST `url` with optional `data` and callback `fn(res)`. + * + * @param {String} url + * @param {Mixed} data + * @param {Function} fn + * @return {Request} + * @api public + */ +request.post = function(url, data, fn){ + var req = request('POST', url); + if ('function' == typeof data) fn = data, data = null; + if (data) req.send(data); + if (fn) req.end(fn); + return req; +}; +/** + * PUT `url` with optional `data` and callback `fn(res)`. + * + * @param {String} url + * @param {Mixed|Function} data or fn + * @param {Function} fn + * @return {Request} + * @api public + */ +request.put = function(url, data, fn){ + var req = request('PUT', url); + if ('function' == typeof data) fn = data, data = null; + if (data) req.send(data); + if (fn) req.end(fn); + return req; +}; +/** + * Expose `request`. + */ +module.exports = request; +},{"emitter":7,"reduce":8}],7:[function(require,module,exports){ +/** + * Expose `Emitter`. + */ +module.exports = Emitter; +/** + * Initialize a new `Emitter`. + * + * @api public + */ +function Emitter(obj) { + if (obj) return mixin(obj); +}; +/** + * Mixin the emitter properties. + * + * @param {Object} obj + * @return {Object} + * @api private + */ +function mixin(obj) { + for (var key in Emitter.prototype) { + obj[key] = Emitter.prototype[key]; + } + return obj; +} +/** + * Listen on the given `event` with `fn`. + * + * @param {String} event + * @param {Function} fn + * @return {Emitter} + * @api public + */ +Emitter.prototype.on = +Emitter.prototype.addEventListener = function(event, fn){ + this._callbacks = this._callbacks || {}; + (this._callbacks[event] = this._callbacks[event] || []) + .push(fn); + return this; +}; +/** + * Adds an `event` listener that will be invoked a single + * time then automatically removed. + * + * @param {String} event + * @param {Function} fn + * @return {Emitter} + * @api public + */ +Emitter.prototype.once = function(event, fn){ + var self = this; + this._callbacks = this._callbacks || {}; + function on() { + self.off(event, on); + fn.apply(this, arguments); + } + on.fn = fn; + this.on(event, on); + return this; +}; +/** + * Remove the given callback for `event` or all + * registered callbacks. + * + * @param {String} event + * @param {Function} fn + * @return {Emitter} + * @api public + */ +Emitter.prototype.off = +Emitter.prototype.removeListener = +Emitter.prototype.removeAllListeners = +Emitter.prototype.removeEventListener = function(event, fn){ + this._callbacks = this._callbacks || {}; + if (0 == arguments.length) { + this._callbacks = {}; + return this; + } + var callbacks = this._callbacks[event]; + if (!callbacks) return this; + if (1 == arguments.length) { + delete this._callbacks[event]; + return this; + } + var cb; + for (var i = 0; i < callbacks.length; i++) { + cb = callbacks[i]; + if (cb === fn || cb.fn === fn) { + callbacks.splice(i, 1); + break; + } + } + return this; +}; +/** + * Emit `event` with the given args. + * + * @param {String} event + * @param {Mixed} ... + * @return {Emitter} + */ +Emitter.prototype.emit = function(event){ + this._callbacks = this._callbacks || {}; + var args = [].slice.call(arguments, 1) + , callbacks = this._callbacks[event]; + if (callbacks) { + callbacks = callbacks.slice(0); + for (var i = 0, len = callbacks.length; i < len; ++i) { + callbacks[i].apply(this, args); + } + } + return this; +}; +/** + * Return array of callbacks for `event`. + * + * @param {String} event + * @return {Array} + * @api public + */ +Emitter.prototype.listeners = function(event){ + this._callbacks = this._callbacks || {}; + return this._callbacks[event] || []; +}; +/** + * Check if this emitter has `event` handlers. + * + * @param {String} event + * @return {Boolean} + * @api public + */ +Emitter.prototype.hasListeners = function(event){ + return !! this.listeners(event).length; +}; +},{}],8:[function(require,module,exports){ +/** + * Reduce `arr` with `fn`. + * + * @param {Array} arr + * @param {Function} fn + * @param {Mixed} initial + * + * TODO: combatible error handling? + */ +module.exports = function(arr, fn, initial){ + var idx = 0; + var len = arr.length; + var curr = arguments.length == 3 + ? initial + : arr[idx++]; + while (idx < len) { + curr = fn.call(null, curr, arr[idx], ++idx, arr); + } + return curr; +}; +},{}],9:[function(require,module,exports){ +var Keen = require("./index"), + each = require("./utils/each"); +module.exports = function(){ + var loaded = window['Keen'] || null, + cached = window['_' + 'Keen'] || null, + clients, + ready; + if (loaded && cached) { + clients = cached['clients'] || {}, + ready = cached['ready'] || []; + each(clients, function(client, id){ + each(Keen.prototype, function(method, key){ + loaded.prototype[key] = method; + }); + each(["Query", "Request", "Dataset", "Dataviz"], function(name){ + loaded[name] = (Keen[name]) ? Keen[name] : function(){}; + }); + if (client._config) { + client.configure.call(client, client._config); + } + if (client._setGlobalProperties) { + each(client._setGlobalProperties, function(fn){ + client.setGlobalProperties.apply(client, fn); + }); + } + if (client._addEvent) { + each(client._addEvent, function(obj){ + client.addEvent.apply(client, obj); + }); + } + var callback = client._on || []; + if (client._on) { + each(client._on, function(obj){ + client.on.apply(client, obj); + }); + client.trigger('ready'); + } + each(["_config", "_setGlobalProperties", "_addEvent", "_on"], function(name){ + if (client[name]) { + client[name] = undefined; + try{ + delete client[name]; + } catch(e){} + } + }); + }); + each(ready, function(cb, i){ + Keen.once("ready", cb); + }); + } + window['_' + 'Keen'] = undefined; + try { + delete window['_' + 'Keen'] + } catch(e) {} +}; +},{"./index":17,"./utils/each":23}],10:[function(require,module,exports){ +var Emitter = require('component-emitter'); +Emitter.prototype.trigger = Emitter.prototype.emit; +module.exports = Emitter; +},{"component-emitter":4}],11:[function(require,module,exports){ +module.exports = function(){ + return "undefined" == typeof window ? "server" : "browser"; +}; +},{}],12:[function(require,module,exports){ +var each = require('../utils/each'), + JSON2 = require('JSON2'); +module.exports = function(params){ + var query = []; + each(params, function(value, key){ + if ('string' !== typeof value) { + value = JSON2.stringify(value); + } + query.push(key + '=' + encodeURIComponent(value)); + }); + return '?' + query.join('&'); +}; +},{"../utils/each":23,"JSON2":2}],13:[function(require,module,exports){ +module.exports = function(){ + if ("undefined" !== typeof window) { + if (navigator.userAgent.indexOf('MSIE') !== -1 || navigator.appVersion.indexOf('Trident/') > 0) { + return 2000; + } + } + return 16000; +}; +},{}],14:[function(require,module,exports){ +module.exports = function() { + var root = "undefined" == typeof window ? this : window; + if (root.XMLHttpRequest && ("file:" != root.location.protocol || !root.ActiveXObject)) { + return new XMLHttpRequest; + } else { + try { return new ActiveXObject("Microsoft.XMLHTTP"); } catch(e) {} + try { return new ActiveXObject("Msxml2.XMLHTTP.6.0"); } catch(e) {} + try { return new ActiveXObject("Msxml2.XMLHTTP.3.0"); } catch(e) {} + try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch(e) {} + } + return false; +}; +},{}],15:[function(require,module,exports){ +module.exports = function(err, res, callback) { + var cb = callback || function() {}; + if (res && !res.ok) { + var is_err = res.body && res.body.error_code; + err = new Error(is_err ? res.body.message : 'Unknown error occurred'); + err.code = is_err ? res.body.error_code : 'UnknownError'; + } + if (err) { + cb(err, null); + } + else { + cb(null, res.body); + } + return; +}; +},{}],16:[function(require,module,exports){ +var superagent = require('superagent'); +var each = require('../utils/each'), + getXHR = require('./get-xhr-object'); +module.exports = function(type, opts){ + return function(request) { + var __super__ = request.constructor.prototype.end; + if ( 'undefined' === typeof window ) return; + request.requestType = request.requestType || {}; + request.requestType['type'] = type; + request.requestType['options'] = request.requestType['options'] || { + async: true, + success: { + responseText: '{ "created": true }', + status: 201 + }, + error: { + responseText: '{ "error_code": "ERROR", "message": "Request failed" }', + status: 404 + } + }; + if (opts) { + if ( 'boolean' === typeof opts.async ) { + request.requestType['options'].async = opts.async; + } + if ( opts.success ) { + extend(request.requestType['options'].success, opts.success); + } + if ( opts.error ) { + extend(request.requestType['options'].error, opts.error); + } + } + request.end = function(fn){ + var self = this, + reqType = (this.requestType) ? this.requestType['type'] : 'xhr', + query, + timeout; + if ( ('GET' !== self['method'] || 'xhr' === reqType) && self.requestType['options'].async ) { + __super__.call(self, fn); + return; + } + query = self._query.join('&'); + timeout = self._timeout; + self._callback = fn || noop; + if (timeout && !self._timer) { + self._timer = setTimeout(function(){ + abortRequest.call(self); + }, timeout); + } + if (query) { + query = superagent.serializeObject(query); + self.url += ~self.url.indexOf('?') ? '&' + query : '?' + query; + } + self.emit('request', self); + if ( !self.requestType['options'].async ) { + sendXhrSync.call(self); + } + else if ( 'jsonp' === reqType ) { + sendJsonp.call(self); + } + else if ( 'beacon' === reqType ) { + sendBeacon.call(self); + } + return self; + }; + return request; + }; +}; +function sendXhrSync(){ + var xhr = getXHR(); + if (xhr) { + xhr.open('GET', this.url, false); + xhr.send(null); + } + return this; +} +function sendJsonp(){ + var self = this, + timestamp = new Date().getTime(), + script = document.createElement('script'), + parent = document.getElementsByTagName('head')[0], + callbackName = 'keenJSONPCallback', + loaded = false; + callbackName += timestamp; + while (callbackName in window) { + callbackName += 'a'; + } + window[callbackName] = function(response) { + if (loaded === true) return; + loaded = true; + handleSuccess.call(self, response); + cleanup(); + }; + script.src = self.url + '&jsonp=' + callbackName; + parent.appendChild(script); + script.onreadystatechange = function() { + if (loaded === false && self.readyState === 'loaded') { + loaded = true; + handleError.call(self); + cleanup(); + } + }; + script.onerror = function() { + if (loaded === false) { + loaded = true; + handleError.call(self); + cleanup(); + } + }; + function cleanup(){ + window[callbackName] = undefined; + try { + delete window[callbackName]; + } catch(e){} + parent.removeChild(script); + } +} +function sendBeacon(){ + var self = this, + img = document.createElement('img'), + loaded = false; + img.onload = function() { + loaded = true; + if ('naturalHeight' in this) { + if (this.naturalHeight + this.naturalWidth === 0) { + this.onerror(); + return; + } + } else if (this.width + this.height === 0) { + this.onerror(); + return; + } + handleSuccess.call(self); + }; + img.onerror = function() { + loaded = true; + handleError.call(self); + }; + img.src = self.url + '&c=clv1'; +} +function handleSuccess(res){ + var opts = this.requestType['options']['success'], + response = ''; + xhrShim.call(this, opts); + if (res) { + try { + response = JSON.stringify(res); + } catch(e) {} + } + else { + response = opts['responseText']; + } + this.xhr.responseText = response; + this.xhr.status = opts['status']; + this.emit('end'); +} +function handleError(){ + var opts = this.requestType['options']['error']; + xhrShim.call(this, opts); + this.xhr.responseText = opts['responseText']; + this.xhr.status = opts['status']; + this.emit('end'); +} +function abortRequest(){ + this.aborted = true; + this.clearTimeout(); + this.emit('abort'); +} +function xhrShim(opts){ + this.xhr = { + getAllResponseHeaders: function(){ return ''; }, + getResponseHeader: function(){ return 'application/json'; }, + responseText: opts['responseText'], + status: opts['status'] + }; + return this; +} +},{"../utils/each":23,"./get-xhr-object":14,"superagent":6}],17:[function(require,module,exports){ +var root = 'undefined' !== typeof window ? window : this; +var previous_Keen = root.Keen; +var Emitter = require('./helpers/emitter-shim'); +function Keen(config) { + this.configure(config || {}); + Keen.trigger('client', this); +} +Keen.debug = false; +Keen.enabled = true; +Keen.loaded = true; +Keen.version = '3.2.6'; +Emitter(Keen); +Emitter(Keen.prototype); +Keen.prototype.configure = function(cfg){ + var config = cfg || {}; + if (config['host']) { + config['host'].replace(/.*?:\/\//g, ''); + } + if (config.protocol && config.protocol === 'auto') { + config['protocol'] = location.protocol.replace(/:/g, ''); + } + this.config = { + projectId : config.projectId, + writeKey : config.writeKey, + readKey : config.readKey, + masterKey : config.masterKey, + requestType : config.requestType || 'jsonp', + host : config['host'] || 'api.keen.io/3.0', + protocol : config['protocol'] || 'https', + globalProperties: null + }; + if (Keen.debug) { + this.on('error', Keen.log); + } + this.trigger('ready'); +}; +Keen.prototype.projectId = function(str){ + if (!arguments.length) return this.config.projectId; + this.config.projectId = (str ? String(str) : null); + return this; +}; +Keen.prototype.masterKey = function(str){ + if (!arguments.length) return this.config.masterKey; + this.config.masterKey = (str ? String(str) : null); + return this; +}; +Keen.prototype.readKey = function(str){ + if (!arguments.length) return this.config.readKey; + this.config.readKey = (str ? String(str) : null); + return this; +}; +Keen.prototype.writeKey = function(str){ + if (!arguments.length) return this.config.writeKey; + this.config.writeKey = (str ? String(str) : null); + return this; +}; +Keen.prototype.url = function(path){ + if (!this.projectId()) { + this.trigger('error', 'Client is missing projectId property'); + return; + } + return this.config.protocol + '://' + this.config.host + '/projects/' + this.projectId() + path; +}; +Keen.log = function(message) { + if (Keen.debug && typeof console == 'object') { + console.log('[Keen IO]', message); + } +}; +Keen.noConflict = function(){ + root.Keen = previous_Keen; + return Keen; +}; +Keen.ready = function(fn){ + if (Keen.loaded) { + fn(); + } else { + Keen.once('ready', fn); + } +}; +module.exports = Keen; +},{"./helpers/emitter-shim":10}],18:[function(require,module,exports){ +var JSON2 = require('JSON2'); +var request = require('superagent'); +var Keen = require('../index'); +var base64 = require('../utils/base64'), + each = require('../utils/each'), + getContext = require('../helpers/get-context'), + getQueryString = require('../helpers/get-query-string'), + getUrlMaxLength = require('../helpers/get-url-max-length'), + getXHR = require('../helpers/get-xhr-object'), + requestTypes = require('../helpers/superagent-request-types'), + responseHandler = require('../helpers/superagent-handle-response'); +module.exports = function(collection, payload, callback, async) { + var self = this, + urlBase = this.url('/events/' + encodeURIComponent(collection)), + reqType = this.config.requestType, + data = {}, + cb = callback, + isAsync, + getUrl; + isAsync = ('boolean' === typeof async) ? async : true; + if (!Keen.enabled) { + handleValidationError.call(self, 'Keen.enabled = false'); + return; + } + if (!self.projectId()) { + handleValidationError.call(self, 'Missing projectId property'); + return; + } + if (!self.writeKey()) { + handleValidationError.call(self, 'Missing writeKey property'); + return; + } + if (!collection || typeof collection !== 'string') { + handleValidationError.call(self, 'Collection name must be a string'); + return; + } + if (self.config.globalProperties) { + data = self.config.globalProperties(collection); + } + each(payload, function(value, key){ + data[key] = value; + }); + if ( !getXHR() && 'xhr' === reqType ) { + reqType = 'jsonp'; + } + if ( 'xhr' !== reqType || !isAsync ) { + getUrl = prepareGetRequest.call(self, urlBase, data); + } + if ( getUrl && getContext() === 'browser' ) { + request + .get(getUrl) + .use(requestTypes(reqType, { async: isAsync })) + .end(handleResponse); + } + else if ( getXHR() || getContext() === 'server' ) { + request + .post(urlBase) + .set('Content-Type', 'application/json') + .set('Authorization', self.writeKey()) + .send(data) + .end(handleResponse); + } + else { + self.trigger('error', 'Request not sent: URL length exceeds current browser limit, and XHR (POST) is not supported.'); + } + function handleResponse(err, res){ + responseHandler(err, res, cb); + cb = callback = null; + } + function handleValidationError(msg){ + var err = 'Event not recorded: ' + msg; + self.trigger('error', err); + if (cb) { + cb.call(self, err, null); + cb = callback = null; + } + } + return; +}; +function prepareGetRequest(url, data){ + url += getQueryString({ + api_key : this.writeKey(), + data : base64.encode( JSON2.stringify(data) ), + modified : new Date().getTime() + }); + return ( url.length < getUrlMaxLength() ) ? url : false; +} +},{"../helpers/get-context":11,"../helpers/get-query-string":12,"../helpers/get-url-max-length":13,"../helpers/get-xhr-object":14,"../helpers/superagent-handle-response":15,"../helpers/superagent-request-types":16,"../index":17,"../utils/base64":22,"../utils/each":23,"JSON2":2,"superagent":6}],19:[function(require,module,exports){ +var Keen = require('../index'); +var request = require('superagent'); +var each = require('../utils/each'), + getContext = require('../helpers/get-context'), + getXHR = require('../helpers/get-xhr-object'), + requestTypes = require('../helpers/superagent-request-types'), + responseHandler = require('../helpers/superagent-handle-response'); +module.exports = function(payload, callback) { + var self = this, + urlBase = this.url('/events'), + data = {}, + cb = callback; + if (!Keen.enabled) { + handleValidationError.call(self, 'Keen.enabled = false'); + return; + } + if (!self.projectId()) { + handleValidationError.call(self, 'Missing projectId property'); + return; + } + if (!self.writeKey()) { + handleValidationError.call(self, 'Missing writeKey property'); + return; + } + if (arguments.length > 2) { + handleValidationError.call(self, 'Incorrect arguments provided to #addEvents method'); + return; + } + if (typeof payload !== 'object' || payload instanceof Array) { + handleValidationError.call(self, 'Request payload must be an object'); + return; + } + if (self.config.globalProperties) { + each(payload, function(events, collection){ + each(events, function(body, index){ + var base = self.config.globalProperties(collection); + each(body, function(value, key){ + base[key] = value; + }); + data[collection].push(base); + }); + }); + } + else { + data = payload; + } + if ( getXHR() || getContext() === 'server' ) { + request + .post(urlBase) + .set('Content-Type', 'application/json') + .set('Authorization', self.writeKey()) + .send(data) + .end(function(err, res){ + responseHandler(err, res, cb); + cb = callback = null; + }); + } + else { + self.trigger('error', 'Events not recorded: XHR support is required for batch upload'); + } + function handleValidationError(msg){ + var err = 'Events not recorded: ' + msg; + self.trigger('error', err); + if (cb) { + cb.call(self, err, null); + cb = callback = null; + } + } + return; +}; +},{"../helpers/get-context":11,"../helpers/get-xhr-object":14,"../helpers/superagent-handle-response":15,"../helpers/superagent-request-types":16,"../index":17,"../utils/each":23,"superagent":6}],20:[function(require,module,exports){ +module.exports = function(newGlobalProperties) { + if (newGlobalProperties && typeof(newGlobalProperties) == "function") { + this.config.globalProperties = newGlobalProperties; + } else { + this.trigger("error", "Invalid value for global properties: " + newGlobalProperties); + } +}; +},{}],21:[function(require,module,exports){ +var addEvent = require("./addEvent"); +module.exports = function(jsEvent, eventCollection, payload, timeout, timeoutCallback){ + var evt = jsEvent, + target = (evt.currentTarget) ? evt.currentTarget : (evt.srcElement || evt.target), + timer = timeout || 500, + triggered = false, + targetAttr = "", + callback, + win; + if (target.getAttribute !== void 0) { + targetAttr = target.getAttribute("target"); + } else if (target.target) { + targetAttr = target.target; + } + if ((targetAttr == "_blank" || targetAttr == "blank") && !evt.metaKey) { + win = window.open("about:blank"); + win.document.location = target.href; + } + if (target.nodeName === "A") { + callback = function(){ + if(!triggered && !evt.metaKey && (targetAttr !== "_blank" && targetAttr !== "blank")){ + triggered = true; + window.location = target.href; + } + }; + } else if (target.nodeName === "FORM") { + callback = function(){ + if(!triggered){ + triggered = true; + target.submit(); + } + }; + } else { + this.trigger("error", "#trackExternalLink method not attached to an or
DOM element"); + } + if (timeoutCallback) { + callback = function(){ + if(!triggered){ + triggered = true; + timeoutCallback(); + } + }; + } + addEvent.call(this, eventCollection, payload, callback); + setTimeout(callback, timer); + if (!evt.metaKey) { + return false; + } +}; +},{"./addEvent":18}],22:[function(require,module,exports){ +module.exports = { + map: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=", + encode: function (n) { + "use strict"; + var o = "", i = 0, m = this.map, i1, i2, i3, e1, e2, e3, e4; + n = this.utf8.encode(n); + while (i < n.length) { + i1 = n.charCodeAt(i++); i2 = n.charCodeAt(i++); i3 = n.charCodeAt(i++); + e1 = (i1 >> 2); e2 = (((i1 & 3) << 4) | (i2 >> 4)); e3 = (isNaN(i2) ? 64 : ((i2 & 15) << 2) | (i3 >> 6)); + e4 = (isNaN(i2) || isNaN(i3)) ? 64 : i3 & 63; + o = o + m.charAt(e1) + m.charAt(e2) + m.charAt(e3) + m.charAt(e4); + } return o; + }, + decode: function (n) { + "use strict"; + var o = "", i = 0, m = this.map, cc = String.fromCharCode, e1, e2, e3, e4, c1, c2, c3; + n = n.replace(/[^A-Za-z0-9\+\/\=]/g, ""); + while (i < n.length) { + e1 = m.indexOf(n.charAt(i++)); e2 = m.indexOf(n.charAt(i++)); + e3 = m.indexOf(n.charAt(i++)); e4 = m.indexOf(n.charAt(i++)); + c1 = (e1 << 2) | (e2 >> 4); c2 = ((e2 & 15) << 4) | (e3 >> 2); + c3 = ((e3 & 3) << 6) | e4; + o = o + (cc(c1) + ((e3 != 64) ? cc(c2) : "")) + (((e4 != 64) ? cc(c3) : "")); + } return this.utf8.decode(o); + }, + utf8: { + encode: function (n) { + "use strict"; + var o = "", i = 0, cc = String.fromCharCode, c; + while (i < n.length) { + c = n.charCodeAt(i++); o = o + ((c < 128) ? cc(c) : ((c > 127) && (c < 2048)) ? + (cc((c >> 6) | 192) + cc((c & 63) | 128)) : (cc((c >> 12) | 224) + cc(((c >> 6) & 63) | 128) + cc((c & 63) | 128))); + } return o; + }, + decode: function (n) { + "use strict"; + var o = "", i = 0, cc = String.fromCharCode, c2, c; + while (i < n.length) { + c = n.charCodeAt(i); + o = o + ((c < 128) ? [cc(c), i++][0] : ((c > 191) && (c < 224)) ? + [cc(((c & 31) << 6) | ((c2 = n.charCodeAt(i + 1)) & 63)), (i += 2)][0] : + [cc(((c & 15) << 12) | (((c2 = n.charCodeAt(i + 1)) & 63) << 6) | ((c3 = n.charCodeAt(i + 2)) & 63)), (i += 3)][0]); + } return o; + } + } +}; +},{}],23:[function(require,module,exports){ +module.exports = function(o, cb, s){ + var n; + if (!o){ + return 0; + } + s = !s ? o : s; + if (o instanceof Array){ + for (n=0; n0){return 2000}}return 16000}},{}],14:[function(b,c,a){c.exports=function(){var d="undefined"==typeof window?this:window;if(d.XMLHttpRequest&&("file:"!=d.location.protocol||!d.ActiveXObject)){return new XMLHttpRequest}else{try{return new ActiveXObject("Microsoft.XMLHTTP")}catch(f){}try{return new ActiveXObject("Msxml2.XMLHTTP.6.0")}catch(f){}try{return new ActiveXObject("Msxml2.XMLHTTP.3.0")}catch(f){}try{return new ActiveXObject("Msxml2.XMLHTTP")}catch(f){}}return false}},{}],15:[function(b,c,a){c.exports=function(h,g,i){var f=i||function(){};if(g&&!g.ok){var d=g.body&&g.body.error_code;h=new Error(d?g.body.message:"Unknown error occurred");h.code=d?g.body.error_code:"UnknownError"}if(h){f(h,null)}else{f(null,g.body)}return}},{}],16:[function(f,b,g){var n=f("superagent");var l=f("../utils/each"),a=f("./get-xhr-object");b.exports=function(o,p){return function(q){var r=q.constructor.prototype.end;if("undefined"===typeof window){return}q.requestType=q.requestType||{};q.requestType.type=o;q.requestType.options=q.requestType.options||{async:true,success:{responseText:'{ "created": true }',status:201},error:{responseText:'{ "error_code": "ERROR", "message": "Request failed" }',status:404}};if(p){if("boolean"===typeof p.async){q.requestType.options.async=p.async}if(p.success){extend(q.requestType.options.success,p.success)}if(p.error){extend(q.requestType.options.error,p.error)}}q.end=function(u){var t=this,s=(this.requestType)?this.requestType.type:"xhr",w,v;if(("GET"!==t.method||"xhr"===s)&&t.requestType.options.async){r.call(t,u);return}w=t._query.join("&");v=t._timeout;t._callback=u||noop;if(v&&!t._timer){t._timer=setTimeout(function(){h.call(t)},v)}if(w){w=n.serializeObject(w);t.url+=~t.url.indexOf("?")?"&"+w:"?"+w}t.emit("request",t);if(!t.requestType.options.async){k.call(t)}else{if("jsonp"===s){j.call(t)}else{if("beacon"===s){i.call(t)}}}return t};return q}};function k(){var o=a();if(o){o.open("GET",this.url,false);o.send(null)}return this}function j(){var p=this,t=new Date().getTime(),o=document.createElement("script"),s=document.getElementsByTagName("head")[0],u="keenJSONPCallback",q=false;u+=t;while(u in window){u+="a"}window[u]=function(v){if(q===true){return}q=true;d.call(p,v);r()};o.src=p.url+"&jsonp="+u;s.appendChild(o);o.onreadystatechange=function(){if(q===false&&p.readyState==="loaded"){q=true;c.call(p);r()}};o.onerror=function(){if(q===false){q=true;c.call(p);r()}};function r(){window[u]=undefined;try{delete window[u]}catch(v){}s.removeChild(o)}}function i(){var p=this,o=document.createElement("img"),q=false;o.onload=function(){q=true;if("naturalHeight" in this){if(this.naturalHeight+this.naturalWidth===0){this.onerror();return}}else{if(this.width+this.height===0){this.onerror();return}}d.call(p)};o.onerror=function(){q=true;c.call(p)};o.src=p.url+"&c=clv1"}function d(p){var q=this.requestType.options["success"],o="";m.call(this,q);if(p){try{o=JSON.stringify(p)}catch(r){}}else{o=q.responseText}this.xhr.responseText=o;this.xhr.status=q.status;this.emit("end")}function c(){var o=this.requestType.options["error"];m.call(this,o);this.xhr.responseText=o.responseText;this.xhr.status=o.status;this.emit("end")}function h(){this.aborted=true;this.clearTimeout();this.emit("abort")}function m(o){this.xhr={getAllResponseHeaders:function(){return""},getResponseHeader:function(){return"application/json"},responseText:o.responseText,status:o.status};return this}},{"../utils/each":23,"./get-xhr-object":14,superagent:6}],17:[function(d,f,c){var b="undefined"!==typeof window?window:this;var h=b.Keen;var g=d("./helpers/emitter-shim");function a(i){this.configure(i||{});a.trigger("client",this)}a.debug=false;a.enabled=true;a.loaded=true;a.version="3.2.6";g(a);g(a.prototype);a.prototype.configure=function(i){var j=i||{};if(j.host){j.host.replace(/.*?:\/\//g,"")}if(j.protocol&&j.protocol==="auto"){j.protocol=location.protocol.replace(/:/g,"")}this.config={projectId:j.projectId,writeKey:j.writeKey,readKey:j.readKey,masterKey:j.masterKey,requestType:j.requestType||"jsonp",host:j.host||"api.keen.io/3.0",protocol:j.protocol||"https",globalProperties:null};if(a.debug){this.on("error",a.log)}this.trigger("ready")};a.prototype.projectId=function(i){if(!arguments.length){return this.config.projectId}this.config.projectId=(i?String(i):null);return this};a.prototype.masterKey=function(i){if(!arguments.length){return this.config.masterKey}this.config.masterKey=(i?String(i):null);return this};a.prototype.readKey=function(i){if(!arguments.length){return this.config.readKey}this.config.readKey=(i?String(i):null);return this};a.prototype.writeKey=function(i){if(!arguments.length){return this.config.writeKey}this.config.writeKey=(i?String(i):null);return this};a.prototype.url=function(i){if(!this.projectId()){this.trigger("error","Client is missing projectId property");return}return this.config.protocol+"://"+this.config.host+"/projects/"+this.projectId()+i};a.log=function(i){if(a.debug&&typeof console=="object"){console.log("[Keen IO]",i)}};a.noConflict=function(){b.Keen=h;return a};a.ready=function(i){if(a.loaded){i()}else{a.once("ready",i)}};f.exports=a},{"./helpers/emitter-shim":10}],18:[function(f,c,h){var n=f("JSON2");var g=f("superagent");var i=f("../index");var j=f("../utils/base64"),m=f("../utils/each"),o=f("../helpers/get-context"),d=f("../helpers/get-query-string"),b=f("../helpers/get-url-max-length"),a=f("../helpers/get-xhr-object"),k=f("../helpers/superagent-request-types"),p=f("../helpers/superagent-handle-response");c.exports=function(x,A,B,t){var C=this,v=this.url("/events/"+encodeURIComponent(x)),q=this.config.requestType,u={},s=B,r,z;r=("boolean"===typeof t)?t:true;if(!i.enabled){y.call(C,"Keen.enabled = false");return}if(!C.projectId()){y.call(C,"Missing projectId property");return}if(!C.writeKey()){y.call(C,"Missing writeKey property");return}if(!x||typeof x!=="string"){y.call(C,"Collection name must be a string");return}if(C.config.globalProperties){u=C.config.globalProperties(x)}m(A,function(E,D){u[D]=E});if(!a()&&"xhr"===q){q="jsonp"}if("xhr"!==q||!r){z=l.call(C,v,u)}if(z&&o()==="browser"){g.get(z).use(k(q,{async:r})).end(w)}else{if(a()||o()==="server"){g.post(v).set("Content-Type","application/json").set("Authorization",C.writeKey()).send(u).end(w)}else{C.trigger("error","Request not sent: URL length exceeds current browser limit, and XHR (POST) is not supported.")}}function w(E,D){p(E,D,s);s=B=null}function y(E){var D="Event not recorded: "+E;C.trigger("error",D);if(s){s.call(C,D,null);s=B=null}}return};function l(q,r){q+=d({api_key:this.writeKey(),data:j.encode(n.stringify(r)),modified:new Date().getTime()});return(q.length2){q.call(n,"Incorrect arguments provided to #addEvents method");return}if(typeof p!=="object"||p instanceof Array){q.call(n,"Request payload must be an object");return}if(n.config.globalProperties){i(p,function(s,t){i(s,function(u,v){var w=n.config.globalProperties(t);i(u,function(y,x){w[x]=y});o[t].push(w)})})}else{o=p}if(a()||j()==="server"){d.post(m).set("Content-Type","application/json").set("Authorization",n.writeKey()).send(o).end(function(t,s){k(t,s,l);l=r=null})}else{n.trigger("error","Events not recorded: XHR support is required for batch upload")}function q(t){var s="Events not recorded: "+t;n.trigger("error",s);if(l){l.call(n,s,null);l=r=null}}return}},{"../helpers/get-context":11,"../helpers/get-xhr-object":14,"../helpers/superagent-handle-response":15,"../helpers/superagent-request-types":16,"../index":17,"../utils/each":23,superagent:6}],20:[function(b,c,a){c.exports=function(d){if(d&&typeof(d)=="function"){this.config.globalProperties=d}else{this.trigger("error","Invalid value for global properties: "+d)}}},{}],21:[function(b,c,a){var d=b("./addEvent");c.exports=function(k,f,n,l,m){var o=k,j=(o.currentTarget)?o.currentTarget:(o.srcElement||o.target),g=l||500,h=false,q="",p,i;if(j.getAttribute!==void 0){q=j.getAttribute("target")}else{if(j.target){q=j.target}}if((q=="_blank"||q=="blank")&&!o.metaKey){i=window.open("about:blank");i.document.location=j.href}if(j.nodeName==="A"){p=function(){if(!h&&!o.metaKey&&(q!=="_blank"&&q!=="blank")){h=true;window.location=j.href}}}else{if(j.nodeName==="FORM"){p=function(){if(!h){h=true;j.submit()}}}else{this.trigger("error","#trackExternalLink method not attached to an or DOM element")}}if(m){p=function(){if(!h){h=true;m()}}}d.call(this,f,n,p);setTimeout(p,g);if(!o.metaKey){return false}}},{"./addEvent":18}],22:[function(b,c,a){c.exports={map:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",encode:function(f){var d="",l=0,h=this.map,k,j,g,s,r,q,p;f=this.utf8.encode(f);while(l>2);r=(((k&3)<<4)|(j>>4));q=(isNaN(j)?64:((j&15)<<2)|(g>>6));p=(isNaN(j)||isNaN(g))?64:g&63;d=d+h.charAt(s)+h.charAt(r)+h.charAt(q)+h.charAt(p)}return d},decode:function(f){var d="",p=0,h=this.map,g=String.fromCharCode,t,s,r,q,l,k,j;f=f.replace(/[^A-Za-z0-9\+\/\=]/g,"");while(p>4);k=((s&15)<<4)|(r>>2);j=((r&3)<<6)|q;d=d+(g(l)+((r!=64)?g(k):""))+(((q!=64)?g(j):""))}return this.utf8.decode(d)},utf8:{encode:function(j){var f="",d=0,h=String.fromCharCode,g;while(d127)&&(g<2048))?(h((g>>6)|192)+h((g&63)|128)):(h((g>>12)|224)+h(((g>>6)&63)|128)+h((g&63)|128)))}return f},decode:function(k){var g="",f=0,j=String.fromCharCode,d,h;while(f191)&&(h<224))?[j(((h&31)<<6)|((d=k.charCodeAt(f+1))&63)),(f+=2)][0]:[j(((h&15)<<12)|(((d=k.charCodeAt(f+1))&63)<<6)|((c3=k.charCodeAt(f+2))&63)),(f+=3)][0])}return g}}}},{}],23:[function(b,c,a){c.exports=function(g,d,f){var h;if(!g){return 0}f=!f?g:f;if(g instanceof Array){for(h=0;h> 1) + 'px' + }) + } + for (; i < o.lines; i++) { + seg = css(createEl(), { + position: 'absolute' + , top: 1 + ~(o.scale * o.width / 2) + 'px' + , transform: o.hwaccel ? 'translate3d(0,0,0)' : '' + , opacity: o.opacity + , animation: useCssAnimations && addAnimation(o.opacity, o.trail, start + i * o.direction, o.lines) + ' ' + 1 / o.speed + 's linear infinite' + }) + if (o.shadow) ins(seg, css(fill('#000', '0 0 4px #000'), {top: '2px'})) + ins(el, ins(seg, fill(getColor(o.color, i), '0 0 1px rgba(0,0,0,.1)'))) + } + return el + } + /** + * Internal method that adjusts the opacity of a single line. + * Will be overwritten in VML fallback mode below. + */ + , opacity: function (el, i, val) { + if (i < el.childNodes.length) el.childNodes[i].style.opacity = val + } + }) + function initVML () { + /* Utility function to create a VML tag */ + function vml (tag, attr) { + return createEl('<' + tag + ' xmlns="urn:schemas-microsoft.com:vml" class="spin-vml">', attr) + } + sheet.addRule('.spin-vml', 'behavior:url(#default#VML)') + Spinner.prototype.lines = function (el, o) { + var r = o.scale * (o.length + o.width) + , s = o.scale * 2 * r + function grp () { + return css( + vml('group', { + coordsize: s + ' ' + s + , coordorigin: -r + ' ' + -r + }) + , { width: s, height: s } + ) + } + var margin = -(o.width + o.length) * o.scale * 2 + 'px' + , g = css(grp(), {position: 'absolute', top: margin, left: margin}) + , i + function seg (i, dx, filter) { + ins( + g + , ins( + css(grp(), {rotation: 360 / o.lines * i + 'deg', left: ~~dx}) + , ins( + css( + vml('roundrect', {arcsize: o.corners}) + , { width: r + , height: o.scale * o.width + , left: o.scale * o.radius + , top: -o.scale * o.width >> 1 + , filter: filter + } + ) + , vml('fill', {color: getColor(o.color, i), opacity: o.opacity}) + , vml('stroke', {opacity: 0}) + ) + ) + ) + } + if (o.shadow) + for (i = 1; i <= o.lines; i++) { + seg(i, -2, 'progid:DXImageTransform.Microsoft.Blur(pixelradius=2,makeshadow=1,shadowopacity=.3)') + } + for (i = 1; i <= o.lines; i++) seg(i) + return ins(el, g) + } + Spinner.prototype.opacity = function (el, i, val, o) { + var c = el.firstChild + o = o.shadow && o.lines || 0 + if (c && i + o < c.childNodes.length) { + c = c.childNodes[i + o]; c = c && c.firstChild; c = c && c.firstChild + if (c) c.opacity = val + } + } + } + if (typeof document !== 'undefined') { + sheet = (function () { + var el = createEl('style', {type : 'text/css'}) + ins(document.getElementsByTagName('head')[0], el) + return el.sheet || el.styleSheet + }()) + var probe = css(createEl('group'), {behavior: 'url(#default#VML)'}) + if (!vendor(probe, 'transform') && probe.adj) initVML() + else useCssAnimations = vendor(probe, 'animation') + } + return Spinner +})); +},{}],7:[function(require,module,exports){ +/** + * Module dependencies. + */ +var Emitter = require('emitter'); +var reduce = require('reduce'); +/** + * Root reference for iframes. + */ +var root = 'undefined' == typeof window + ? this + : window; +/** + * Noop. + */ +function noop(){}; +/** + * Check if `obj` is a host object, + * we don't want to serialize these :) + * + * TODO: future proof, move to compoent land + * + * @param {Object} obj + * @return {Boolean} + * @api private + */ +function isHost(obj) { + var str = {}.toString.call(obj); + switch (str) { + case '[object File]': + case '[object Blob]': + case '[object FormData]': + return true; + default: + return false; + } +} +/** + * Determine XHR. + */ +function getXHR() { + if (root.XMLHttpRequest + && ('file:' != root.location.protocol || !root.ActiveXObject)) { + return new XMLHttpRequest; + } else { + try { return new ActiveXObject('Microsoft.XMLHTTP'); } catch(e) {} + try { return new ActiveXObject('Msxml2.XMLHTTP.6.0'); } catch(e) {} + try { return new ActiveXObject('Msxml2.XMLHTTP.3.0'); } catch(e) {} + try { return new ActiveXObject('Msxml2.XMLHTTP'); } catch(e) {} + } + return false; +} +/** + * Removes leading and trailing whitespace, added to support IE. + * + * @param {String} s + * @return {String} + * @api private + */ +var trim = ''.trim + ? function(s) { return s.trim(); } + : function(s) { return s.replace(/(^\s*|\s*$)/g, ''); }; +/** + * Check if `obj` is an object. + * + * @param {Object} obj + * @return {Boolean} + * @api private + */ +function isObject(obj) { + return obj === Object(obj); +} +/** + * Serialize the given `obj`. + * + * @param {Object} obj + * @return {String} + * @api private + */ +function serialize(obj) { + if (!isObject(obj)) return obj; + var pairs = []; + for (var key in obj) { + if (null != obj[key]) { + pairs.push(encodeURIComponent(key) + + '=' + encodeURIComponent(obj[key])); + } + } + return pairs.join('&'); +} +/** + * Expose serialization method. + */ + request.serializeObject = serialize; + /** + * Parse the given x-www-form-urlencoded `str`. + * + * @param {String} str + * @return {Object} + * @api private + */ +function parseString(str) { + var obj = {}; + var pairs = str.split('&'); + var parts; + var pair; + for (var i = 0, len = pairs.length; i < len; ++i) { + pair = pairs[i]; + parts = pair.split('='); + obj[decodeURIComponent(parts[0])] = decodeURIComponent(parts[1]); + } + return obj; +} +/** + * Expose parser. + */ +request.parseString = parseString; +/** + * Default MIME type map. + * + * superagent.types.xml = 'application/xml'; + * + */ +request.types = { + html: 'text/html', + json: 'application/json', + xml: 'application/xml', + urlencoded: 'application/x-www-form-urlencoded', + 'form': 'application/x-www-form-urlencoded', + 'form-data': 'application/x-www-form-urlencoded' +}; +/** + * Default serialization map. + * + * superagent.serialize['application/xml'] = function(obj){ + * return 'generated xml here'; + * }; + * + */ + request.serialize = { + 'application/x-www-form-urlencoded': serialize, + 'application/json': JSON.stringify + }; + /** + * Default parsers. + * + * superagent.parse['application/xml'] = function(str){ + * return { object parsed from str }; + * }; + * + */ +request.parse = { + 'application/x-www-form-urlencoded': parseString, + 'application/json': JSON.parse +}; +/** + * Parse the given header `str` into + * an object containing the mapped fields. + * + * @param {String} str + * @return {Object} + * @api private + */ +function parseHeader(str) { + var lines = str.split(/\r?\n/); + var fields = {}; + var index; + var line; + var field; + var val; + lines.pop(); + for (var i = 0, len = lines.length; i < len; ++i) { + line = lines[i]; + index = line.indexOf(':'); + field = line.slice(0, index).toLowerCase(); + val = trim(line.slice(index + 1)); + fields[field] = val; + } + return fields; +} +/** + * Return the mime type for the given `str`. + * + * @param {String} str + * @return {String} + * @api private + */ +function type(str){ + return str.split(/ *; */).shift(); +}; +/** + * Return header field parameters. + * + * @param {String} str + * @return {Object} + * @api private + */ +function params(str){ + return reduce(str.split(/ *; */), function(obj, str){ + var parts = str.split(/ *= */) + , key = parts.shift() + , val = parts.shift(); + if (key && val) obj[key] = val; + return obj; + }, {}); +}; +/** + * Initialize a new `Response` with the given `xhr`. + * + * - set flags (.ok, .error, etc) + * - parse header + * + * Examples: + * + * Aliasing `superagent` as `request` is nice: + * + * request = superagent; + * + * We can use the promise-like API, or pass callbacks: + * + * request.get('/').end(function(res){}); + * request.get('/', function(res){}); + * + * Sending data can be chained: + * + * request + * .post('/user') + * .send({ name: 'tj' }) + * .end(function(res){}); + * + * Or passed to `.send()`: + * + * request + * .post('/user') + * .send({ name: 'tj' }, function(res){}); + * + * Or passed to `.post()`: + * + * request + * .post('/user', { name: 'tj' }) + * .end(function(res){}); + * + * Or further reduced to a single call for simple cases: + * + * request + * .post('/user', { name: 'tj' }, function(res){}); + * + * @param {XMLHTTPRequest} xhr + * @param {Object} options + * @api private + */ +function Response(req, options) { + options = options || {}; + this.req = req; + this.xhr = this.req.xhr; + this.text = this.req.method !='HEAD' + ? this.xhr.responseText + : null; + this.setStatusProperties(this.xhr.status); + this.header = this.headers = parseHeader(this.xhr.getAllResponseHeaders()); + this.header['content-type'] = this.xhr.getResponseHeader('content-type'); + this.setHeaderProperties(this.header); + this.body = this.req.method != 'HEAD' + ? this.parseBody(this.text) + : null; +} +/** + * Get case-insensitive `field` value. + * + * @param {String} field + * @return {String} + * @api public + */ +Response.prototype.get = function(field){ + return this.header[field.toLowerCase()]; +}; +/** + * Set header related properties: + * + * - `.type` the content type without params + * + * A response of "Content-Type: text/plain; charset=utf-8" + * will provide you with a `.type` of "text/plain". + * + * @param {Object} header + * @api private + */ +Response.prototype.setHeaderProperties = function(header){ + var ct = this.header['content-type'] || ''; + this.type = type(ct); + var obj = params(ct); + for (var key in obj) this[key] = obj[key]; +}; +/** + * Parse the given body `str`. + * + * Used for auto-parsing of bodies. Parsers + * are defined on the `superagent.parse` object. + * + * @param {String} str + * @return {Mixed} + * @api private + */ +Response.prototype.parseBody = function(str){ + var parse = request.parse[this.type]; + return parse && str && str.length + ? parse(str) + : null; +}; +/** + * Set flags such as `.ok` based on `status`. + * + * For example a 2xx response will give you a `.ok` of __true__ + * whereas 5xx will be __false__ and `.error` will be __true__. The + * `.clientError` and `.serverError` are also available to be more + * specific, and `.statusType` is the class of error ranging from 1..5 + * sometimes useful for mapping respond colors etc. + * + * "sugar" properties are also defined for common cases. Currently providing: + * + * - .noContent + * - .badRequest + * - .unauthorized + * - .notAcceptable + * - .notFound + * + * @param {Number} status + * @api private + */ +Response.prototype.setStatusProperties = function(status){ + var type = status / 100 | 0; + this.status = status; + this.statusType = type; + this.info = 1 == type; + this.ok = 2 == type; + this.clientError = 4 == type; + this.serverError = 5 == type; + this.error = (4 == type || 5 == type) + ? this.toError() + : false; + this.accepted = 202 == status; + this.noContent = 204 == status || 1223 == status; + this.badRequest = 400 == status; + this.unauthorized = 401 == status; + this.notAcceptable = 406 == status; + this.notFound = 404 == status; + this.forbidden = 403 == status; +}; +/** + * Return an `Error` representative of this response. + * + * @return {Error} + * @api public + */ +Response.prototype.toError = function(){ + var req = this.req; + var method = req.method; + var url = req.url; + var msg = 'cannot ' + method + ' ' + url + ' (' + this.status + ')'; + var err = new Error(msg); + err.status = this.status; + err.method = method; + err.url = url; + return err; +}; +/** + * Expose `Response`. + */ +request.Response = Response; +/** + * Initialize a new `Request` with the given `method` and `url`. + * + * @param {String} method + * @param {String} url + * @api public + */ +function Request(method, url) { + var self = this; + Emitter.call(this); + this._query = this._query || []; + this.method = method; + this.url = url; + this.header = {}; + this._header = {}; + this.on('end', function(){ + var err = null; + var res = null; + try { + res = new Response(self); + } catch(e) { + err = new Error('Parser is unable to parse the response'); + err.parse = true; + err.original = e; + } + self.callback(err, res); + }); +} +/** + * Mixin `Emitter`. + */ +Emitter(Request.prototype); +/** + * Allow for extension + */ +Request.prototype.use = function(fn) { + fn(this); + return this; +} +/** + * Set timeout to `ms`. + * + * @param {Number} ms + * @return {Request} for chaining + * @api public + */ +Request.prototype.timeout = function(ms){ + this._timeout = ms; + return this; +}; +/** + * Clear previous timeout. + * + * @return {Request} for chaining + * @api public + */ +Request.prototype.clearTimeout = function(){ + this._timeout = 0; + clearTimeout(this._timer); + return this; +}; +/** + * Abort the request, and clear potential timeout. + * + * @return {Request} + * @api public + */ +Request.prototype.abort = function(){ + if (this.aborted) return; + this.aborted = true; + this.xhr.abort(); + this.clearTimeout(); + this.emit('abort'); + return this; +}; +/** + * Set header `field` to `val`, or multiple fields with one object. + * + * Examples: + * + * req.get('/') + * .set('Accept', 'application/json') + * .set('X-API-Key', 'foobar') + * .end(callback); + * + * req.get('/') + * .set({ Accept: 'application/json', 'X-API-Key': 'foobar' }) + * .end(callback); + * + * @param {String|Object} field + * @param {String} val + * @return {Request} for chaining + * @api public + */ +Request.prototype.set = function(field, val){ + if (isObject(field)) { + for (var key in field) { + this.set(key, field[key]); + } + return this; + } + this._header[field.toLowerCase()] = val; + this.header[field] = val; + return this; +}; +/** + * Remove header `field`. + * + * Example: + * + * req.get('/') + * .unset('User-Agent') + * .end(callback); + * + * @param {String} field + * @return {Request} for chaining + * @api public + */ +Request.prototype.unset = function(field){ + delete this._header[field.toLowerCase()]; + delete this.header[field]; + return this; +}; +/** + * Get case-insensitive header `field` value. + * + * @param {String} field + * @return {String} + * @api private + */ +Request.prototype.getHeader = function(field){ + return this._header[field.toLowerCase()]; +}; +/** + * Set Content-Type to `type`, mapping values from `request.types`. + * + * Examples: + * + * superagent.types.xml = 'application/xml'; + * + * request.post('/') + * .type('xml') + * .send(xmlstring) + * .end(callback); + * + * request.post('/') + * .type('application/xml') + * .send(xmlstring) + * .end(callback); + * + * @param {String} type + * @return {Request} for chaining + * @api public + */ +Request.prototype.type = function(type){ + this.set('Content-Type', request.types[type] || type); + return this; +}; +/** + * Set Accept to `type`, mapping values from `request.types`. + * + * Examples: + * + * superagent.types.json = 'application/json'; + * + * request.get('/agent') + * .accept('json') + * .end(callback); + * + * request.get('/agent') + * .accept('application/json') + * .end(callback); + * + * @param {String} accept + * @return {Request} for chaining + * @api public + */ +Request.prototype.accept = function(type){ + this.set('Accept', request.types[type] || type); + return this; +}; +/** + * Set Authorization field value with `user` and `pass`. + * + * @param {String} user + * @param {String} pass + * @return {Request} for chaining + * @api public + */ +Request.prototype.auth = function(user, pass){ + var str = btoa(user + ':' + pass); + this.set('Authorization', 'Basic ' + str); + return this; +}; +/** +* Add query-string `val`. +* +* Examples: +* +* request.get('/shoes') +* .query('size=10') +* .query({ color: 'blue' }) +* +* @param {Object|String} val +* @return {Request} for chaining +* @api public +*/ +Request.prototype.query = function(val){ + if ('string' != typeof val) val = serialize(val); + if (val) this._query.push(val); + return this; +}; +/** + * Write the field `name` and `val` for "multipart/form-data" + * request bodies. + * + * ``` js + * request.post('/upload') + * .field('foo', 'bar') + * .end(callback); + * ``` + * + * @param {String} name + * @param {String|Blob|File} val + * @return {Request} for chaining + * @api public + */ +Request.prototype.field = function(name, val){ + if (!this._formData) this._formData = new FormData(); + this._formData.append(name, val); + return this; +}; +/** + * Queue the given `file` as an attachment to the specified `field`, + * with optional `filename`. + * + * ``` js + * request.post('/upload') + * .attach(new Blob(['hey!'], { type: "text/html"})) + * .end(callback); + * ``` + * + * @param {String} field + * @param {Blob|File} file + * @param {String} filename + * @return {Request} for chaining + * @api public + */ +Request.prototype.attach = function(field, file, filename){ + if (!this._formData) this._formData = new FormData(); + this._formData.append(field, file, filename); + return this; +}; +/** + * Send `data`, defaulting the `.type()` to "json" when + * an object is given. + * + * Examples: + * + * + * request.get('/search') + * .end(callback) + * + * + * request.get('/search') + * .send({ search: 'query' }) + * .send({ range: '1..5' }) + * .send({ order: 'desc' }) + * .end(callback) + * + * + * request.post('/user') + * .type('json') + * .send('{"name":"tj"}) + * .end(callback) + * + * + * request.post('/user') + * .send({ name: 'tj' }) + * .end(callback) + * + * + * request.post('/user') + * .type('form') + * .send('name=tj') + * .end(callback) + * + * + * request.post('/user') + * .type('form') + * .send({ name: 'tj' }) + * .end(callback) + * + * + * request.post('/user') + * .send('name=tobi') + * .send('species=ferret') + * .end(callback) + * + * @param {String|Object} data + * @return {Request} for chaining + * @api public + */ +Request.prototype.send = function(data){ + var obj = isObject(data); + var type = this.getHeader('Content-Type'); + if (obj && isObject(this._data)) { + for (var key in data) { + this._data[key] = data[key]; + } + } else if ('string' == typeof data) { + if (!type) this.type('form'); + type = this.getHeader('Content-Type'); + if ('application/x-www-form-urlencoded' == type) { + this._data = this._data + ? this._data + '&' + data + : data; + } else { + this._data = (this._data || '') + data; + } + } else { + this._data = data; + } + if (!obj) return this; + if (!type) this.type('json'); + return this; +}; +/** + * Invoke the callback with `err` and `res` + * and handle arity check. + * + * @param {Error} err + * @param {Response} res + * @api private + */ +Request.prototype.callback = function(err, res){ + var fn = this._callback; + this.clearTimeout(); + if (2 == fn.length) return fn(err, res); + if (err) return this.emit('error', err); + fn(res); +}; +/** + * Invoke callback with x-domain error. + * + * @api private + */ +Request.prototype.crossDomainError = function(){ + var err = new Error('Origin is not allowed by Access-Control-Allow-Origin'); + err.crossDomain = true; + this.callback(err); +}; +/** + * Invoke callback with timeout error. + * + * @api private + */ +Request.prototype.timeoutError = function(){ + var timeout = this._timeout; + var err = new Error('timeout of ' + timeout + 'ms exceeded'); + err.timeout = timeout; + this.callback(err); +}; +/** + * Enable transmission of cookies with x-domain requests. + * + * Note that for this to work the origin must not be + * using "Access-Control-Allow-Origin" with a wildcard, + * and also must set "Access-Control-Allow-Credentials" + * to "true". + * + * @api public + */ +Request.prototype.withCredentials = function(){ + this._withCredentials = true; + return this; +}; +/** + * Initiate request, invoking callback `fn(res)` + * with an instanceof `Response`. + * + * @param {Function} fn + * @return {Request} for chaining + * @api public + */ +Request.prototype.end = function(fn){ + var self = this; + var xhr = this.xhr = getXHR(); + var query = this._query.join('&'); + var timeout = this._timeout; + var data = this._formData || this._data; + this._callback = fn || noop; + xhr.onreadystatechange = function(){ + if (4 != xhr.readyState) return; + if (0 == xhr.status) { + if (self.aborted) return self.timeoutError(); + return self.crossDomainError(); + } + self.emit('end'); + }; + if (xhr.upload) { + xhr.upload.onprogress = function(e){ + e.percent = e.loaded / e.total * 100; + self.emit('progress', e); + }; + } + if (timeout && !this._timer) { + this._timer = setTimeout(function(){ + self.abort(); + }, timeout); + } + if (query) { + query = request.serializeObject(query); + this.url += ~this.url.indexOf('?') + ? '&' + query + : '?' + query; + } + xhr.open(this.method, this.url, true); + if (this._withCredentials) xhr.withCredentials = true; + if ('GET' != this.method && 'HEAD' != this.method && 'string' != typeof data && !isHost(data)) { + var serialize = request.serialize[this.getHeader('Content-Type')]; + if (serialize) data = serialize(data); + } + for (var field in this.header) { + if (null == this.header[field]) continue; + xhr.setRequestHeader(field, this.header[field]); + } + this.emit('request', this); + xhr.send(data); + return this; +}; +/** + * Expose `Request`. + */ +request.Request = Request; +/** + * Issue a request: + * + * Examples: + * + * request('GET', '/users').end(callback) + * request('/users').end(callback) + * request('/users', callback) + * + * @param {String} method + * @param {String|Function} url or callback + * @return {Request} + * @api public + */ +function request(method, url) { + if ('function' == typeof url) { + return new Request('GET', method).end(url); + } + if (1 == arguments.length) { + return new Request('GET', method); + } + return new Request(method, url); +} +/** + * GET `url` with optional callback `fn(res)`. + * + * @param {String} url + * @param {Mixed|Function} data or fn + * @param {Function} fn + * @return {Request} + * @api public + */ +request.get = function(url, data, fn){ + var req = request('GET', url); + if ('function' == typeof data) fn = data, data = null; + if (data) req.query(data); + if (fn) req.end(fn); + return req; +}; +/** + * HEAD `url` with optional callback `fn(res)`. + * + * @param {String} url + * @param {Mixed|Function} data or fn + * @param {Function} fn + * @return {Request} + * @api public + */ +request.head = function(url, data, fn){ + var req = request('HEAD', url); + if ('function' == typeof data) fn = data, data = null; + if (data) req.send(data); + if (fn) req.end(fn); + return req; +}; +/** + * DELETE `url` with optional callback `fn(res)`. + * + * @param {String} url + * @param {Function} fn + * @return {Request} + * @api public + */ +request.del = function(url, fn){ + var req = request('DELETE', url); + if (fn) req.end(fn); + return req; +}; +/** + * PATCH `url` with optional `data` and callback `fn(res)`. + * + * @param {String} url + * @param {Mixed} data + * @param {Function} fn + * @return {Request} + * @api public + */ +request.patch = function(url, data, fn){ + var req = request('PATCH', url); + if ('function' == typeof data) fn = data, data = null; + if (data) req.send(data); + if (fn) req.end(fn); + return req; +}; +/** + * POST `url` with optional `data` and callback `fn(res)`. + * + * @param {String} url + * @param {Mixed} data + * @param {Function} fn + * @return {Request} + * @api public + */ +request.post = function(url, data, fn){ + var req = request('POST', url); + if ('function' == typeof data) fn = data, data = null; + if (data) req.send(data); + if (fn) req.end(fn); + return req; +}; +/** + * PUT `url` with optional `data` and callback `fn(res)`. + * + * @param {String} url + * @param {Mixed|Function} data or fn + * @param {Function} fn + * @return {Request} + * @api public + */ +request.put = function(url, data, fn){ + var req = request('PUT', url); + if ('function' == typeof data) fn = data, data = null; + if (data) req.send(data); + if (fn) req.end(fn); + return req; +}; +/** + * Expose `request`. + */ +module.exports = request; +},{"emitter":8,"reduce":9}],8:[function(require,module,exports){ +/** + * Expose `Emitter`. + */ +module.exports = Emitter; +/** + * Initialize a new `Emitter`. + * + * @api public + */ +function Emitter(obj) { + if (obj) return mixin(obj); +}; +/** + * Mixin the emitter properties. + * + * @param {Object} obj + * @return {Object} + * @api private + */ +function mixin(obj) { + for (var key in Emitter.prototype) { + obj[key] = Emitter.prototype[key]; + } + return obj; +} +/** + * Listen on the given `event` with `fn`. + * + * @param {String} event + * @param {Function} fn + * @return {Emitter} + * @api public + */ +Emitter.prototype.on = +Emitter.prototype.addEventListener = function(event, fn){ + this._callbacks = this._callbacks || {}; + (this._callbacks[event] = this._callbacks[event] || []) + .push(fn); + return this; +}; +/** + * Adds an `event` listener that will be invoked a single + * time then automatically removed. + * + * @param {String} event + * @param {Function} fn + * @return {Emitter} + * @api public + */ +Emitter.prototype.once = function(event, fn){ + var self = this; + this._callbacks = this._callbacks || {}; + function on() { + self.off(event, on); + fn.apply(this, arguments); + } + on.fn = fn; + this.on(event, on); + return this; +}; +/** + * Remove the given callback for `event` or all + * registered callbacks. + * + * @param {String} event + * @param {Function} fn + * @return {Emitter} + * @api public + */ +Emitter.prototype.off = +Emitter.prototype.removeListener = +Emitter.prototype.removeAllListeners = +Emitter.prototype.removeEventListener = function(event, fn){ + this._callbacks = this._callbacks || {}; + if (0 == arguments.length) { + this._callbacks = {}; + return this; + } + var callbacks = this._callbacks[event]; + if (!callbacks) return this; + if (1 == arguments.length) { + delete this._callbacks[event]; + return this; + } + var cb; + for (var i = 0; i < callbacks.length; i++) { + cb = callbacks[i]; + if (cb === fn || cb.fn === fn) { + callbacks.splice(i, 1); + break; + } + } + return this; +}; +/** + * Emit `event` with the given args. + * + * @param {String} event + * @param {Mixed} ... + * @return {Emitter} + */ +Emitter.prototype.emit = function(event){ + this._callbacks = this._callbacks || {}; + var args = [].slice.call(arguments, 1) + , callbacks = this._callbacks[event]; + if (callbacks) { + callbacks = callbacks.slice(0); + for (var i = 0, len = callbacks.length; i < len; ++i) { + callbacks[i].apply(this, args); + } + } + return this; +}; +/** + * Return array of callbacks for `event`. + * + * @param {String} event + * @return {Array} + * @api public + */ +Emitter.prototype.listeners = function(event){ + this._callbacks = this._callbacks || {}; + return this._callbacks[event] || []; +}; +/** + * Check if this emitter has `event` handlers. + * + * @param {String} event + * @return {Boolean} + * @api public + */ +Emitter.prototype.hasListeners = function(event){ + return !! this.listeners(event).length; +}; +},{}],9:[function(require,module,exports){ +/** + * Reduce `arr` with `fn`. + * + * @param {Array} arr + * @param {Function} fn + * @param {Mixed} initial + * + * TODO: combatible error handling? + */ +module.exports = function(arr, fn, initial){ + var idx = 0; + var len = arr.length; + var curr = arguments.length == 3 + ? initial + : arr[idx++]; + while (idx < len) { + curr = fn.call(null, curr, arr[idx], ++idx, arr); + } + return curr; +}; +},{}],10:[function(require,module,exports){ +var Keen = require("./index"), + each = require("./utils/each"); +module.exports = function(){ + var loaded = window['Keen'] || null, + cached = window['_' + 'Keen'] || null, + clients, + ready; + if (loaded && cached) { + clients = cached['clients'] || {}, + ready = cached['ready'] || []; + each(clients, function(client, id){ + each(Keen.prototype, function(method, key){ + loaded.prototype[key] = method; + }); + each(["Query", "Request", "Dataset", "Dataviz"], function(name){ + loaded[name] = (Keen[name]) ? Keen[name] : function(){}; + }); + if (client._config) { + client.configure.call(client, client._config); + } + if (client._setGlobalProperties) { + each(client._setGlobalProperties, function(fn){ + client.setGlobalProperties.apply(client, fn); + }); + } + if (client._addEvent) { + each(client._addEvent, function(obj){ + client.addEvent.apply(client, obj); + }); + } + var callback = client._on || []; + if (client._on) { + each(client._on, function(obj){ + client.on.apply(client, obj); + }); + client.trigger('ready'); + } + each(["_config", "_setGlobalProperties", "_addEvent", "_on"], function(name){ + if (client[name]) { + client[name] = undefined; + try{ + delete client[name]; + } catch(e){} + } + }); + }); + each(ready, function(cb, i){ + Keen.once("ready", cb); + }); + } + window['_' + 'Keen'] = undefined; + try { + delete window['_' + 'Keen'] + } catch(e) {} +}; +},{"./index":19,"./utils/each":31}],11:[function(require,module,exports){ +var Emitter = require('component-emitter'); +Emitter.prototype.trigger = Emitter.prototype.emit; +module.exports = Emitter; +},{"component-emitter":4}],12:[function(require,module,exports){ +module.exports = function(){ + return "undefined" == typeof window ? "server" : "browser"; +}; +},{}],13:[function(require,module,exports){ +var each = require('../utils/each'), + JSON2 = require('JSON2'); +module.exports = function(params){ + var query = []; + each(params, function(value, key){ + if ('string' !== typeof value) { + value = JSON2.stringify(value); + } + query.push(key + '=' + encodeURIComponent(value)); + }); + return '?' + query.join('&'); +}; +},{"../utils/each":31,"JSON2":2}],14:[function(require,module,exports){ +module.exports = function(){ + return new Date().getTimezoneOffset() * -60; +}; +},{}],15:[function(require,module,exports){ +module.exports = function(){ + if ("undefined" !== typeof window) { + if (navigator.userAgent.indexOf('MSIE') !== -1 || navigator.appVersion.indexOf('Trident/') > 0) { + return 2000; + } + } + return 16000; +}; +},{}],16:[function(require,module,exports){ +module.exports = function() { + var root = "undefined" == typeof window ? this : window; + if (root.XMLHttpRequest && ("file:" != root.location.protocol || !root.ActiveXObject)) { + return new XMLHttpRequest; + } else { + try { return new ActiveXObject("Microsoft.XMLHTTP"); } catch(e) {} + try { return new ActiveXObject("Msxml2.XMLHTTP.6.0"); } catch(e) {} + try { return new ActiveXObject("Msxml2.XMLHTTP.3.0"); } catch(e) {} + try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch(e) {} + } + return false; +}; +},{}],17:[function(require,module,exports){ +module.exports = function(err, res, callback) { + var cb = callback || function() {}; + if (res && !res.ok) { + var is_err = res.body && res.body.error_code; + err = new Error(is_err ? res.body.message : 'Unknown error occurred'); + err.code = is_err ? res.body.error_code : 'UnknownError'; + } + if (err) { + cb(err, null); + } + else { + cb(null, res.body); + } + return; +}; +},{}],18:[function(require,module,exports){ +var superagent = require('superagent'); +var each = require('../utils/each'), + getXHR = require('./get-xhr-object'); +module.exports = function(type, opts){ + return function(request) { + var __super__ = request.constructor.prototype.end; + if ( 'undefined' === typeof window ) return; + request.requestType = request.requestType || {}; + request.requestType['type'] = type; + request.requestType['options'] = request.requestType['options'] || { + async: true, + success: { + responseText: '{ "created": true }', + status: 201 + }, + error: { + responseText: '{ "error_code": "ERROR", "message": "Request failed" }', + status: 404 + } + }; + if (opts) { + if ( 'boolean' === typeof opts.async ) { + request.requestType['options'].async = opts.async; + } + if ( opts.success ) { + extend(request.requestType['options'].success, opts.success); + } + if ( opts.error ) { + extend(request.requestType['options'].error, opts.error); + } + } + request.end = function(fn){ + var self = this, + reqType = (this.requestType) ? this.requestType['type'] : 'xhr', + query, + timeout; + if ( ('GET' !== self['method'] || 'xhr' === reqType) && self.requestType['options'].async ) { + __super__.call(self, fn); + return; + } + query = self._query.join('&'); + timeout = self._timeout; + self._callback = fn || noop; + if (timeout && !self._timer) { + self._timer = setTimeout(function(){ + abortRequest.call(self); + }, timeout); + } + if (query) { + query = superagent.serializeObject(query); + self.url += ~self.url.indexOf('?') ? '&' + query : '?' + query; + } + self.emit('request', self); + if ( !self.requestType['options'].async ) { + sendXhrSync.call(self); + } + else if ( 'jsonp' === reqType ) { + sendJsonp.call(self); + } + else if ( 'beacon' === reqType ) { + sendBeacon.call(self); + } + return self; + }; + return request; + }; +}; +function sendXhrSync(){ + var xhr = getXHR(); + if (xhr) { + xhr.open('GET', this.url, false); + xhr.send(null); + } + return this; +} +function sendJsonp(){ + var self = this, + timestamp = new Date().getTime(), + script = document.createElement('script'), + parent = document.getElementsByTagName('head')[0], + callbackName = 'keenJSONPCallback', + loaded = false; + callbackName += timestamp; + while (callbackName in window) { + callbackName += 'a'; + } + window[callbackName] = function(response) { + if (loaded === true) return; + loaded = true; + handleSuccess.call(self, response); + cleanup(); + }; + script.src = self.url + '&jsonp=' + callbackName; + parent.appendChild(script); + script.onreadystatechange = function() { + if (loaded === false && self.readyState === 'loaded') { + loaded = true; + handleError.call(self); + cleanup(); + } + }; + script.onerror = function() { + if (loaded === false) { + loaded = true; + handleError.call(self); + cleanup(); + } + }; + function cleanup(){ + window[callbackName] = undefined; + try { + delete window[callbackName]; + } catch(e){} + parent.removeChild(script); + } +} +function sendBeacon(){ + var self = this, + img = document.createElement('img'), + loaded = false; + img.onload = function() { + loaded = true; + if ('naturalHeight' in this) { + if (this.naturalHeight + this.naturalWidth === 0) { + this.onerror(); + return; + } + } else if (this.width + this.height === 0) { + this.onerror(); + return; + } + handleSuccess.call(self); + }; + img.onerror = function() { + loaded = true; + handleError.call(self); + }; + img.src = self.url + '&c=clv1'; +} +function handleSuccess(res){ + var opts = this.requestType['options']['success'], + response = ''; + xhrShim.call(this, opts); + if (res) { + try { + response = JSON.stringify(res); + } catch(e) {} + } + else { + response = opts['responseText']; + } + this.xhr.responseText = response; + this.xhr.status = opts['status']; + this.emit('end'); +} +function handleError(){ + var opts = this.requestType['options']['error']; + xhrShim.call(this, opts); + this.xhr.responseText = opts['responseText']; + this.xhr.status = opts['status']; + this.emit('end'); +} +function abortRequest(){ + this.aborted = true; + this.clearTimeout(); + this.emit('abort'); +} +function xhrShim(opts){ + this.xhr = { + getAllResponseHeaders: function(){ return ''; }, + getResponseHeader: function(){ return 'application/json'; }, + responseText: opts['responseText'], + status: opts['status'] + }; + return this; +} +},{"../utils/each":31,"./get-xhr-object":16,"superagent":7}],19:[function(require,module,exports){ +var root = 'undefined' !== typeof window ? window : this; +var previous_Keen = root.Keen; +var Emitter = require('./helpers/emitter-shim'); +function Keen(config) { + this.configure(config || {}); + Keen.trigger('client', this); +} +Keen.debug = false; +Keen.enabled = true; +Keen.loaded = true; +Keen.version = '3.2.6'; +Emitter(Keen); +Emitter(Keen.prototype); +Keen.prototype.configure = function(cfg){ + var config = cfg || {}; + if (config['host']) { + config['host'].replace(/.*?:\/\//g, ''); + } + if (config.protocol && config.protocol === 'auto') { + config['protocol'] = location.protocol.replace(/:/g, ''); + } + this.config = { + projectId : config.projectId, + writeKey : config.writeKey, + readKey : config.readKey, + masterKey : config.masterKey, + requestType : config.requestType || 'jsonp', + host : config['host'] || 'api.keen.io/3.0', + protocol : config['protocol'] || 'https', + globalProperties: null + }; + if (Keen.debug) { + this.on('error', Keen.log); + } + this.trigger('ready'); +}; +Keen.prototype.projectId = function(str){ + if (!arguments.length) return this.config.projectId; + this.config.projectId = (str ? String(str) : null); + return this; +}; +Keen.prototype.masterKey = function(str){ + if (!arguments.length) return this.config.masterKey; + this.config.masterKey = (str ? String(str) : null); + return this; +}; +Keen.prototype.readKey = function(str){ + if (!arguments.length) return this.config.readKey; + this.config.readKey = (str ? String(str) : null); + return this; +}; +Keen.prototype.writeKey = function(str){ + if (!arguments.length) return this.config.writeKey; + this.config.writeKey = (str ? String(str) : null); + return this; +}; +Keen.prototype.url = function(path){ + if (!this.projectId()) { + this.trigger('error', 'Client is missing projectId property'); + return; + } + return this.config.protocol + '://' + this.config.host + '/projects/' + this.projectId() + path; +}; +Keen.log = function(message) { + if (Keen.debug && typeof console == 'object') { + console.log('[Keen IO]', message); + } +}; +Keen.noConflict = function(){ + root.Keen = previous_Keen; + return Keen; +}; +Keen.ready = function(fn){ + if (Keen.loaded) { + fn(); + } else { + Keen.once('ready', fn); + } +}; +module.exports = Keen; +},{"./helpers/emitter-shim":11}],20:[function(require,module,exports){ +var JSON2 = require('JSON2'); +var request = require('superagent'); +var Keen = require('../index'); +var base64 = require('../utils/base64'), + each = require('../utils/each'), + getContext = require('../helpers/get-context'), + getQueryString = require('../helpers/get-query-string'), + getUrlMaxLength = require('../helpers/get-url-max-length'), + getXHR = require('../helpers/get-xhr-object'), + requestTypes = require('../helpers/superagent-request-types'), + responseHandler = require('../helpers/superagent-handle-response'); +module.exports = function(collection, payload, callback, async) { + var self = this, + urlBase = this.url('/events/' + encodeURIComponent(collection)), + reqType = this.config.requestType, + data = {}, + cb = callback, + isAsync, + getUrl; + isAsync = ('boolean' === typeof async) ? async : true; + if (!Keen.enabled) { + handleValidationError.call(self, 'Keen.enabled = false'); + return; + } + if (!self.projectId()) { + handleValidationError.call(self, 'Missing projectId property'); + return; + } + if (!self.writeKey()) { + handleValidationError.call(self, 'Missing writeKey property'); + return; + } + if (!collection || typeof collection !== 'string') { + handleValidationError.call(self, 'Collection name must be a string'); + return; + } + if (self.config.globalProperties) { + data = self.config.globalProperties(collection); + } + each(payload, function(value, key){ + data[key] = value; + }); + if ( !getXHR() && 'xhr' === reqType ) { + reqType = 'jsonp'; + } + if ( 'xhr' !== reqType || !isAsync ) { + getUrl = prepareGetRequest.call(self, urlBase, data); + } + if ( getUrl && getContext() === 'browser' ) { + request + .get(getUrl) + .use(requestTypes(reqType, { async: isAsync })) + .end(handleResponse); + } + else if ( getXHR() || getContext() === 'server' ) { + request + .post(urlBase) + .set('Content-Type', 'application/json') + .set('Authorization', self.writeKey()) + .send(data) + .end(handleResponse); + } + else { + self.trigger('error', 'Request not sent: URL length exceeds current browser limit, and XHR (POST) is not supported.'); + } + function handleResponse(err, res){ + responseHandler(err, res, cb); + cb = callback = null; + } + function handleValidationError(msg){ + var err = 'Event not recorded: ' + msg; + self.trigger('error', err); + if (cb) { + cb.call(self, err, null); + cb = callback = null; + } + } + return; +}; +function prepareGetRequest(url, data){ + url += getQueryString({ + api_key : this.writeKey(), + data : base64.encode( JSON2.stringify(data) ), + modified : new Date().getTime() + }); + return ( url.length < getUrlMaxLength() ) ? url : false; +} +},{"../helpers/get-context":12,"../helpers/get-query-string":13,"../helpers/get-url-max-length":15,"../helpers/get-xhr-object":16,"../helpers/superagent-handle-response":17,"../helpers/superagent-request-types":18,"../index":19,"../utils/base64":29,"../utils/each":31,"JSON2":2,"superagent":7}],21:[function(require,module,exports){ +var Keen = require('../index'); +var request = require('superagent'); +var each = require('../utils/each'), + getContext = require('../helpers/get-context'), + getXHR = require('../helpers/get-xhr-object'), + requestTypes = require('../helpers/superagent-request-types'), + responseHandler = require('../helpers/superagent-handle-response'); +module.exports = function(payload, callback) { + var self = this, + urlBase = this.url('/events'), + data = {}, + cb = callback; + if (!Keen.enabled) { + handleValidationError.call(self, 'Keen.enabled = false'); + return; + } + if (!self.projectId()) { + handleValidationError.call(self, 'Missing projectId property'); + return; + } + if (!self.writeKey()) { + handleValidationError.call(self, 'Missing writeKey property'); + return; + } + if (arguments.length > 2) { + handleValidationError.call(self, 'Incorrect arguments provided to #addEvents method'); + return; + } + if (typeof payload !== 'object' || payload instanceof Array) { + handleValidationError.call(self, 'Request payload must be an object'); + return; + } + if (self.config.globalProperties) { + each(payload, function(events, collection){ + each(events, function(body, index){ + var base = self.config.globalProperties(collection); + each(body, function(value, key){ + base[key] = value; + }); + data[collection].push(base); + }); + }); + } + else { + data = payload; + } + if ( getXHR() || getContext() === 'server' ) { + request + .post(urlBase) + .set('Content-Type', 'application/json') + .set('Authorization', self.writeKey()) + .send(data) + .end(function(err, res){ + responseHandler(err, res, cb); + cb = callback = null; + }); + } + else { + self.trigger('error', 'Events not recorded: XHR support is required for batch upload'); + } + function handleValidationError(msg){ + var err = 'Events not recorded: ' + msg; + self.trigger('error', err); + if (cb) { + cb.call(self, err, null); + cb = callback = null; + } + } + return; +}; +},{"../helpers/get-context":12,"../helpers/get-xhr-object":16,"../helpers/superagent-handle-response":17,"../helpers/superagent-request-types":18,"../index":19,"../utils/each":31,"superagent":7}],22:[function(require,module,exports){ +var request = require('superagent'); +var getQueryString = require('../helpers/get-query-string'), + handleResponse = require('../helpers/superagent-handle-response'), + requestTypes = require('../helpers/superagent-request-types'); +module.exports = function(url, params, api_key, callback){ + var reqType = this.config.requestType, + data = params || {}; + if (reqType === 'beacon') { + reqType = 'jsonp'; + } + data['api_key'] = data['api_key'] || api_key; + request + .get(url+getQueryString(data)) + .use(requestTypes(reqType)) + .end(function(err, res){ + handleResponse(err, res, callback); + callback = null; + }); +}; +},{"../helpers/get-query-string":13,"../helpers/superagent-handle-response":17,"../helpers/superagent-request-types":18,"superagent":7}],23:[function(require,module,exports){ +var request = require('superagent'); +var handleResponse = require('../helpers/superagent-handle-response'); +module.exports = function(url, data, api_key, callback){ + request + .post(url) + .set('Content-Type', 'application/json') + .set('Authorization', api_key) + .send(data || {}) + .end(function(err, res) { + handleResponse(err, res, callback); + callback = null; + }); +}; +},{"../helpers/superagent-handle-response":17,"superagent":7}],24:[function(require,module,exports){ +var Request = require("../request"); +module.exports = function(query, callback) { + var queries = [], + cb = callback, + request; + if (query instanceof Array) { + queries = query; + } else { + queries.push(query); + } + request = new Request(this, queries, cb).refresh(); + cb = callback = null; + return request; +}; +},{"../request":28}],25:[function(require,module,exports){ +module.exports = function(newGlobalProperties) { + if (newGlobalProperties && typeof(newGlobalProperties) == "function") { + this.config.globalProperties = newGlobalProperties; + } else { + this.trigger("error", "Invalid value for global properties: " + newGlobalProperties); + } +}; +},{}],26:[function(require,module,exports){ +var addEvent = require("./addEvent"); +module.exports = function(jsEvent, eventCollection, payload, timeout, timeoutCallback){ + var evt = jsEvent, + target = (evt.currentTarget) ? evt.currentTarget : (evt.srcElement || evt.target), + timer = timeout || 500, + triggered = false, + targetAttr = "", + callback, + win; + if (target.getAttribute !== void 0) { + targetAttr = target.getAttribute("target"); + } else if (target.target) { + targetAttr = target.target; + } + if ((targetAttr == "_blank" || targetAttr == "blank") && !evt.metaKey) { + win = window.open("about:blank"); + win.document.location = target.href; + } + if (target.nodeName === "A") { + callback = function(){ + if(!triggered && !evt.metaKey && (targetAttr !== "_blank" && targetAttr !== "blank")){ + triggered = true; + window.location = target.href; + } + }; + } else if (target.nodeName === "FORM") { + callback = function(){ + if(!triggered){ + triggered = true; + target.submit(); + } + }; + } else { + this.trigger("error", "#trackExternalLink method not attached to an or DOM element"); + } + if (timeoutCallback) { + callback = function(){ + if(!triggered){ + triggered = true; + timeoutCallback(); + } + }; + } + addEvent.call(this, eventCollection, payload, callback); + setTimeout(callback, timer); + if (!evt.metaKey) { + return false; + } +}; +},{"./addEvent":20}],27:[function(require,module,exports){ +var each = require("./utils/each"), + extend = require("./utils/extend"), + getTimezoneOffset = require("./helpers/get-timezone-offset"), + getQueryString = require("./helpers/get-query-string"); +var Emitter = require('./helpers/emitter-shim'); +function Query(){ + this.configure.apply(this, arguments); +}; +Emitter(Query.prototype); +Query.prototype.configure = function(analysisType, params) { + this.analysis = analysisType; + this.params = this.params || {}; + this.set(params); + if (this.params.timezone === void 0) { + this.params.timezone = getTimezoneOffset(); + } + return this; +}; +Query.prototype.set = function(attributes) { + var self = this; + each(attributes, function(v, k){ + var key = k, value = v; + if (k.match(new RegExp("[A-Z]"))) { + key = k.replace(/([A-Z])/g, function($1) { return "_"+$1.toLowerCase(); }); + } + self.params[key] = value; + if (value instanceof Array) { + each(value, function(dv, index){ + if (dv instanceof Array == false && typeof dv === "object") { + each(dv, function(deepValue, deepKey){ + if (deepKey.match(new RegExp("[A-Z]"))) { + var _deepKey = deepKey.replace(/([A-Z])/g, function($1) { return "_"+$1.toLowerCase(); }); + delete self.params[key][index][deepKey]; + self.params[key][index][_deepKey] = deepValue; + } + }); + } + }); + } + }); + return self; +}; +Query.prototype.get = function(attribute) { + var key = attribute; + if (key.match(new RegExp("[A-Z]"))) { + key = key.replace(/([A-Z])/g, function($1) { return "_"+$1.toLowerCase(); }); + } + if (this.params) { + return this.params[key] || null; + } +}; +Query.prototype.addFilter = function(property, operator, value) { + this.params.filters = this.params.filters || []; + this.params.filters.push({ + "property_name": property, + "operator": operator, + "property_value": value + }); + return this; +}; +module.exports = Query; +},{"./helpers/emitter-shim":11,"./helpers/get-query-string":13,"./helpers/get-timezone-offset":14,"./utils/each":31,"./utils/extend":32}],28:[function(require,module,exports){ +var each = require("./utils/each"), + extend = require("./utils/extend"), + sendQuery = require("./utils/sendQuery"); +var Keen = require("./"); +var Emitter = require('./helpers/emitter-shim'); +function Request(client, queries, callback){ + var cb = callback; + this.config = { + timeout: 300 * 1000 + }; + this.configure(client, queries, cb); + cb = callback = null; +}; +Emitter(Request.prototype); +Request.prototype.configure = function(client, queries, callback){ + var cb = callback; + extend(this, { + "client" : client, + "queries" : queries, + "data" : {}, + "callback" : cb + }); + cb = callback = null; + return this; +}; +Request.prototype.timeout = function(ms){ + if (!arguments.length) return this.config.timeout; + this.config.timeout = (!isNaN(parseInt(ms)) ? parseInt(ms) : null); + return this; +}; +Request.prototype.refresh = function(){ + var self = this, + completions = 0, + response = [], + errored = false; + var handleResponse = function(err, res, index){ + if (err) { + self.trigger("error", err); + if (self.callback) { + self.callback(err, null); + } + errored = true; + return; + } + response[index] = res; + completions++; + if (completions == self.queries.length && !errored) { + self.data = (self.queries.length == 1) ? response[0] : response; + self.trigger("complete", null, self.data); + if (self.callback) { + self.callback(null, self.data); + } + } + }; + each(self.queries, function(query, index){ + var path; + var cbSequencer = function(err, res){ + handleResponse(err, res, index); + }; + if (query instanceof Keen.Query) { + path = "/queries/" + query.analysis; + sendQuery.call(self, path, query.params, cbSequencer); + } + else if ( Object.prototype.toString.call(query) === "[object String]" ) { + path = "/saved_queries/" + encodeURIComponent(query) + "/result"; + sendQuery.call(self, path, null, cbSequencer); + } + else { + var res = { + statusText: "Bad Request", + responseText: { message: "Error: Query " + (+index+1) + " of " + self.queries.length + " for project " + self.client.projectId() + " is not a valid request" } + }; + self.trigger("error", res.responseText.message); + if (self.callback) { + self.callback(res.responseText.message, null); + } + } + }); + return this; +}; +module.exports = Request; +},{"./":19,"./helpers/emitter-shim":11,"./utils/each":31,"./utils/extend":32,"./utils/sendQuery":34}],29:[function(require,module,exports){ +module.exports = { + map: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=", + encode: function (n) { + "use strict"; + var o = "", i = 0, m = this.map, i1, i2, i3, e1, e2, e3, e4; + n = this.utf8.encode(n); + while (i < n.length) { + i1 = n.charCodeAt(i++); i2 = n.charCodeAt(i++); i3 = n.charCodeAt(i++); + e1 = (i1 >> 2); e2 = (((i1 & 3) << 4) | (i2 >> 4)); e3 = (isNaN(i2) ? 64 : ((i2 & 15) << 2) | (i3 >> 6)); + e4 = (isNaN(i2) || isNaN(i3)) ? 64 : i3 & 63; + o = o + m.charAt(e1) + m.charAt(e2) + m.charAt(e3) + m.charAt(e4); + } return o; + }, + decode: function (n) { + "use strict"; + var o = "", i = 0, m = this.map, cc = String.fromCharCode, e1, e2, e3, e4, c1, c2, c3; + n = n.replace(/[^A-Za-z0-9\+\/\=]/g, ""); + while (i < n.length) { + e1 = m.indexOf(n.charAt(i++)); e2 = m.indexOf(n.charAt(i++)); + e3 = m.indexOf(n.charAt(i++)); e4 = m.indexOf(n.charAt(i++)); + c1 = (e1 << 2) | (e2 >> 4); c2 = ((e2 & 15) << 4) | (e3 >> 2); + c3 = ((e3 & 3) << 6) | e4; + o = o + (cc(c1) + ((e3 != 64) ? cc(c2) : "")) + (((e4 != 64) ? cc(c3) : "")); + } return this.utf8.decode(o); + }, + utf8: { + encode: function (n) { + "use strict"; + var o = "", i = 0, cc = String.fromCharCode, c; + while (i < n.length) { + c = n.charCodeAt(i++); o = o + ((c < 128) ? cc(c) : ((c > 127) && (c < 2048)) ? + (cc((c >> 6) | 192) + cc((c & 63) | 128)) : (cc((c >> 12) | 224) + cc(((c >> 6) & 63) | 128) + cc((c & 63) | 128))); + } return o; + }, + decode: function (n) { + "use strict"; + var o = "", i = 0, cc = String.fromCharCode, c2, c; + while (i < n.length) { + c = n.charCodeAt(i); + o = o + ((c < 128) ? [cc(c), i++][0] : ((c > 191) && (c < 224)) ? + [cc(((c & 31) << 6) | ((c2 = n.charCodeAt(i + 1)) & 63)), (i += 2)][0] : + [cc(((c & 15) << 12) | (((c2 = n.charCodeAt(i + 1)) & 63) << 6) | ((c3 = n.charCodeAt(i + 2)) & 63)), (i += 3)][0]); + } return o; + } + } +}; +},{}],30:[function(require,module,exports){ +var JSON2 = require("JSON2"); +module.exports = function(target) { + return JSON2.parse( JSON2.stringify( target ) ); +}; +},{"JSON2":2}],31:[function(require,module,exports){ +module.exports = function(o, cb, s){ + var n; + if (!o){ + return 0; + } + s = !s ? o : s; + if (o instanceof Array){ + for (n=0; n 0) { + this.parse.apply(this, arguments); + } +} +Dataset.defaults = { + delimeter: " -> " +}; +Emitter(Dataset); +Emitter(Dataset.prototype); +Dataset.prototype.input = function(obj){ + if (!arguments.length) return this["data"]["input"]; + this["data"]["input"] = (obj ? clone(obj) : null); + return this; +}; +Dataset.prototype.output = function(arr){ + if (!arguments.length) return this["data"].output; + this["data"].output = (arr instanceof Array ? arr : null); + return this; +} +Dataset.prototype.method = function(str){ + if (!arguments.length) return this.meta["method"]; + this.meta["method"] = (str ? String(str) : null); + return this; +}; +Dataset.prototype.schema = function(obj){ + if (!arguments.length) return this.meta.schema; + this.meta.schema = (obj ? obj : null); + return this; +}; +Dataset.prototype.parse = function(raw, schema){ + var options; + if (raw) this.input(raw); + if (schema) this.schema(schema); + this.output([[]]); + if (this.meta.schema.select) { + this.method("select"); + options = extend({ + records: "", + select: true + }, this.schema()); + _select.call(this, _optHash(options)); + } + else if (this.meta.schema.unpack) { + this.method("unpack"); + options = extend({ + records: "", + unpack: { + index: false, + value: false, + label: false + } + }, this.schema()); + _unpack.call(this, _optHash(options)); + } + return this; +}; +function _select(cfg){ + var self = this, + options = cfg || {}, + target_set = [], + unique_keys = []; + var root, records_target; + if (options.records === "" || !options.records) { + root = [self.input()]; + } else { + records_target = options.records.split(Dataset.defaults.delimeter); + root = parse.apply(self, [self.input()].concat(records_target))[0]; + } + each(options.select, function(prop){ + target_set.push(prop.path.split(Dataset.defaults.delimeter)); + }); + if (target_set.length == 0) { + each(root, function(record, interval){ + var flat = flatten(record); + for (var key in flat) { + if (flat.hasOwnProperty(key) && unique_keys.indexOf(key) == -1) { + unique_keys.push(key); + target_set.push([key]); + } + } + }); + } + var test = [[]]; + each(target_set, function(props, i){ + if (target_set.length == 1) { + test[0].push('label', 'value'); + } else { + test[0].push(props.join(".")); + } + }); + each(root, function(record, i){ + var flat = flatten(record); + if (target_set.length == 1) { + test.push([target_set.join("."), flat[target_set.join(".")]]); + } else { + test.push([]); + each(target_set, function(t, j){ + var target = t.join("."); + test[i+1].push(flat[target]); + }); + } + }); + self.output(test); + self.format(options.select); + return self; +} +function _unpack(options){ + var self = this, discovered_labels = []; + var value_set = (options.unpack.value) ? options.unpack.value.path.split(Dataset.defaults.delimeter) : false, + label_set = (options.unpack.label) ? options.unpack.label.path.split(Dataset.defaults.delimeter) : false, + index_set = (options.unpack.index) ? options.unpack.index.path.split(Dataset.defaults.delimeter) : false; + var value_desc = (value_set[value_set.length-1] !== "") ? value_set[value_set.length-1] : "Value", + label_desc = (label_set[label_set.length-1] !== "") ? label_set[label_set.length-1] : "Label", + index_desc = (index_set[index_set.length-1] !== "") ? index_set[index_set.length-1] : "Index"; + var root = (function(){ + var root; + if (options.records == "") { + root = [self.input()]; + } else { + root = parse.apply(self, [self.input()].concat(options.records.split(Dataset.defaults.delimeter))); + } + return root[0]; + })(); + if (root instanceof Array == false) { + root = [root]; + } + each(root, function(record, interval){ + var labels = (label_set) ? parse.apply(self, [record].concat(label_set)) : []; + if (labels) { + discovered_labels = labels; + } + }); + each(root, function(record, interval){ + var plucked_value = (value_set) ? parse.apply(self, [record].concat(value_set)) : false, + plucked_index = (index_set) ? parse.apply(self, [record].concat(index_set)) : false; + if (plucked_index) { + each(plucked_index, function(){ + self.data.output.push([]); + }); + } else { + self.data.output.push([]); + } + if (plucked_index) { + if (interval == 0) { + self.data.output[0].push(index_desc); + if (discovered_labels.length > 0) { + each(discovered_labels, function(value, i){ + self.data.output[0].push(value); + }); + } else { + self.data.output[0].push(value_desc); + } + } + if (root.length < self.data.output.length-1) { + if (interval == 0) { + each(self.data.output, function(row, i){ + if (i > 0) { + self.data.output[i].push(plucked_index[i-1]); + } + }); + } + } else { + self.data.output[interval+1].push(plucked_index[0]); + } + } + if (!plucked_index && discovered_labels.length > 0) { + if (interval == 0) { + self.data.output[0].push(label_desc); + self.data.output[0].push(value_desc); + } + self.data.output[interval+1].push(discovered_labels[0]); + } + if (!plucked_index && discovered_labels.length == 0) { + self.data.output[0].push(''); + } + if (plucked_value) { + if (root.length < self.data.output.length-1) { + if (interval == 0) { + each(self.data.output, function(row, i){ + if (i > 0) { + self.data.output[i].push(plucked_value[i-1]); + } + }); + } + } else { + each(plucked_value, function(value){ + self.data.output[interval+1].push(value); + }); + } + } else { + each(self.data.output[0], function(cell, i){ + var offset = (plucked_index) ? 0 : -1; + if (i > offset) { + self.data.output[interval+1].push(null); + } + }) + } + }); + self.format(options.unpack); + return this; +} +function _optHash(options){ + each(options.unpack, function(value, key, object){ + if (value && is(value, 'string')) { + options.unpack[key] = { path: options.unpack[key] }; + } + }); + return options; +} +function is(o, t){ + o = typeof(o); + if (!t){ + return o != 'undefined'; + } + return o == t; +} +function extend(o, e){ + each(e, function(v, n){ + if (is(o[n], 'object') && is(v, 'object')){ + o[n] = extend(o[n], v); + } else if (v !== null) { + o[n] = v; + } + }); + return o; +} +module.exports = Dataset; +},{"../core/helpers/emitter-shim":11,"../core/utils/clone":30,"../core/utils/each":31,"./utils/flatten":48,"./utils/parse":49}],36:[function(require,module,exports){ +var extend = require("../core/utils/extend"), + Dataset = require("./dataset"); +extend(Dataset.prototype, require("./lib/append")); +extend(Dataset.prototype, require("./lib/delete")); +extend(Dataset.prototype, require("./lib/filter")); +extend(Dataset.prototype, require("./lib/insert")); +extend(Dataset.prototype, require("./lib/select")); +extend(Dataset.prototype, require("./lib/set")); +extend(Dataset.prototype, require("./lib/sort")); +extend(Dataset.prototype, require("./lib/update")); +extend(Dataset.prototype, require("./lib/analyses")); +extend(Dataset.prototype, { + "format": require("./lib/format"), +}); +module.exports = Dataset; +},{"../core/utils/extend":32,"./dataset":35,"./lib/analyses":37,"./lib/append":38,"./lib/delete":39,"./lib/filter":40,"./lib/format":41,"./lib/insert":42,"./lib/select":43,"./lib/set":44,"./lib/sort":45,"./lib/update":46}],37:[function(require,module,exports){ +var each = require("../../core/utils/each"), + arr = ["Average", "Maximum", "Minimum", "Sum"], + output = {}; +output["average"] = function(arr, start, end){ + var set = arr.slice(start||0, (end ? end+1 : arr.length)), + sum = 0, + avg = null; + each(set, function(val, i){ + if (typeof val === "number" && !isNaN(parseFloat(val))) { + sum += parseFloat(val); + } + }); + return sum / set.length; +}; +output["maximum"] = function(arr, start, end){ + var set = arr.slice(start||0, (end ? end+1 : arr.length)), + nums = []; + each(set, function(val, i){ + if (typeof val === "number" && !isNaN(parseFloat(val))) { + nums.push(parseFloat(val)); + } + }); + return Math.max.apply(Math, nums); +}; +output["minimum"] = function(arr, start, end){ + var set = arr.slice(start||0, (end ? end+1 : arr.length)), + nums = []; + each(set, function(val, i){ + if (typeof val === "number" && !isNaN(parseFloat(val))) { + nums.push(parseFloat(val)); + } + }); + return Math.min.apply(Math, nums); +}; +output["sum"] = function(arr, start, end){ + var set = arr.slice(start||0, (end ? end+1 : arr.length)), + sum = 0; + each(set, function(val, i){ + if (typeof val === "number" && !isNaN(parseFloat(val))) { + sum += parseFloat(val); + } + }); + return sum; +}; +each(arr, function(v,i){ + output["getColumn"+v] = output["getRow"+v] = function(arr){ + return this[v.toLowerCase()](arr, 1); + }; +}); +output["getColumnLabel"] = output["getRowIndex"] = function(arr){ + return arr[0]; +}; +module.exports = output; +},{"../../core/utils/each":31}],38:[function(require,module,exports){ +var each = require("../../core/utils/each"); +var createNullList = require('../utils/create-null-list'); +module.exports = { + "appendColumn": appendColumn, + "appendRow": appendRow +}; +function appendColumn(str, input){ + var self = this, + args = Array.prototype.slice.call(arguments, 2), + label = (str !== undefined) ? str : null; + if (typeof input === "function") { + self.data.output[0].push(label); + each(self.output(), function(row, i){ + var cell; + if (i > 0) { + cell = input.call(self, row, i); + if (typeof cell === "undefined") { + cell = null; + } + self.data.output[i].push(cell); + } + }); + } + else if (!input || input instanceof Array) { + input = input || []; + if (input.length <= self.output().length - 1) { + input = input.concat( createNullList(self.output().length - 1 - input.length) ); + } + else { + each(input, function(value, i){ + if (self.data.output.length -1 < input.length) { + appendRow.call(self, String( self.data.output.length )); + } + }); + } + self.data.output[0].push(label); + each(input, function(value, i){ + self.data.output[i+1][self.data.output[0].length-1] = value; + }); + } + return self; +} +function appendRow(str, input){ + var self = this, + args = Array.prototype.slice.call(arguments, 2), + label = (str !== undefined) ? str : null, + newRow = []; + newRow.push(label); + if (typeof input === "function") { + each(self.data.output[0], function(label, i){ + var col, cell; + if (i > 0) { + col = self.selectColumn(i); + cell = input.call(self, col, i); + if (typeof cell === "undefined") { + cell = null; + } + newRow.push(cell); + } + }); + self.data.output.push(newRow); + } + else if (!input || input instanceof Array) { + input = input || []; + if (input.length <= self.data.output[0].length - 1) { + input = input.concat( createNullList( self.data.output[0].length - 1 - input.length ) ); + } + else { + each(input, function(value, i){ + if (self.data.output[0].length -1 < input.length) { + appendColumn.call(self, String( self.data.output[0].length )); + } + }); + } + self.data.output.push( newRow.concat(input) ); + } + return self; +} +},{"../../core/utils/each":31,"../utils/create-null-list":47}],39:[function(require,module,exports){ +var each = require("../../core/utils/each"); +module.exports = { + "deleteColumn": deleteColumn, + "deleteRow": deleteRow +}; +function deleteColumn(q){ + var self = this, + index = (typeof q === 'number') ? q : this.data.output[0].indexOf(q); + if (index > -1) { + each(self.data.output, function(row, i){ + self.data.output[i].splice(index, 1); + }); + } + return self; +} +function deleteRow(q){ + var index = (typeof q === 'number') ? q : this.selectColumn(0).indexOf(q); + if (index > -1) { + this.data.output.splice(index, 1); + } + return this; +} +},{"../../core/utils/each":31}],40:[function(require,module,exports){ +var each = require("../../core/utils/each"); +module.exports = { + "filterColumns": filterColumns, + "filterRows": filterRows +}; +function filterColumns(fn){ + var self = this, + clone = new Array(); + each(self.data.output, function(row, i){ + clone.push([]); + }); + each(self.data.output[0], function(col, i){ + var selectedColumn = self.selectColumn(i); + if (i == 0 || fn.call(self, selectedColumn, i)) { + each(selectedColumn, function(cell, ri){ + clone[ri].push(cell); + }); + } + }); + self.output(clone); + return self; +} +function filterRows(fn){ + var self = this, + clone = []; + each(self.output(), function(row, i){ + if (i == 0 || fn.call(self, row, i)) { + clone.push(row); + } + }); + self.output(clone); + return self; +} +},{"../../core/utils/each":31}],41:[function(require,module,exports){ +var each = require("../../core/utils/each"); +module.exports = function(options){ + var self = this; + if (this.method() === 'select') { + each(self.output(), function(row, i){ + if (i == 0) { + each(row, function(cell, j){ + if (options[j] && options[j].label) { + self.data.output[i][j] = options[j].label; + } + }); + } else { + each(row, function(cell, j){ + self.data.output[i][j] = _applyFormat(self.data.output[i][j], options[j]); + }); + } + }); + } + if (this.method() === 'unpack') { + if (options.index) { + each(self.output(), function(row, i){ + if (i == 0) { + if (options.index.label) { + self.data.output[i][0] = options.index.label; + } + } else { + self.data.output[i][0] = _applyFormat(self.data.output[i][0], options.index); + } + }); + } + if (options.label) { + if (options.index) { + each(self.output(), function(row, i){ + each(row, function(cell, j){ + if (i == 0 && j > 0) { + self.data.output[i][j] = _applyFormat(self.data.output[i][j], options.label); + } + }); + }); + } else { + each(self.output(), function(row, i){ + if (i > 0) { + self.data.output[i][0] = _applyFormat(self.data.output[i][0], options.label); + } + }); + } + } + if (options.value) { + if (options.index) { + each(self.output(), function(row, i){ + each(row, function(cell, j){ + if (i > 0 && j > 0) { + self.data.output[i][j] = _applyFormat(self.data.output[i][j], options.value); + } + }); + }); + } else { + each(self.output(), function(row, i){ + each(row, function(cell, j){ + if (i > 0) { + self.data.output[i][j] = _applyFormat(self.data.output[i][j], options.value); + } + }); + }); + } + } + } + return self; +}; +function _applyFormat(value, opts){ + var output = value, + options = opts || {}; + if (options.replace) { + each(options.replace, function(val, key){ + if (output == key || String(output) == String(key) || parseFloat(output) == parseFloat(key)) { + output = val; + } + }); + } + if (options.type && options.type == 'date') { + if (options.format && moment && moment(value).isValid()) { + output = moment(output).format(options.format); + } else { + output = new Date(output); + } + } + if (options.type && options.type == 'string') { + output = String(output); + } + if (options.type && options.type == 'number' && !isNaN(parseFloat(output))) { + output = parseFloat(output); + } + return output; +} +},{"../../core/utils/each":31}],42:[function(require,module,exports){ +var each = require("../../core/utils/each"); +var createNullList = require('../utils/create-null-list'); +var append = require('./append'); +var appendRow = append.appendRow, + appendColumn = append.appendColumn; +module.exports = { + "insertColumn": insertColumn, + "insertRow": insertRow +}; +function insertColumn(index, str, input){ + var self = this, label; + label = (str !== undefined) ? str : null; + if (typeof input === "function") { + self.data.output[0].splice(index, 0, label); + each(self.output(), function(row, i){ + var cell; + if (i > 0) { + cell = input.call(self, row, i); + if (typeof cell === "undefined") { + cell = null; + } + self.data.output[i].splice(index, 0, cell); + } + }); + } + else if (!input || input instanceof Array) { + input = input || []; + if (input.length <= self.output().length - 1) { + input = input.concat( createNullList(self.output().length - 1 - input.length) ); + } + else { + each(input, function(value, i){ + if (self.data.output.length -1 < input.length) { + appendRow.call(self, String( self.data.output.length )); + } + }); + } + self.data.output[0].splice(index, 0, label); + each(input, function(value, i){ + self.data.output[i+1].splice(index, 0, value); + }); + } + return self; +} +function insertRow(index, str, input){ + var self = this, label, newRow = []; + label = (str !== undefined) ? str : null; + newRow.push(label); + if (typeof input === "function") { + each(self.output()[0], function(label, i){ + var col, cell; + if (i > 0) { + col = self.selectColumn(i); + cell = input.call(self, col, i); + if (typeof cell === "undefined") { + cell = null; + } + newRow.push(cell); + } + }); + self.data.output.splice(index, 0, newRow); + } + else if (!input || input instanceof Array) { + input = input || []; + if (input.length <= self.data.output[0].length - 1) { + input = input.concat( createNullList( self.data.output[0].length - 1 - input.length ) ); + } + else { + each(input, function(value, i){ + if (self.data.output[0].length -1 < input.length) { + appendColumn.call(self, String( self.data.output[0].length )); + } + }); + } + self.data.output.splice(index, 0, newRow.concat(input) ); + } + return self; +} +},{"../../core/utils/each":31,"../utils/create-null-list":47,"./append":38}],43:[function(require,module,exports){ +var each = require("../../core/utils/each"); +module.exports = { + "selectColumn": selectColumn, + "selectRow": selectRow +}; +function selectColumn(q){ + var result = new Array(), + index = (typeof q === 'number') ? q : this.data.output[0].indexOf(q); + if (index > -1 && 'undefined' !== typeof this.data.output[0][index]) { + each(this.data.output, function(row, i){ + result.push(row[index]); + }); + } + return result; +} +function selectRow(q){ + var result = new Array(), + index = (typeof q === 'number') ? q : this.selectColumn(0).indexOf(q); + if (index > -1 && 'undefined' !== typeof this.data.output[index]) { + result = this.data.output[index]; + } + return result; +} +},{"../../core/utils/each":31}],44:[function(require,module,exports){ +var each = require("../../core/utils/each"); +var append = require('./append'); +var select = require('./select'); +module.exports = { + "set": set +}; +function set(coords, value){ + if (arguments.length < 2 || coords.length < 2) { + throw Error('Incorrect arguments provided for #set method'); + } + var colIndex = 'number' === typeof coords[0] ? coords[0] : this.data.output[0].indexOf(coords[0]), + rowIndex = 'number' === typeof coords[1] ? coords[1] : select.selectColumn.call(this, 0).indexOf(coords[1]); + var colResult = select.selectColumn.call(this, coords[0]), + rowResult = select.selectRow.call(this, coords[1]); + if (colResult.length < 1) { + append.appendColumn.call(this, coords[0]); + colIndex = this.data.output[0].length-1; + } + if (rowResult.length < 1) { + append.appendRow.call(this, coords[1]); + rowIndex = this.data.output.length-1; + } + this.data.output[ rowIndex ][ colIndex ] = value; + return this; +} +},{"../../core/utils/each":31,"./append":38,"./select":43}],45:[function(require,module,exports){ +var each = require("../../core/utils/each"); +module.exports = { + "sortColumns": sortColumns, + "sortRows": sortRows +}; +function sortColumns(str, comp){ + var self = this, + head = this.output()[0].slice(1), + cols = [], + clone = [], + fn = comp || this.getColumnLabel; + each(head, function(cell, i){ + cols.push(self.selectColumn(i+1).slice(0)); + }); + cols.sort(function(a,b){ + var op = fn.call(self, a) > fn.call(self, b); + if (op) { + return (str === "asc" ? 1 : -1); + } else if (!op) { + return (str === "asc" ? -1 : 1); + } else { + return 0; + } + }); + each(cols, function(col, i){ + self + .deleteColumn(i+1) + .insertColumn(i+1, col[0], col.slice(1)); + }); + return self; +} +function sortRows(str, comp){ + var self = this, + head = this.output().slice(0,1), + body = this.output().slice(1), + fn = comp || this.getRowIndex; + body.sort(function(a, b){ + var op = fn.call(self, a) > fn.call(self, b); + if (op) { + return (str === "asc" ? 1 : -1); + } else if (!op) { + return (str === "asc" ? -1 : 1); + } else { + return 0; + } + }); + self.output(head.concat(body)); + return self; +} +},{"../../core/utils/each":31}],46:[function(require,module,exports){ +var each = require("../../core/utils/each"); +var createNullList = require('../utils/create-null-list'); +var append = require('./append'); +var appendRow = append.appendRow, + appendColumn = append.appendColumn; +module.exports = { + "updateColumn": updateColumn, + "updateRow": updateRow +}; +function updateColumn(q, input){ + var self = this, + index = (typeof q === 'number') ? q : this.data.output[0].indexOf(q); + if (index > -1) { + if (typeof input === "function") { + each(self.output(), function(row, i){ + var cell; + if (i > 0) { + cell = input.call(self, row[index], i, row); + if (typeof cell !== "undefined") { + self.data.output[i][index] = cell; + } + } + }); + } else if (!input || input instanceof Array) { + input = input || []; + if (input.length <= self.output().length - 1) { + input = input.concat( createNullList(self.output().length - 1 - input.length) ); + } + else { + each(input, function(value, i){ + if (self.data.output.length -1 < input.length) { + appendRow.call(self, String( self.data.output.length )); + } + }); + } + each(input, function(value, i){ + self.data.output[i+1][index] = value; + }); + } + } + return self; +} +function updateRow(q, input){ + var self = this, + index = (typeof q === 'number') ? q : this.selectColumn(0).indexOf(q); + if (index > -1) { + if (typeof input === "function") { + each(self.output()[index], function(value, i){ + var col = self.selectColumn(i), + cell = input.call(self, value, i, col); + if (typeof cell !== "undefined") { + self.data.output[index][i] = cell; + } + }); + } else if (!input || input instanceof Array) { + input = input || []; + if (input.length <= self.data.output[0].length - 1) { + input = input.concat( createNullList( self.data.output[0].length - 1 - input.length ) ); + } + else { + each(input, function(value, i){ + if (self.data.output[0].length -1 < input.length) { + appendColumn.call(self, String( self.data.output[0].length )); + } + }); + } + each(input, function(value, i){ + self.data.output[index][i+1] = value; + }); + } + } + return self; +} +},{"../../core/utils/each":31,"../utils/create-null-list":47,"./append":38}],47:[function(require,module,exports){ +module.exports = function(len){ + var list = new Array(); + for (i = 0; i < len; i++) { + list.push(null); + } + return list; +}; +},{}],48:[function(require,module,exports){ +module.exports = flatten; +function flatten(ob) { + var toReturn = {}; + for (var i in ob) { + if (!ob.hasOwnProperty(i)) continue; + if ((typeof ob[i]) == 'object' && ob[i] !== null) { + var flatObject = flatten(ob[i]); + for (var x in flatObject) { + if (!flatObject.hasOwnProperty(x)) continue; + toReturn[i + '.' + x] = flatObject[x]; + } + } else { + toReturn[i] = ob[i]; + } + } + return toReturn; +} +},{}],49:[function(require,module,exports){ +var each = require("../../core/utils/each"); +module.exports = function() { + var result = []; + var loop = function() { + var root = arguments[0]; + var args = Array.prototype.slice.call(arguments, 1); + var target = args.pop(); + if (args.length === 0) { + if (root instanceof Array) { + args = root; + } else if (typeof root === 'object') { + args.push(root); + } + } + each(args, function(el){ + if (target == "") { + if (typeof el == "number" || el == null) { + return result.push(el); + } + } + if (el[target] || el[target] === 0 || el[target] !== void 0) { + if (el[target] === null) { + return result.push(null); + } else { + return result.push(el[target]); + } + } else if (root[el]){ + if (root[el] instanceof Array) { + each(root[el], function(n, i) { + var splinter = [root[el]].concat(root[el][i]).concat(args.slice(1)).concat(target); + return loop.apply(this, splinter); + }); + } else { + if (root[el][target]) { + return result.push(root[el][target]); + } else { + return loop.apply(this, [root[el]].concat(args.splice(1)).concat(target)); + } + } + } else if (typeof root === 'object' && root instanceof Array === false && !root[target]) { + throw new Error("Target property does not exist", target); + } else { + return loop.apply(this, [el].concat(args.splice(1)).concat(target)); + } + return; + }); + if (result.length > 0) { + return result; + } + }; + return loop.apply(this, arguments); +} +},{"../../core/utils/each":31}],50:[function(require,module,exports){ +/*! + * ---------------------- + * C3.js Adapter + * ---------------------- + */ +var Dataviz = require('../dataviz'), + each = require('../../core/utils/each'), + extend = require('../../core/utils/extend'); +module.exports = function(){ + var dataTypes = { + 'singular' : ['gauge'], + 'categorical' : ['donut', 'pie'], + 'cat-interval' : ['area-step', 'step', 'bar', 'area', 'area-spline', 'spline', 'line'], + 'cat-ordinal' : ['bar', 'area', 'area-spline', 'spline', 'line', 'step', 'area-step'], + 'chronological' : ['area', 'area-spline', 'spline', 'line', 'bar', 'step', 'area-step'], + 'cat-chronological' : ['line', 'spline', 'area', 'area-spline', 'bar', 'step', 'area-step'] + }; + var charts = {}; + each(['gauge', 'donut', 'pie', 'bar', 'area', 'area-spline', 'spline', 'line', 'step', 'area-step'], function(type, index){ + charts[type] = { + render: function(){ + var setup = getSetupTemplate.call(this, type); + this.view._artifacts['c3'] = c3.generate(setup); + this.update(); + }, + update: function(){ + var self = this, cols = []; + if (type === 'gauge') { + self.view._artifacts['c3'].load({ + columns: [ [self.title(), self.data()[1][1]] ] + }) + } + else if (type === 'pie' || type === 'donut') { + self.view._artifacts['c3'].load({ + columns: self.dataset.data.output.slice(1) + }); + } + else { + if (this.dataType().indexOf('chron') > -1) { + cols.push(self.dataset.selectColumn(0)); + cols[0][0] = 'x'; + } + each(self.data()[0], function(c, i){ + if (i > 0) { + cols.push(self.dataset.selectColumn(i)); + } + }); + if (self.stacked()) { + self.view._artifacts['c3'].groups([self.labels()]); + } + self.view._artifacts['c3'].load({ + columns: cols + }); + } + }, + destroy: function(){ + _selfDestruct.call(this); + } + }; + }); + function getSetupTemplate(type){ + var setup = { + axis: {}, + bindto: this.el(), + data: { + columns: [] + }, + color: { + pattern: this.colors() + }, + size: { + height: this.height(), + width: this.width() + } + }; + setup['data']['type'] = type; + if (type === 'gauge') {} + else if (type === 'pie' || type === 'donut') { + setup[type] = { title: this.title() }; + } + else { + if (this.dataType().indexOf('chron') > -1) { + setup['data']['x'] = 'x'; + setup['axis']['x'] = { + type: 'timeseries', + tick: { + format: '%Y-%m-%d' + } + }; + } + else { + if (this.dataType() === 'cat-ordinal') { + setup['axis']['x'] = { + type: 'category', + categories: this.labels() + }; + } + } + if (this.title()) { + setup['axis']['y'] = { label: this.title() } + } + } + return extend(setup, this.chartOptions()); + } + function _selfDestruct(){ + if (this.view._artifacts['c3']) { + this.view._artifacts['c3'].destroy(); + this.view._artifacts['c3'] = null; + } + } + Dataviz.register('c3', charts, { capabilities: dataTypes }); +}; +},{"../../core/utils/each":31,"../../core/utils/extend":32,"../dataviz":54}],51:[function(require,module,exports){ +/*! + * ---------------------- + * Chart.js Adapter + * ---------------------- + */ +var Dataviz = require("../dataviz"), + each = require("../../core/utils/each"), + extend = require("../../core/utils/extend"); +module.exports = function(){ + if (typeof Chart !== "undefined") { + Chart.defaults.global.responsive = true; + } + var dataTypes = { + "categorical" : ["doughnut", "pie", "polar-area", "radar"], + "cat-interval" : ["bar", "line"], + "cat-ordinal" : ["bar", "line"], + "chronological" : ["line", "bar"], + "cat-chronological" : ["line", "bar"] + }; + var ChartNameMap = { + "radar": "Radar", + "polar-area": "PolarArea", + "pie": "Pie", + "doughnut": "Doughnut", + "line": "Line", + "bar": "Bar" + }; + var dataTransformers = { + 'doughnut': getCategoricalData, + 'pie': getCategoricalData, + 'polar-area': getCategoricalData, + 'radar': getSeriesData, + 'line': getSeriesData, + 'bar': getSeriesData + }; + function getCategoricalData(){ + var self = this, result = []; + each(self.dataset.selectColumn(0).slice(1), function(label, i){ + result.push({ + value: self.dataset.selectColumn(1).slice(1)[i], + color: self.colors()[+i], + hightlight: self.colors()[+i+9], + label: label + }); + }); + return result; + } + function getSeriesData(){ + var self = this, + labels, + result = { + labels: [], + datasets: [] + }; + labels = this.dataset.selectColumn(0).slice(1); + each(labels, function(l,i){ + if (l instanceof Date) { + result.labels.push((l.getMonth()+1) + "-" + l.getDate() + "-" + l.getFullYear()); + } else { + result.labels.push(l); + } + }) + each(self.dataset.selectRow(0).slice(1), function(label, i){ + var hex = { + r: hexToR(self.colors()[i]), + g: hexToG(self.colors()[i]), + b: hexToB(self.colors()[i]) + }; + result.datasets.push({ + label: label, + fillColor : "rgba(" + hex.r + "," + hex.g + "," + hex.b + ",0.2)", + strokeColor : "rgba(" + hex.r + "," + hex.g + "," + hex.b + ",1)", + pointColor : "rgba(" + hex.r + "," + hex.g + "," + hex.b + ",1)", + pointStrokeColor: "#fff", + pointHighlightFill: "#fff", + pointHighlightStroke: "rgba(" + hex.r + "," + hex.g + "," + hex.b + ",1)", + data: self.dataset.selectColumn(+i+1).slice(1) + }); + }); + return result; + } + var charts = {}; + each(["doughnut", "pie", "polar-area", "radar", "bar", "line"], function(type, index){ + charts[type] = { + initialize: function(){ + if (this.el().nodeName.toLowerCase() !== "canvas") { + var canvas = document.createElement('canvas'); + this.el().innerHTML = ""; + this.el().appendChild(canvas); + this.view._artifacts["ctx"] = canvas.getContext("2d"); + } + else { + this.view._artifacts["ctx"] = this.el().getContext("2d"); + } + if (this.height()) { + this.view._artifacts["ctx"].canvas.height = this.height(); + this.view._artifacts["ctx"].canvas.style.height = String(this.height() + "px"); + } + if (this.width()) { + this.view._artifacts["ctx"].canvas.width = this.width(); + this.view._artifacts["ctx"].canvas.style.width = String(this.width() + "px"); + } + return this; + }, + render: function(){ + var method = ChartNameMap[type], + opts = extend({}, this.chartOptions()), + data = dataTransformers[type].call(this); + if (this.view._artifacts["chartjs"]) { + this.view._artifacts["chartjs"].destroy(); + } + this.view._artifacts["chartjs"] = new Chart(this.view._artifacts["ctx"])[method](data, opts); + return this; + }, + destroy: function(){ + _selfDestruct.call(this); + } + }; + }); + function _selfDestruct(){ + if (this.view._artifacts["chartjs"]) { + this.view._artifacts["chartjs"].destroy(); + this.view._artifacts["chartjs"] = null; + } + } + function hexToR(h) {return parseInt((cutHex(h)).substring(0,2),16)} + function hexToG(h) {return parseInt((cutHex(h)).substring(2,4),16)} + function hexToB(h) {return parseInt((cutHex(h)).substring(4,6),16)} + function cutHex(h) {return (h.charAt(0)=="#") ? h.substring(1,7):h} + Dataviz.register("chartjs", charts, { capabilities: dataTypes }); +}; +},{"../../core/utils/each":31,"../../core/utils/extend":32,"../dataviz":54}],52:[function(require,module,exports){ +/*! + * ---------------------- + * Google Charts Adapter + * ---------------------- + */ +/* + TODO: + [ ] Build a more robust DataTable transformer + [ ] ^Expose date parser for google charts tooltips (#70) + [ ] ^Allow custom tooltips (#147) +*/ +var Dataviz = require("../dataviz"), + each = require("../../core/utils/each"), + extend = require("../../core/utils/extend"), + Keen = require("../../core"); +module.exports = function(){ + Keen.loaded = false; + var errorMapping = { + "Data column(s) for axis #0 cannot be of type string": "No results to visualize" + }; + var chartTypes = ['AreaChart', 'BarChart', 'ColumnChart', 'LineChart', 'PieChart', 'Table']; + var chartMap = {}; + var dataTypes = { + 'categorical': ['piechart', 'barchart', 'columnchart', 'table'], + 'cat-interval': ['columnchart', 'barchart', 'table'], + 'cat-ordinal': ['barchart', 'columnchart', 'areachart', 'linechart', 'table'], + 'chronological': ['areachart', 'linechart', 'table'], + 'cat-chronological': ['linechart', 'columnchart', 'barchart', 'areachart'], + 'nominal': ['table'], + 'extraction': ['table'] + }; + each(chartTypes, function (type) { + var name = type.toLowerCase(); + chartMap[name] = { + initialize: function(){ + }, + render: function(){ + if(typeof google === "undefined") { + this.error("The Google Charts library could not be loaded."); + return; + } + var self = this; + if (self.view._artifacts['googlechart']) { + this.destroy(); + } + self.view._artifacts['googlechart'] = self.view._artifacts['googlechart'] || new google.visualization[type](self.el()); + google.visualization.events.addListener(self.view._artifacts['googlechart'], 'error', function(stack){ + _handleErrors.call(self, stack); + }); + this.update(); + }, + update: function(){ + var options = _getDefaultAttributes.call(this, type); + extend(options, this.chartOptions(), this.attributes()); + options['isStacked'] = (this.stacked() || options['isStacked']); + this.view._artifacts['datatable'] = google.visualization.arrayToDataTable(this.data()); + if (this.view._artifacts['googlechart']) { + this.view._artifacts['googlechart'].draw(this.view._artifacts['datatable'], options); + } + }, + destroy: function(){ + if (this.view._artifacts['googlechart']) { + google.visualization.events.removeAllListeners(this.view._artifacts['googlechart']); + this.view._artifacts['googlechart'].clearChart(); + this.view._artifacts['googlechart'] = null; + this.view._artifacts['datatable'] = null; + } + } + }; + }); + Dataviz.register('google', chartMap, { + capabilities: dataTypes, + dependencies: [{ + type: 'script', + url: 'https://www.google.com/jsapi', + cb: function(done) { + if (typeof google === 'undefined'){ + this.trigger("error", "Problem loading Google Charts library. Please contact us!"); + done(); + } + else { + google.load('visualization', '1.1', { + packages: ['corechart', 'table'], + callback: function(){ + done(); + } + }); + } + } + }] + }); + function _handleErrors(stack){ + var message = errorMapping[stack['message']] || stack['message'] || 'An error occurred'; + this.error(message); + } + function _getDefaultAttributes(type){ + var output = {}; + switch (type.toLowerCase()) { + case "areachart": + output.lineWidth = 2; + output.hAxis = { + baselineColor: 'transparent', + gridlines: { color: 'transparent' } + }; + output.vAxis = { + viewWindow: { min: 0 } + }; + if (this.dataType() === "chronological" || this.dataType() === "cat-ordinal") { + output.legend = "none"; + output.chartArea = { + width: "85%" + }; + } + break; + case "barchart": + output.hAxis = { + viewWindow: { min: 0 } + }; + output.vAxis = { + baselineColor: 'transparent', + gridlines: { color: 'transparent' } + }; + if (this.dataType() === "chronological" || this.dataType() === "cat-ordinal") { + output.legend = "none"; + } + break; + case "columnchart": + output.hAxis = { + baselineColor: 'transparent', + gridlines: { color: 'transparent' } + }; + output.vAxis = { + viewWindow: { min: 0 } + }; + if (this.dataType() === "chronological" || this.dataType() === "cat-ordinal") { + output.legend = "none"; + output.chartArea = { + width: "85%" + }; + } + break; + case "linechart": + output.lineWidth = 2; + output.hAxis = { + baselineColor: 'transparent', + gridlines: { color: 'transparent' } + }; + output.vAxis = { + viewWindow: { min: 0 } + }; + if (this.dataType() === "chronological" || this.dataType() === "cat-ordinal") { + output.legend = "none"; + output.chartArea = { + width: "85%" + }; + } + break; + case "piechart": + output.sliceVisibilityThreshold = 0.01; + break; + case "table": + break; + } + return output; + } +}; +},{"../../core":19,"../../core/utils/each":31,"../../core/utils/extend":32,"../dataviz":54}],53:[function(require,module,exports){ +/*! +* ---------------------- +* Keen IO Adapter +* ---------------------- +*/ +var Keen = require("../../core"), + Dataviz = require("../dataviz"); +var clone = require("../../core/utils/clone"), + each = require("../../core/utils/each"), + extend = require("../../core/utils/extend"), + prettyNumber = require("../utils/prettyNumber"); +module.exports = function(){ + var Metric, Error, Spinner; + Keen.Error = { + defaults: { + backgroundColor : "", + borderRadius : "4px", + color : "#ccc", + display : "block", + fontFamily : "Helvetica Neue, Helvetica, Arial, sans-serif", + fontSize : "21px", + fontWeight : "light", + textAlign : "center" + } + }; + Keen.Spinner.defaults = { + height: 138, + lines: 10, + length: 8, + width: 3, + radius: 10, + corners: 1, + rotate: 0, + direction: 1, + color: '#4d4d4d', + speed: 1.67, + trail: 60, + shadow: false, + hwaccel: false, + className: 'keen-spinner', + zIndex: 2e9, + top: '50%', + left: '50%' + }; + var dataTypes = { + 'singular': ['metric'] + }; + Metric = { + initialize: function(){ + var css = document.createElement("style"), + bgDefault = "#49c5b1"; + css.id = "keen-widgets"; + css.type = "text/css"; + css.innerHTML = "\ + .keen-metric { \n background: " + bgDefault + "; \n border-radius: 4px; \n color: #fff; \n font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; \n padding: 10px 0; \n text-align: center; \n} \ + .keen-metric-value { \n display: block; \n font-size: 84px; \n font-weight: 700; \n line-height: 84px; \n} \ + .keen-metric-title { \n display: block; \n font-size: 24px; \n font-weight: 200; \n}"; + if (!document.getElementById(css.id)) { + document.body.appendChild(css); + } + }, + render: function(){ + var bgColor = (this.colors().length == 1) ? this.colors()[0] : "#49c5b1", + title = this.title() || "Result", + value = this.data()[1][1] || 0, + width = this.width(), + opts = this.chartOptions() || {}, + prefix = "", + suffix = ""; + var styles = { + 'width': (width) ? width + 'px' : 'auto' + }; + var formattedNum = value; + if ( typeof opts.prettyNumber === 'undefined' || opts.prettyNumber == true ) { + if ( !isNaN(parseInt(value)) ) { + formattedNum = prettyNumber(value); + } + } + if (opts['prefix']) { + prefix = '' + opts['prefix'] + ''; + } + if (opts['suffix']) { + suffix = '' + opts['suffix'] + ''; + } + this.el().innerHTML = '' + + '
' + + '' + prefix + formattedNum + suffix + '' + + '' + title + '' + + '
'; + } + }; + Error = { + initialize: function(){}, + render: function(text, style){ + var err, msg; + var defaultStyle = clone(Keen.Error.defaults); + var currentStyle = extend(defaultStyle, style); + err = document.createElement("div"); + err.className = "keen-error"; + each(currentStyle, function(value, key){ + err.style[key] = value; + }); + err.style.height = String(this.height() + "px"); + err.style.paddingTop = (this.height() / 2 - 15) + "px"; + err.style.width = String(this.width() + "px"); + msg = document.createElement("span"); + msg.innerHTML = text || "Yikes! An error occurred!"; + err.appendChild(msg); + this.el().innerHTML = ""; + this.el().appendChild(err); + }, + destroy: function(){ + this.el().innerHTML = ""; + } + }; + Spinner = { + initialize: function(){}, + render: function(){ + var spinner = document.createElement("div"); + var height = this.height() || Keen.Spinner.defaults.height; + spinner.className = "keen-loading"; + spinner.style.height = String(height + "px"); + spinner.style.position = "relative"; + spinner.style.width = String(this.width() + "px"); + this.el().innerHTML = ""; + this.el().appendChild(spinner); + this.view._artifacts.spinner = new Keen.Spinner(Keen.Spinner.defaults).spin(spinner); + }, + destroy: function(){ + this.view._artifacts.spinner.stop(); + this.view._artifacts.spinner = null; + } + }; + Keen.Dataviz.register('keen-io', { + 'metric': Metric, + 'error': Error, + 'spinner': Spinner + }, { + capabilities: dataTypes + }); +}; +},{"../../core":19,"../../core/utils/clone":30,"../../core/utils/each":31,"../../core/utils/extend":32,"../dataviz":54,"../utils/prettyNumber":93}],54:[function(require,module,exports){ +var clone = require('../core/utils/clone'), + each = require('../core/utils/each'), + extend = require('../core/utils/extend'), + loadScript = require('./utils/loadScript'), + loadStyle = require('./utils/loadStyle'); +var Keen = require('../core'); +var Emitter = require('../core/helpers/emitter-shim'); +var Dataset = require('../dataset'); +function Dataviz(){ + this.dataset = new Dataset(); + this.view = { + _prepared: false, + _initialized: false, + _rendered: false, + _artifacts: { /* state bin */ }, + adapter: { + library: undefined, + chartOptions: {}, + chartType: undefined, + defaultChartType: undefined, + dataType: undefined + }, + attributes: clone(Dataviz.defaults), + defaults: clone(Dataviz.defaults), + el: undefined, + loader: { library: 'keen-io', chartType: 'spinner' } + }; + Dataviz.visuals.push(this); +}; +extend(Dataviz, { + dataTypeMap: { + 'singular': { library: 'keen-io', chartType: 'metric' }, + 'categorical': { library: 'google', chartType: 'piechart' }, + 'cat-interval': { library: 'google', chartType: 'columnchart' }, + 'cat-ordinal': { library: 'google', chartType: 'barchart' }, + 'chronological': { library: 'google', chartType: 'areachart' }, + 'cat-chronological': { library: 'google', chartType: 'linechart' }, + 'extraction': { library: 'google', chartType: 'table' }, + 'nominal': { library: 'google', chartType: 'table' } + }, + defaults: { + colors: [ + /* teal red yellow purple orange mint blue green lavender */ + '#00bbde', '#fe6672', '#eeb058', '#8a8ad6', '#ff855c', '#00cfbb', '#5a9eed', '#73d483', '#c879bb', + '#0099b6', '#d74d58', '#cb9141', '#6b6bb6', '#d86945', '#00aa99', '#4281c9', '#57b566', '#ac5c9e', + '#27cceb', '#ff818b', '#f6bf71', '#9b9be1', '#ff9b79', '#26dfcd', '#73aff4', '#87e096', '#d88bcb' + ], + indexBy: 'timeframe.start', + stacked: false + }, + dependencies: { + loading: 0, + loaded: 0, + urls: {} + }, + libraries: {}, + visuals: [] +}); +Emitter(Dataviz); +Emitter(Dataviz.prototype); +Dataviz.register = function(name, methods, config){ + var self = this; + var loadHandler = function(st) { + st.loaded++; + if(st.loaded === st.loading) { + Keen.loaded = true; + Keen.trigger('ready'); + } + }; + Dataviz.libraries[name] = Dataviz.libraries[name] || {}; + each(methods, function(method, key){ + Dataviz.libraries[name][key] = method; + }); + if (config && config.capabilities) { + Dataviz.libraries[name]._defaults = Dataviz.libraries[name]._defaults || {}; + each(config.capabilities, function(typeSet, key){ + Dataviz.libraries[name]._defaults[key] = typeSet; + }); + } + if (config && config.dependencies) { + each(config.dependencies, function (dependency, index, collection) { + var status = Dataviz.dependencies; + if(!status.urls[dependency.url]) { + status.urls[dependency.url] = true; + status.loading++; + var method = dependency.type === 'script' ? loadScript : loadStyle; + method(dependency.url, function() { + if(dependency.cb) { + dependency.cb.call(self, function() { + loadHandler(status); + }); + } else { + loadHandler(status); + } + }); + } + }); + } +}; +Dataviz.find = function(target){ + if (!arguments.length) return Dataviz.visuals; + var el = target.nodeName ? target : document.querySelector(target), + match; + each(Dataviz.visuals, function(visual){ + if (el == visual.el()){ + match = visual; + return false; + } + }); + if (match) return match; +}; +module.exports = Dataviz; +},{"../core":19,"../core/helpers/emitter-shim":11,"../core/utils/clone":30,"../core/utils/each":31,"../core/utils/extend":32,"../dataset":36,"./utils/loadScript":91,"./utils/loadStyle":92}],55:[function(require,module,exports){ +var clone = require("../../core/utils/clone"), + extend = require("../../core/utils/extend"), + Dataviz = require("../dataviz"), + Request = require("../../core/request"); +module.exports = function(query, el, cfg) { + var DEFAULTS = clone(Dataviz.defaults), + visual = new Dataviz(), + request = new Request(this, [query]), + config = cfg ? clone(cfg) : {}; + if (config.chartType) { + visual.chartType(config.chartType); + delete config.chartType; + } + if (config.library) { + visual.library(config.library); + delete config.library; + } + if (config.chartOptions) { + visual.chartOptions(config.chartOptions); + delete config.chartOptions; + } + visual + .attributes(extend(DEFAULTS, config)) + .el(el) + .prepare(); + request.refresh(); + request.on("complete", function(){ + visual + .parseRequest(this) + .call(function(){ + if (config.labels) { + this.labels(config.labels); + } + }) + .render(); + }); + request.on("error", function(res){ + visual.error(res.message); + }); + return visual; +}; +},{"../../core/request":28,"../../core/utils/clone":30,"../../core/utils/extend":32,"../dataviz":54}],56:[function(require,module,exports){ +var Dataviz = require("../dataviz"), + extend = require("../../core/utils/extend") +module.exports = function(){ + var map = extend({}, Dataviz.dataTypeMap), + dataType = this.dataType(), + library = this.library(), + chartType = this.chartType() || this.defaultChartType(); + if (!library && map[dataType]) { + library = map[dataType].library; + } + if (library && !chartType && dataType) { + chartType = Dataviz.libraries[library]._defaults[dataType][0]; + } + if (library && !chartType && map[dataType]) { + chartType = map[dataType].chartType; + } + return (library && chartType) ? Dataviz.libraries[library][chartType] : {}; +}; +},{"../../core/utils/extend":32,"../dataviz":54}],57:[function(require,module,exports){ +var each = require("../../core/utils/each"), + Dataset = require("../../dataset"); +module.exports = { + "extraction": parseExtraction +}; +function parseExtraction(req){ + var data = (req.data instanceof Array ? req.data[0] : req.data), + names = req.queries[0].get("property_names") || [], + schema = { records: "result", select: true }; + if (names) { + schema.select = []; + each(names, function(p){ + schema.select.push({ path: p }); + }); + } + return new Dataset(data, schema); +} +},{"../../core/utils/each":31,"../../dataset":36}],58:[function(require,module,exports){ +module.exports = function(req){ + var analysis = req.queries[0].analysis.replace("_", " "), + collection = req.queries[0].get('event_collection'), + output; + output = analysis.replace( /\b./g, function(a){ + return a.toUpperCase(); + }); + if (collection) { + output += ' - ' + collection; + } + return output; +}; +},{}],59:[function(require,module,exports){ +module.exports = function(query){ + var isInterval = typeof query.params.interval === "string", + isGroupBy = typeof query.params.group_by === "string", + is2xGroupBy = query.params.group_by instanceof Array, + dataType; + if (!isGroupBy && !isInterval) { + dataType = 'singular'; + } + if (isGroupBy && !isInterval) { + dataType = 'categorical'; + } + if (isInterval && !isGroupBy) { + dataType = 'chronological'; + } + if (isInterval && isGroupBy) { + dataType = 'cat-chronological'; + } + if (!isInterval && is2xGroupBy) { + dataType = 'categorical'; + } + if (isInterval && is2xGroupBy) { + dataType = 'cat-chronological'; + } + if (query.analysis === "funnel") { + dataType = 'cat-ordinal'; + } + if (query.analysis === "extraction") { + dataType = 'extraction'; + } + if (query.analysis === "select_unique") { + dataType = 'nominal'; + } + return dataType; +}; +},{}],60:[function(require,module,exports){ +var extend = require('../core/utils/extend'), + Dataviz = require('./dataviz'); +extend(Dataviz.prototype, { + 'adapter' : require('./lib/adapter'), + 'attributes' : require('./lib/attributes'), + 'call' : require('./lib/call'), + 'chartOptions' : require('./lib/chartOptions'), + 'chartType' : require('./lib/chartType'), + 'colorMapping' : require('./lib/colorMapping'), + 'colors' : require('./lib/colors'), + 'data' : require('./lib/data'), + 'dataType' : require('./lib/dataType'), + 'defaultChartType' : require('./lib/defaultChartType'), + 'el' : require('./lib/el'), + 'height' : require('./lib/height'), + 'indexBy' : require('./lib/indexBy'), + 'labelMapping' : require('./lib/labelMapping'), + 'labels' : require('./lib/labels'), + 'library' : require('./lib/library'), + 'parseRawData' : require('./lib/parseRawData'), + 'parseRequest' : require('./lib/parseRequest'), + 'prepare' : require('./lib/prepare'), + 'sortGroups' : require('./lib/sortGroups'), + 'sortIntervals' : require('./lib/sortIntervals'), + 'stacked' : require('./lib/stacked'), + 'title' : require('./lib/title'), + 'width' : require('./lib/width') +}); +extend(Dataviz.prototype, { + 'destroy' : require('./lib/actions/destroy'), + 'error' : require('./lib/actions/error'), + 'initialize' : require('./lib/actions/initialize'), + 'render' : require('./lib/actions/render'), + 'update' : require('./lib/actions/update') +}); +module.exports = Dataviz; +},{"../core/utils/extend":32,"./dataviz":54,"./lib/actions/destroy":61,"./lib/actions/error":62,"./lib/actions/initialize":63,"./lib/actions/render":64,"./lib/actions/update":65,"./lib/adapter":66,"./lib/attributes":67,"./lib/call":68,"./lib/chartOptions":69,"./lib/chartType":70,"./lib/colorMapping":71,"./lib/colors":72,"./lib/data":73,"./lib/dataType":74,"./lib/defaultChartType":75,"./lib/el":76,"./lib/height":77,"./lib/indexBy":78,"./lib/labelMapping":79,"./lib/labels":80,"./lib/library":81,"./lib/parseRawData":82,"./lib/parseRequest":83,"./lib/prepare":84,"./lib/sortGroups":85,"./lib/sortIntervals":86,"./lib/stacked":87,"./lib/title":88,"./lib/width":89}],61:[function(require,module,exports){ +var getAdapterActions = require("../../helpers/getAdapterActions"); +module.exports = function(){ + var actions = getAdapterActions.call(this); + if (actions.destroy) { + actions.destroy.apply(this, arguments); + } + if (this.el()) { + this.el().innerHTML = ""; + } + this.view._prepared = false; + this.view._initialized = false; + this.view._rendered = false; + this.view._artifacts = {}; + return this; +}; +},{"../../helpers/getAdapterActions":56}],62:[function(require,module,exports){ +var getAdapterActions = require("../../helpers/getAdapterActions"), + Dataviz = require("../../dataviz"); +module.exports = function(){ + var actions = getAdapterActions.call(this); + if (actions['error']) { + actions['error'].apply(this, arguments); + } else { + Dataviz.libraries['keen-io']['error'].render.apply(this, arguments); + } + return this; +}; +},{"../../dataviz":54,"../../helpers/getAdapterActions":56}],63:[function(require,module,exports){ +var getAdapterActions = require("../../helpers/getAdapterActions"), + Dataviz = require("../../dataviz"); +module.exports = function(){ + var actions = getAdapterActions.call(this); + var loader = Dataviz.libraries[this.view.loader.library][this.view.loader.chartType]; + if (this.view._prepared) { + if (loader.destroy) loader.destroy.apply(this, arguments); + } else { + if (this.el()) this.el().innerHTML = ""; + } + if (actions.initialize) actions.initialize.apply(this, arguments); + this.view._initialized = true; + return this; +}; +},{"../../dataviz":54,"../../helpers/getAdapterActions":56}],64:[function(require,module,exports){ +var getAdapterActions = require("../../helpers/getAdapterActions"), + applyTransforms = require("../../utils/applyTransforms"); +module.exports = function(){ + var actions = getAdapterActions.call(this); + applyTransforms.call(this); + if (!this.view._initialized) { + this.initialize(); + } + if (this.el() && actions.render) { + actions.render.apply(this, arguments); + this.view._rendered = true; + } + return this; +}; +},{"../../helpers/getAdapterActions":56,"../../utils/applyTransforms":90}],65:[function(require,module,exports){ +var getAdapterActions = require("../../helpers/getAdapterActions"), + applyTransforms = require("../../utils/applyTransforms"); +module.exports = function(){ + var actions = getAdapterActions.call(this); + applyTransforms.call(this); + if (actions.update) { + actions.update.apply(this, arguments); + } else if (actions.render) { + this.render(); + } + return this; +}; +},{"../../helpers/getAdapterActions":56,"../../utils/applyTransforms":90}],66:[function(require,module,exports){ +var each = require("../../core/utils/each"); +module.exports = function(obj){ + if (!arguments.length) return this.view.adapter; + var self = this; + each(obj, function(prop, key){ + self.view.adapter[key] = (prop ? prop : null); + }); + return this; +}; +},{"../../core/utils/each":31}],67:[function(require,module,exports){ +var each = require("../../core/utils/each"); +var chartOptions = require("./chartOptions"); +module.exports = function(obj){ + if (!arguments.length) return this.view["attributes"]; + var self = this; + each(obj, function(prop, key){ + if (key === "chartOptions") { + chartOptions.call(self, prop); + } else { + self.view["attributes"][key] = prop; + } + }); + return this; +}; +},{"../../core/utils/each":31,"./chartOptions":69}],68:[function(require,module,exports){ +module.exports = function(fn){ + fn.call(this); + return this; +}; +},{}],69:[function(require,module,exports){ +var extend = require('../../core/utils/extend'); +module.exports = function(obj){ + if (!arguments.length) return this.view.adapter.chartOptions; + extend(this.view.adapter.chartOptions, obj); + return this; +}; +},{"../../core/utils/extend":32}],70:[function(require,module,exports){ +module.exports = function(str){ + if (!arguments.length) return this.view.adapter.chartType; + this.view.adapter.chartType = (str ? String(str) : null); + return this; +}; +},{}],71:[function(require,module,exports){ +var each = require("../../core/utils/each"); +module.exports = function(obj){ + if (!arguments.length) return this.view["attributes"].colorMapping; + this.view["attributes"].colorMapping = (obj ? obj : null); + colorMapping.call(this); + return this; +}; +function colorMapping(){ + var self = this, + schema = this.dataset.schema, + data = this.dataset.output(), + colorSet = this.view.defaults.colors.slice(), + colorMap = this.colorMapping(), + dt = this.dataType() || ""; + if (colorMap) { + if (dt.indexOf("chronological") > -1 || (schema.unpack && data[0].length > 2)) { + each(data[0].slice(1), function(label, i){ + var color = colorMap[label]; + if (color && colorSet[i] !== color) { + colorSet.splice(i, 0, color); + } + }); + } + else { + each(self.dataset.selectColumn(0).slice(1), function(label, i){ + var color = colorMap[label]; + if (color && colorSet[i] !== color) { + colorSet.splice(i, 0, color); + } + }); + } + self.view.attributes.colors = colorSet; + } +} +},{"../../core/utils/each":31}],72:[function(require,module,exports){ +module.exports = function(arr){ + if (!arguments.length) return this.view["attributes"].colors; + this.view["attributes"].colors = (arr instanceof Array ? arr : null); + this.view.defaults.colors = (arr instanceof Array ? arr : null); + return this; +}; +},{}],73:[function(require,module,exports){ +var Dataset = require("../../dataset"), + Request = require("../../core/request"); +module.exports = function(data){ + if (!arguments.length) return this.dataset.output(); + if (data instanceof Dataset) { + this.dataset = data; + } else if (data instanceof Request) { + this.parseRequest(data); + } else { + this.parseRawData(data); + } + return this; +}; +},{"../../core/request":28,"../../dataset":36}],74:[function(require,module,exports){ +module.exports = function(str){ + if (!arguments.length) return this.view.adapter.dataType; + this.view.adapter.dataType = (str ? String(str) : null); + return this; +}; +},{}],75:[function(require,module,exports){ +module.exports = function(str){ + if (!arguments.length) return this.view.adapter.defaultChartType; + this.view.adapter.defaultChartType = (str ? String(str) : null); + return this; +}; +},{}],76:[function(require,module,exports){ +module.exports = function(el){ + if (!arguments.length) return this.view.el; + this.view.el = el; + return this; +}; +},{}],77:[function(require,module,exports){ +module.exports = function(num){ + if (!arguments.length) return this.view["attributes"]["height"]; + this.view["attributes"]["height"] = (!isNaN(parseInt(num)) ? parseInt(num) : null); + return this; +}; +},{}],78:[function(require,module,exports){ +var Dataset = require("../../dataset"), + Dataviz = require("../dataviz"), + each = require("../../core/utils/each"); +module.exports = function(str){ + if (!arguments.length) return this.view["attributes"].indexBy; + this.view["attributes"].indexBy = (str ? String(str) : Dataviz.defaults.indexBy); + indexBy.call(this); + return this; +}; +function indexBy(){ + var self = this, + root = this.dataset.meta.schema || this.dataset.meta.unpack, + newOrder = this.indexBy().split(".").join(Dataset.defaults.delimeter); + each(root, function(def, i){ + if (i === "select" && def instanceof Array) { + each(def, function(c, j){ + if (c.path.indexOf("timeframe -> ") > -1) { + self.dataset.meta.schema[i][j].path = newOrder; + } + }); + } + else if (i === "unpack" && typeof def === "object") { + self.dataset.meta.schema[i]['index'].path = newOrder; + } + }); + this.dataset.parse(); +} +},{"../../core/utils/each":31,"../../dataset":36,"../dataviz":54}],79:[function(require,module,exports){ +var each = require("../../core/utils/each"); +module.exports = function(obj){ + if (!arguments.length) return this.view["attributes"].labelMapping; + this.view["attributes"].labelMapping = (obj ? obj : null); + applyLabelMapping.call(this); + return this; +}; +function applyLabelMapping(){ + var self = this, + labelMap = this.labelMapping(), + schema = this.dataset.schema() || {}, + dt = this.dataType() || ""; + if (labelMap) { + if (dt.indexOf("chronological") > -1 || (schema.unpack && self.dataset.output()[0].length > 2)) { + each(self.dataset.output()[0], function(c, i){ + if (i > 0) { + self.dataset.data.output[0][i] = labelMap[c] || c; + } + }); + } + else if (schema.select && self.dataset.output()[0].length === 2) { + self.dataset.updateColumn(0, function(c, i){ + return labelMap[c] || c; + }); + } + } +} +},{"../../core/utils/each":31}],80:[function(require,module,exports){ +var each = require('../../core/utils/each'); +module.exports = function(arr){ + if (!arguments.length) { + if (!this.view['attributes'].labels || !this.view['attributes'].labels.length) { + return getLabels.call(this); + } + else { + return this.view['attributes'].labels; + } + } + else { + this.view['attributes'].labels = (arr instanceof Array ? arr : null); + setLabels.call(this); + return this; + } +}; +function setLabels(){ + var self = this, + labelSet = this.labels() || null, + schema = this.dataset.schema() || {}, + data = this.dataset.output(), + dt = this.dataType() || ''; + if (labelSet) { + if (dt.indexOf('chronological') > -1 || (schema.unpack && data[0].length > 2)) { + each(data[0], function(cell,i){ + if (i > 0 && labelSet[i-1]) { + self.dataset.data.output[0][i] = labelSet[i-1]; + } + }); + } + else { + each(data, function(row,i){ + if (i > 0 && labelSet[i-1]) { + self.dataset.data.output[i][0] = labelSet[i-1]; + } + }); + } + } +} +function getLabels(){ + var schema = this.dataset.schema() || {}, + data = this.dataset.output(), + dt = this.dataType() || '', + labels; + if (dt.indexOf('chron') > -1 || (schema.unpack && data[0].length > 2)) { + labels = this.dataset.selectRow(0).slice(1); + } + else { + labels = this.dataset.selectColumn(0).slice(1); + } + return labels; +} +},{"../../core/utils/each":31}],81:[function(require,module,exports){ +module.exports = function(str){ + if (!arguments.length) return this.view.adapter.library; + this.view.adapter.library = (str ? String(str) : null); + return this; +}; +},{}],82:[function(require,module,exports){ +var Dataviz = require('../dataviz'), + Dataset = require('../../dataset'); +var each = require('../../core/utils/each'); +module.exports = function(raw){ + this.dataset = parseRawData.call(this, raw); + return this; +}; +function parseRawData(response){ + var self = this, + schema = {}, + indexBy, + delimeter, + indexTarget, + labelSet, + labelMap, + dataType, + dataset; + indexBy = self.indexBy() ? self.indexBy() : Dataviz.defaults.indexBy; + delimeter = Dataset.defaults.delimeter; + indexTarget = indexBy.split('.').join(delimeter); + labelSet = self.labels() || null; + labelMap = self.labelMapping() || null; + if (typeof response.result == 'number'){ + dataType = 'singular'; + schema = { + records: '', + select: [{ + path: 'result', + type: 'string', + label: 'Metric' + }] + } + } + if (response.result instanceof Array && response.result.length > 0){ + if (response.result[0].timeframe && (typeof response.result[0].value == 'number' || response.result[0].value == null)) { + dataType = 'chronological'; + schema = { + records: 'result', + select: [ + { + path: indexTarget, + type: 'date' + }, + { + path: 'value', + type: 'number' + } + ] + } + } + if (typeof response.result[0].result == 'number'){ + dataType = 'categorical'; + schema = { + records: 'result', + select: [] + }; + for (var key in response.result[0]){ + if (response.result[0].hasOwnProperty(key) && key !== 'result'){ + schema.select.push({ + path: key, + type: 'string' + }); + break; + } + } + schema.select.push({ + path: 'result', + type: 'number' + }); + } + if (response.result[0].value instanceof Array){ + dataType = 'cat-chronological'; + schema = { + records: 'result', + unpack: { + index: { + path: indexTarget, + type: 'date' + }, + value: { + path: 'value -> result', + type: 'number' + } + } + } + for (var key in response.result[0].value[0]){ + if (response.result[0].value[0].hasOwnProperty(key) && key !== 'result'){ + schema.unpack.label = { + path: 'value -> ' + key, + type: 'string' + } + break; + } + } + } + if (typeof response.result[0] == 'number'){ + dataType = 'cat-ordinal'; + schema = { + records: '', + unpack: { + index: { + path: 'steps -> event_collection', + type: 'string' + }, + value: { + path: 'result -> ', + type: 'number' + } + } + } + } + if (typeof response.result[0] == 'string'){ + dataType = 'nominal'; + dataset = new Dataset(); + dataset.appendColumn('unique values', []); + each(response.result, function(result, i){ + dataset.appendRow(result); + }); + } + if (dataType === void 0) { + dataType = 'extraction'; + schema = { records: 'result', select: true }; + } + } + dataset = dataset instanceof Dataset ? dataset : new Dataset(response, schema); + if (dataType) { + self.dataType(dataType); + } + return dataset; +} +},{"../../core/utils/each":31,"../../dataset":36,"../dataviz":54}],83:[function(require,module,exports){ +var getDatasetSchemas = require("../helpers/getDatasetSchemas"), + getDefaultTitle = require("../helpers/getDefaultTitle"), + getQueryDataType = require("../helpers/getQueryDataType"); +var Dataset = require("../../dataset"), + parseRawData = require("./parseRawData"); +module.exports = function(req){ + var dataType = getQueryDataType(req.queries[0]); + if (dataType === "extraction") { + this.dataset = getDatasetSchemas.extraction(req); + } + else { + this.parseRawData(req.data instanceof Array ? req.data[0] : req.data); + } + this.dataType(dataType); + this.view.defaults.title = getDefaultTitle.call(this, req); + if (!this.title()) { + this.title(this.view.defaults.title); + } + return this; +}; +},{"../../dataset":36,"../helpers/getDatasetSchemas":57,"../helpers/getDefaultTitle":58,"../helpers/getQueryDataType":59,"./parseRawData":82}],84:[function(require,module,exports){ +var Dataviz = require("../dataviz"); +module.exports = function(){ + var loader; + if (this.view._rendered) { + this.destroy(); + } + if (this.el()) { + this.el().innerHTML = ""; + loader = Dataviz.libraries[this.view.loader.library][this.view.loader.chartType]; + if (loader.initialize) { + loader.initialize.apply(this, arguments); + } + if (loader.render) { + loader.render.apply(this, arguments); + } + this.view._prepared = true; + } + return this; +}; +},{"../dataviz":54}],85:[function(require,module,exports){ +module.exports = function(str){ + if (!arguments.length) return this.view["attributes"].sortGroups; + this.view["attributes"].sortGroups = (str ? String(str) : null); + runSortGroups.call(this); + return this; +}; +function runSortGroups(){ + var dt = this.dataType(); + if (!this.sortGroups()) return; + if ((dt && dt.indexOf("chronological") > -1) || this.data()[0].length > 2) { + this.dataset.sortColumns(this.sortGroups(), this.dataset.getColumnSum); + } + else if (dt && (dt.indexOf("cat-") > -1 || dt.indexOf("categorical") > -1)) { + this.dataset.sortRows(this.sortGroups(), this.dataset.getRowSum); + } + return; +} +},{}],86:[function(require,module,exports){ +module.exports = function(str){ + if (!arguments.length) return this.view["attributes"].sortIntervals; + this.view["attributes"].sortIntervals = (str ? String(str) : null); + runSortIntervals.call(this); + return this; +}; +function runSortIntervals(){ + if (!this.sortIntervals()) return; + this.dataset.sortRows(this.sortIntervals()); + return; +} +},{}],87:[function(require,module,exports){ +module.exports = function(bool){ + if (!arguments.length) return this.view['attributes']['stacked']; + this.view['attributes']['stacked'] = bool ? true : false; + return this; +}; +},{}],88:[function(require,module,exports){ +module.exports = function(str){ + if (!arguments.length) return this.view["attributes"]["title"]; + this.view["attributes"]["title"] = (str ? String(str) : null); + return this; +}; +},{}],89:[function(require,module,exports){ +module.exports = function(num){ + if (!arguments.length) return this.view["attributes"]["width"]; + this.view["attributes"]["width"] = (!isNaN(parseInt(num)) ? parseInt(num) : null); + return this; +}; +},{}],90:[function(require,module,exports){ +module.exports = function(){ + if (this.labelMapping()) { + this.labelMapping(this.labelMapping()); + } + if (this.colorMapping()) { + this.colorMapping(this.colorMapping()); + } + if (this.sortGroups()) { + this.sortGroups(this.sortGroups()); + } + if (this.sortIntervals()) { + this.sortIntervals(this.sortIntervals()); + } +}; +},{}],91:[function(require,module,exports){ +module.exports = function(url, cb) { + var doc = document; + var handler; + var head = doc.head || doc.getElementsByTagName("head"); + setTimeout(function () { + if ('item' in head) { + if (!head[0]) { + setTimeout(arguments.callee, 25); + return; + } + head = head[0]; + } + var script = doc.createElement("script"), + scriptdone = false; + script.onload = script.onreadystatechange = function () { + if ((script.readyState && script.readyState !== "complete" && script.readyState !== "loaded") || scriptdone) { + return false; + } + script.onload = script.onreadystatechange = null; + scriptdone = true; + cb(); + }; + script.src = url; + head.insertBefore(script, head.firstChild); + }, 0); + if (doc.readyState === null && doc.addEventListener) { + doc.readyState = "loading"; + doc.addEventListener("DOMContentLoaded", handler = function () { + doc.removeEventListener("DOMContentLoaded", handler, false); + doc.readyState = "complete"; + }, false); + } +}; +},{}],92:[function(require,module,exports){ +module.exports = function(url, cb) { + var link = document.createElement('link'); + link.setAttribute('rel', 'stylesheet'); + link.type = 'text/css'; + link.href = url; + cb(); + document.head.appendChild(link); +}; +},{}],93:[function(require,module,exports){ +module.exports = function(_input) { + var input = Number(_input), + sciNo = input.toPrecision(3), + prefix = "", + suffixes = ["", "k", "M", "B", "T"]; + if (Number(sciNo) == input && String(input).length <= 4) { + return String(input); + } + if(input >= 1 || input <= -1) { + if(input < 0){ + input = -input; + prefix = "-"; + } + return prefix + recurse(input, 0); + } else { + return input.toPrecision(3); + } + function recurse(input, iteration) { + var input = String(input); + var split = input.split("."); + if(split.length > 1) { + input = split[0]; + var rhs = split[1]; + if (input.length == 2 && rhs.length > 0) { + if (rhs.length > 0) { + input = input + "." + rhs.charAt(0); + } + else { + input += "0"; + } + } + else if (input.length == 1 && rhs.length > 0) { + input = input + "." + rhs.charAt(0); + if(rhs.length > 1) { + input += rhs.charAt(1); + } + else { + input += "0"; + } + } + } + var numNumerals = input.length; + if (input.split(".").length > 1) { + numNumerals--; + } + if(numNumerals <= 3) { + return String(input) + suffixes[iteration]; + } + else { + return recurse(Number(input) / 1000, iteration + 1); + } + } +}; +},{}],94:[function(require,module,exports){ +(function (global){ +;(function (f) { + if (typeof define === "function" && define.amd) { + define("keen", [], function(){ return f(); }); + } + if (typeof exports === "object" && typeof module !== "undefined") { + module.exports = f(); + } + var g = null; + if (typeof window !== "undefined") { + g = window; + } else if (typeof global !== "undefined") { + g = global; + } else if (typeof self !== "undefined") { + g = self; + } + if (g) { + g.Keen = f(); + } +})(function() { + "use strict"; + var Keen = require("./core"), + extend = require("./core/utils/extend"); + extend(Keen.prototype, { + "addEvent" : require("./core/lib/addEvent"), + "addEvents" : require("./core/lib/addEvents"), + "setGlobalProperties" : require("./core/lib/setGlobalProperties"), + "trackExternalLink" : require("./core/lib/trackExternalLink"), + "get" : require("./core/lib/get"), + "post" : require("./core/lib/post"), + "put" : require("./core/lib/post"), + "run" : require("./core/lib/run"), + "draw" : require("./dataviz/extensions/draw") + }); + Keen.Query = require("./core/query"); + Keen.Request = require("./core/request"); + Keen.Dataset = require("./dataset"); + Keen.Dataviz = require("./dataviz"); + Keen.Base64 = require("./core/utils/base64"); + Keen.Spinner = require("spin.js"); + Keen.utils = { + "domready" : require("domready"), + "each" : require("./core/utils/each"), + "extend" : extend, + "parseParams" : require("./core/utils/parseParams"), + "prettyNumber" : require("./dataviz/utils/prettyNumber") + }; + require("./dataviz/adapters/keen-io")(); + require("./dataviz/adapters/google")(); + require("./dataviz/adapters/c3")(); + require("./dataviz/adapters/chartjs")(); + if (Keen.loaded) { + setTimeout(function(){ + Keen.utils.domready(function(){ + Keen.emit("ready"); + }); + }, 0); + } + require("./core/async")(); + module.exports = Keen; + return Keen; +}); +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"./core":19,"./core/async":10,"./core/lib/addEvent":20,"./core/lib/addEvents":21,"./core/lib/get":22,"./core/lib/post":23,"./core/lib/run":24,"./core/lib/setGlobalProperties":25,"./core/lib/trackExternalLink":26,"./core/query":27,"./core/request":28,"./core/utils/base64":29,"./core/utils/each":31,"./core/utils/extend":32,"./core/utils/parseParams":33,"./dataset":36,"./dataviz":60,"./dataviz/adapters/c3":50,"./dataviz/adapters/chartjs":51,"./dataviz/adapters/google":52,"./dataviz/adapters/keen-io":53,"./dataviz/extensions/draw":55,"./dataviz/utils/prettyNumber":93,"domready":5,"spin.js":6}]},{},[94]); diff --git a/dist/keen.min.js b/dist/keen.min.js new file mode 100644 index 0000000..0120134 --- /dev/null +++ b/dist/keen.min.js @@ -0,0 +1,29 @@ +(function e(b,g,d){function c(n,k){if(!g[n]){if(!b[n]){var j=typeof require=="function"&&require;if(!k&&j){return j(n,!0)}if(a){return a(n,!0)}var m=new Error("Cannot find module '"+n+"'");throw m.code="MODULE_NOT_FOUND",m}var h=g[n]={exports:{}};b[n][0].call(h.exports,function(l){var o=b[n][1][l];return c(o?o:l)},h,h.exports,e,b,g,d)}return g[n].exports}var a=typeof require=="function"&&require;for(var f=0;f>1)+"px"})}for(;v',v)}n.addRule(".spin-vml","behavior:url(#default#VML)");f.prototype.lines=function(x,w){var v=w.scale*(w.length+w.width),D=w.scale*2*v;function C(){return k(u("group",{coordsize:D+" "+D,coordorigin:-v+" "+-v}),{width:D,height:D})}var y=-(w.width+w.length)*w.scale*2+"px",B=k(C(),{position:"absolute",top:y,left:y}),A;function z(F,E,G){m(B,m(k(C(),{rotation:360/w.lines*F+"deg",left:~~E}),m(k(u("roundrect",{arcsize:w.corners}),{width:v,height:w.scale*w.width,left:w.scale*w.radius,top:-w.scale*w.width>>1,filter:G}),u("fill",{color:r(w.color,F),opacity:w.opacity}),u("stroke",{opacity:0}))))}if(w.shadow){for(A=1;A<=w.lines;A++){z(A,-2,"progid:DXImageTransform.Microsoft.Blur(pixelradius=2,makeshadow=1,shadowopacity=.3)")}}for(A=1;A<=w.lines;A++){z(A)}return m(x,B)};f.prototype.opacity=function(w,v,y,x){var z=w.firstChild;x=x.shadow&&x.lines||0;if(z&&v+x0){return 2000}}return 16000}},{}],16:[function(b,c,a){c.exports=function(){var d="undefined"==typeof window?this:window;if(d.XMLHttpRequest&&("file:"!=d.location.protocol||!d.ActiveXObject)){return new XMLHttpRequest}else{try{return new ActiveXObject("Microsoft.XMLHTTP")}catch(f){}try{return new ActiveXObject("Msxml2.XMLHTTP.6.0")}catch(f){}try{return new ActiveXObject("Msxml2.XMLHTTP.3.0")}catch(f){}try{return new ActiveXObject("Msxml2.XMLHTTP")}catch(f){}}return false}},{}],17:[function(b,c,a){c.exports=function(h,g,j){var f=j||function(){};if(g&&!g.ok){var d=g.body&&g.body.error_code;h=new Error(d?g.body.message:"Unknown error occurred");h.code=d?g.body.error_code:"UnknownError"}if(h){f(h,null)}else{f(null,g.body)}return}},{}],18:[function(f,b,g){var o=f("superagent");var m=f("../utils/each"),a=f("./get-xhr-object");b.exports=function(p,q){return function(r){var s=r.constructor.prototype.end;if("undefined"===typeof window){return}r.requestType=r.requestType||{};r.requestType.type=p;r.requestType.options=r.requestType.options||{async:true,success:{responseText:'{ "created": true }',status:201},error:{responseText:'{ "error_code": "ERROR", "message": "Request failed" }',status:404}};if(q){if("boolean"===typeof q.async){r.requestType.options.async=q.async}if(q.success){extend(r.requestType.options.success,q.success)}if(q.error){extend(r.requestType.options.error,q.error)}}r.end=function(v){var u=this,t=(this.requestType)?this.requestType.type:"xhr",x,w;if(("GET"!==u.method||"xhr"===t)&&u.requestType.options.async){s.call(u,v);return}x=u._query.join("&");w=u._timeout;u._callback=v||noop;if(w&&!u._timer){u._timer=setTimeout(function(){h.call(u)},w)}if(x){x=o.serializeObject(x);u.url+=~u.url.indexOf("?")?"&"+x:"?"+x}u.emit("request",u);if(!u.requestType.options.async){l.call(u)}else{if("jsonp"===t){k.call(u)}else{if("beacon"===t){j.call(u)}}}return u};return r}};function l(){var p=a();if(p){p.open("GET",this.url,false);p.send(null)}return this}function k(){var q=this,u=new Date().getTime(),p=document.createElement("script"),t=document.getElementsByTagName("head")[0],v="keenJSONPCallback",r=false;v+=u;while(v in window){v+="a"}window[v]=function(w){if(r===true){return}r=true;d.call(q,w);s()};p.src=q.url+"&jsonp="+v;t.appendChild(p);p.onreadystatechange=function(){if(r===false&&q.readyState==="loaded"){r=true;c.call(q);s()}};p.onerror=function(){if(r===false){r=true;c.call(q);s()}};function s(){window[v]=undefined;try{delete window[v]}catch(w){}t.removeChild(p)}}function j(){var q=this,p=document.createElement("img"),r=false;p.onload=function(){r=true;if("naturalHeight" in this){if(this.naturalHeight+this.naturalWidth===0){this.onerror();return}}else{if(this.width+this.height===0){this.onerror();return}}d.call(q)};p.onerror=function(){r=true;c.call(q)};p.src=q.url+"&c=clv1"}function d(q){var r=this.requestType.options["success"],p="";n.call(this,r);if(q){try{p=JSON.stringify(q)}catch(s){}}else{p=r.responseText}this.xhr.responseText=p;this.xhr.status=r.status;this.emit("end")}function c(){var p=this.requestType.options["error"];n.call(this,p);this.xhr.responseText=p.responseText;this.xhr.status=p.status;this.emit("end")}function h(){this.aborted=true;this.clearTimeout();this.emit("abort")}function n(p){this.xhr={getAllResponseHeaders:function(){return""},getResponseHeader:function(){return"application/json"},responseText:p.responseText,status:p.status};return this}},{"../utils/each":31,"./get-xhr-object":16,superagent:7}],19:[function(d,f,c){var b="undefined"!==typeof window?window:this;var h=b.Keen;var g=d("./helpers/emitter-shim");function a(j){this.configure(j||{});a.trigger("client",this)}a.debug=false;a.enabled=true;a.loaded=true;a.version="3.2.6";g(a);g(a.prototype);a.prototype.configure=function(j){var k=j||{};if(k.host){k.host.replace(/.*?:\/\//g,"")}if(k.protocol&&k.protocol==="auto"){k.protocol=location.protocol.replace(/:/g,"")}this.config={projectId:k.projectId,writeKey:k.writeKey,readKey:k.readKey,masterKey:k.masterKey,requestType:k.requestType||"jsonp",host:k.host||"api.keen.io/3.0",protocol:k.protocol||"https",globalProperties:null};if(a.debug){this.on("error",a.log)}this.trigger("ready")};a.prototype.projectId=function(j){if(!arguments.length){return this.config.projectId}this.config.projectId=(j?String(j):null);return this};a.prototype.masterKey=function(j){if(!arguments.length){return this.config.masterKey}this.config.masterKey=(j?String(j):null);return this};a.prototype.readKey=function(j){if(!arguments.length){return this.config.readKey}this.config.readKey=(j?String(j):null);return this};a.prototype.writeKey=function(j){if(!arguments.length){return this.config.writeKey}this.config.writeKey=(j?String(j):null);return this};a.prototype.url=function(j){if(!this.projectId()){this.trigger("error","Client is missing projectId property");return}return this.config.protocol+"://"+this.config.host+"/projects/"+this.projectId()+j};a.log=function(j){if(a.debug&&typeof console=="object"){console.log("[Keen IO]",j)}};a.noConflict=function(){b.Keen=h;return a};a.ready=function(j){if(a.loaded){j()}else{a.once("ready",j)}};f.exports=a},{"./helpers/emitter-shim":11}],20:[function(f,c,h){var o=f("JSON2");var g=f("superagent");var j=f("../index");var k=f("../utils/base64"),n=f("../utils/each"),p=f("../helpers/get-context"),d=f("../helpers/get-query-string"),b=f("../helpers/get-url-max-length"),a=f("../helpers/get-xhr-object"),l=f("../helpers/superagent-request-types"),q=f("../helpers/superagent-handle-response");c.exports=function(y,B,C,u){var D=this,w=this.url("/events/"+encodeURIComponent(y)),r=this.config.requestType,v={},t=C,s,A;s=("boolean"===typeof u)?u:true;if(!j.enabled){z.call(D,"Keen.enabled = false");return}if(!D.projectId()){z.call(D,"Missing projectId property");return}if(!D.writeKey()){z.call(D,"Missing writeKey property");return}if(!y||typeof y!=="string"){z.call(D,"Collection name must be a string");return}if(D.config.globalProperties){v=D.config.globalProperties(y)}n(B,function(F,E){v[E]=F});if(!a()&&"xhr"===r){r="jsonp"}if("xhr"!==r||!s){A=m.call(D,w,v)}if(A&&p()==="browser"){g.get(A).use(l(r,{async:s})).end(x)}else{if(a()||p()==="server"){g.post(w).set("Content-Type","application/json").set("Authorization",D.writeKey()).send(v).end(x)}else{D.trigger("error","Request not sent: URL length exceeds current browser limit, and XHR (POST) is not supported.")}}function x(F,E){q(F,E,t);t=C=null}function z(F){var E="Event not recorded: "+F;D.trigger("error",E);if(t){t.call(D,E,null);t=C=null}}return};function m(r,s){r+=d({api_key:this.writeKey(),data:k.encode(o.stringify(s)),modified:new Date().getTime()});return(r.length2){r.call(o,"Incorrect arguments provided to #addEvents method");return}if(typeof q!=="object"||q instanceof Array){r.call(o,"Request payload must be an object");return}if(o.config.globalProperties){j(q,function(t,u){j(t,function(v,w){var x=o.config.globalProperties(u);j(v,function(z,y){x[y]=z});p[u].push(x)})})}else{p=q}if(a()||k()==="server"){d.post(n).set("Content-Type","application/json").set("Authorization",o.writeKey()).send(p).end(function(u,t){l(u,t,m);m=s=null})}else{o.trigger("error","Events not recorded: XHR support is required for batch upload")}function r(u){var t="Events not recorded: "+u;o.trigger("error",t);if(m){m.call(o,t,null);m=s=null}}return}},{"../helpers/get-context":12,"../helpers/get-xhr-object":16,"../helpers/superagent-handle-response":17,"../helpers/superagent-request-types":18,"../index":19,"../utils/each":31,superagent:7}],22:[function(d,f,c){var h=d("superagent");var b=d("../helpers/get-query-string"),g=d("../helpers/superagent-handle-response"),a=d("../helpers/superagent-request-types");f.exports=function(k,n,m,o){var j=this.config.requestType,l=n||{};if(j==="beacon"){j="jsonp"}l.api_key=l.api_key||m;h.get(k+b(l)).use(a(j)).end(function(q,p){g(q,p,o);o=null})}},{"../helpers/get-query-string":13,"../helpers/superagent-handle-response":17,"../helpers/superagent-request-types":18,superagent:7}],23:[function(b,c,a){var f=b("superagent");var d=b("../helpers/superagent-handle-response");c.exports=function(g,j,h,k){f.post(g).set("Content-Type","application/json").set("Authorization",h).send(j||{}).end(function(m,l){d(m,l,k);k=null})}},{"../helpers/superagent-handle-response":17,superagent:7}],24:[function(b,d,a){var c=b("../request");d.exports=function(j,k){var g=[],f=k,h;if(j instanceof Array){g=j}else{g.push(j)}h=new c(this,g,f).refresh();f=k=null;return h}},{"../request":28}],25:[function(b,c,a){c.exports=function(d){if(d&&typeof(d)=="function"){this.config.globalProperties=d}else{this.trigger("error","Invalid value for global properties: "+d)}}},{}],26:[function(b,c,a){var d=b("./addEvent");c.exports=function(l,f,o,m,n){var p=l,k=(p.currentTarget)?p.currentTarget:(p.srcElement||p.target),g=m||500,h=false,r="",q,j;if(k.getAttribute!==void 0){r=k.getAttribute("target")}else{if(k.target){r=k.target}}if((r=="_blank"||r=="blank")&&!p.metaKey){j=window.open("about:blank");j.document.location=k.href}if(k.nodeName==="A"){q=function(){if(!h&&!p.metaKey&&(r!=="_blank"&&r!=="blank")){h=true;window.location=k.href}}}else{if(k.nodeName==="FORM"){q=function(){if(!h){h=true;k.submit()}}}else{this.trigger("error","#trackExternalLink method not attached to an
or DOM element")}}if(n){q=function(){if(!h){h=true;n()}}}d.call(this,f,o,q);setTimeout(q,g);if(!p.metaKey){return false}}},{"./addEvent":20}],27:[function(c,a,d){var k=c("./utils/each"),h=c("./utils/extend"),g=c("./helpers/get-timezone-offset"),b=c("./helpers/get-query-string");var j=c("./helpers/emitter-shim");function f(){this.configure.apply(this,arguments)}j(f.prototype);f.prototype.configure=function(l,m){this.analysis=l;this.params=this.params||{};this.set(m);if(this.params.timezone===void 0){this.params.timezone=g()}return this};f.prototype.set=function(m){var l=this;k(m,function(o,n){var p=n,q=o;if(n.match(new RegExp("[A-Z]"))){p=n.replace(/([A-Z])/g,function(r){return"_"+r.toLowerCase()})}l.params[p]=q;if(q instanceof Array){k(q,function(s,r){if(s instanceof Array==false&&typeof s==="object"){k(s,function(u,t){if(t.match(new RegExp("[A-Z]"))){var v=t.replace(/([A-Z])/g,function(w){return"_"+w.toLowerCase()});delete l.params[p][r][t];l.params[p][r][v]=u}})}})}});return l};f.prototype.get=function(m){var l=m;if(l.match(new RegExp("[A-Z]"))){l=l.replace(/([A-Z])/g,function(n){return"_"+n.toLowerCase()})}if(this.params){return this.params[l]||null}};f.prototype.addFilter=function(n,l,m){this.params.filters=this.params.filters||[];this.params.filters.push({property_name:n,operator:l,property_value:m});return this};a.exports=f},{"./helpers/emitter-shim":11,"./helpers/get-query-string":13,"./helpers/get-timezone-offset":14,"./utils/each":31,"./utils/extend":32}],28:[function(c,b,d){var k=c("./utils/each"),h=c("./utils/extend"),g=c("./utils/sendQuery");var f=c("./");var j=c("./helpers/emitter-shim");function a(m,n,o){var l=o;this.config={timeout:300*1000};this.configure(m,n,l);l=o=null}j(a.prototype);a.prototype.configure=function(m,n,o){var l=o;h(this,{client:m,queries:n,data:{},callback:l});l=o=null;return this};a.prototype.timeout=function(l){if(!arguments.length){return this.config.timeout}this.config.timeout=(!isNaN(parseInt(l))?parseInt(l):null);return this};a.prototype.refresh=function(){var n=this,l=0,m=[],p=false;var o=function(s,r,q){if(s){n.trigger("error",s);if(n.callback){n.callback(s,null)}p=true;return}m[q]=r;l++;if(l==n.queries.length&&!p){n.data=(n.queries.length==1)?m[0]:m;n.trigger("complete",null,n.data);if(n.callback){n.callback(null,n.data)}}};k(n.queries,function(t,r){var u;var q=function(w,v){o(w,v,r)};if(t instanceof f.Query){u="/queries/"+t.analysis;g.call(n,u,t.params,q)}else{if(Object.prototype.toString.call(t)==="[object String]"){u="/saved_queries/"+encodeURIComponent(t)+"/result";g.call(n,u,null,q)}else{var s={statusText:"Bad Request",responseText:{message:"Error: Query "+(+r+1)+" of "+n.queries.length+" for project "+n.client.projectId()+" is not a valid request"}};n.trigger("error",s.responseText.message);if(n.callback){n.callback(s.responseText.message,null)}}}});return this};b.exports=a},{"./":19,"./helpers/emitter-shim":11,"./utils/each":31,"./utils/extend":32,"./utils/sendQuery":34}],29:[function(b,c,a){c.exports={map:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",encode:function(f){var d="",l=0,h=this.map,k,j,g,s,r,q,p;f=this.utf8.encode(f);while(l>2);r=(((k&3)<<4)|(j>>4));q=(isNaN(j)?64:((j&15)<<2)|(g>>6));p=(isNaN(j)||isNaN(g))?64:g&63;d=d+h.charAt(s)+h.charAt(r)+h.charAt(q)+h.charAt(p)}return d},decode:function(f){var d="",p=0,h=this.map,g=String.fromCharCode,t,s,r,q,l,k,j;f=f.replace(/[^A-Za-z0-9\+\/\=]/g,"");while(p>4);k=((s&15)<<4)|(r>>2);j=((r&3)<<6)|q;d=d+(g(l)+((r!=64)?g(k):""))+(((q!=64)?g(j):""))}return this.utf8.decode(d)},utf8:{encode:function(j){var f="",d=0,h=String.fromCharCode,g;while(d127)&&(g<2048))?(h((g>>6)|192)+h((g&63)|128)):(h((g>>12)|224)+h(((g>>6)&63)|128)+h((g&63)|128)))}return f},decode:function(k){var g="",f=0,j=String.fromCharCode,d,h;while(f191)&&(h<224))?[j(((h&31)<<6)|((d=k.charCodeAt(f+1))&63)),(f+=2)][0]:[j(((h&15)<<12)|(((d=k.charCodeAt(f+1))&63)<<6)|((c3=k.charCodeAt(f+2))&63)),(f+=3)][0])}return g}}}},{}],30:[function(b,c,a){var d=b("JSON2");c.exports=function(f){return d.parse(d.stringify(f))}},{JSON2:2}],31:[function(b,c,a){c.exports=function(g,d,f){var h;if(!g){return 0}f=!f?g:f;if(g instanceof Array){for(h=0;h0){this.parse.apply(this,arguments)}}b.defaults={delimeter:" -> "};o(b);o(b.prototype);b.prototype.input=function(q){if(!arguments.length){return this["data"]["input"]}this["data"]["input"]=(q?n(q):null);return this};b.prototype.output=function(q){if(!arguments.length){return this["data"].output}this["data"].output=(q instanceof Array?q:null);return this};b.prototype.method=function(q){if(!arguments.length){return this.meta.method}this.meta.method=(q?String(q):null);return this};b.prototype.schema=function(q){if(!arguments.length){return this.meta.schema}this.meta.schema=(q?q:null);return this};b.prototype.parse=function(r,s){var q;if(r){this.input(r)}if(s){this.schema(s)}this.output([[]]);if(this.meta.schema.select){this.method("select");q=m({records:"",select:true},this.schema());f.call(this,d(q))}else{if(this.meta.schema.unpack){this.method("unpack");q=m({records:"",unpack:{index:false,value:false,label:false}},this.schema());l.call(this,d(q))}}return this};function f(s){var t=this,u=s||{},v=[],w=[];var r,q;if(u.records===""||!u.records){r=[t.input()]}else{q=u.records.split(b.defaults.delimeter);r=h.apply(t,[t.input()].concat(q))[0]}p(u.select,function(y){v.push(y.path.split(b.defaults.delimeter))});if(v.length==0){p(r,function(y,z){var B=a(y);for(var A in B){if(B.hasOwnProperty(A)&&w.indexOf(A)==-1){w.push(A);v.push([A])}}})}var x=[[]];p(v,function(z,y){if(v.length==1){x[0].push("label","value")}else{x[0].push(z.join("."))}});p(r,function(y,z){var A=a(y);if(v.length==1){x.push([v.join("."),A[v.join(".")]])}else{x.push([]);p(v,function(C,B){var D=C.join(".");x[z+1].push(A[D])})}});t.output(x);t.format(u.select);return t}function l(z){var y=this,u=[];var s=(z.unpack.value)?z.unpack.value.path.split(b.defaults.delimeter):false,r=(z.unpack.label)?z.unpack.label.path.split(b.defaults.delimeter):false,t=(z.unpack.index)?z.unpack.index.path.split(b.defaults.delimeter):false;var v=(s[s.length-1]!=="")?s[s.length-1]:"Value",q=(r[r.length-1]!=="")?r[r.length-1]:"Label",x=(t[t.length-1]!=="")?t[t.length-1]:"Index";var w=(function(){var A;if(z.records==""){A=[y.input()]}else{A=h.apply(y,[y.input()].concat(z.records.split(b.defaults.delimeter)))}return A[0]})();if(w instanceof Array==false){w=[w]}p(w,function(A,B){var C=(r)?h.apply(y,[A].concat(r)):[];if(C){u=C}});p(w,function(B,C){var D=(s)?h.apply(y,[B].concat(s)):false,A=(t)?h.apply(y,[B].concat(t)):false;if(A){p(A,function(){y.data.output.push([])})}else{y.data.output.push([])}if(A){if(C==0){y.data.output[0].push(x);if(u.length>0){p(u,function(F,E){y.data.output[0].push(F)})}else{y.data.output[0].push(v)}}if(w.length0){y.data.output[E].push(A[E-1])}})}}else{y.data.output[C+1].push(A[0])}}if(!A&&u.length>0){if(C==0){y.data.output[0].push(q);y.data.output[0].push(v)}y.data.output[C+1].push(u[0])}if(!A&&u.length==0){y.data.output[0].push("")}if(D){if(w.length0){y.data.output[E].push(D[E-1])}})}}else{p(D,function(E){y.data.output[C+1].push(E)})}}else{p(y.data.output[0],function(E,F){var G=(A)?0:-1;if(F>G){y.data.output[C+1].push(null)}})}});y.format(z.unpack);return this}function d(q){p(q.unpack,function(t,s,r){if(t&&k(t,"string")){q.unpack[s]={path:q.unpack[s]}}});return q}function k(r,q){r=typeof(r);if(!q){return r!="undefined"}return r==q}function m(r,q){p(q,function(s,t){if(k(r[t],"object")&&k(s,"object")){r[t]=m(r[t],s)}else{if(s!==null){r[t]=s}}});return r}c.exports=b},{"../core/helpers/emitter-shim":11,"../core/utils/clone":30,"../core/utils/each":31,"./utils/flatten":48,"./utils/parse":49}],36:[function(b,c,a){var f=b("../core/utils/extend"),d=b("./dataset");f(d.prototype,b("./lib/append"));f(d.prototype,b("./lib/delete"));f(d.prototype,b("./lib/filter"));f(d.prototype,b("./lib/insert"));f(d.prototype,b("./lib/select"));f(d.prototype,b("./lib/set"));f(d.prototype,b("./lib/sort"));f(d.prototype,b("./lib/update"));f(d.prototype,b("./lib/analyses"));f(d.prototype,{format:b("./lib/format"),});c.exports=d},{"../core/utils/extend":32,"./dataset":35,"./lib/analyses":37,"./lib/append":38,"./lib/delete":39,"./lib/filter":40,"./lib/format":41,"./lib/insert":42,"./lib/select":43,"./lib/set":44,"./lib/sort":45,"./lib/update":46}],37:[function(d,f,c){var g=d("../../core/utils/each"),a=["Average","Maximum","Minimum","Sum"],b={};b.average=function(h,n,j){var m=h.slice(n||0,(j?j+1:h.length)),k=0,l=null;g(m,function(p,o){if(typeof p==="number"&&!isNaN(parseFloat(p))){k+=parseFloat(p)}});return k/m.length};b.maximum=function(h,m,j){var l=h.slice(m||0,(j?j+1:h.length)),k=[];g(l,function(o,n){if(typeof o==="number"&&!isNaN(parseFloat(o))){k.push(parseFloat(o))}});return Math.max.apply(Math,k)};b.minimum=function(h,m,j){var l=h.slice(m||0,(j?j+1:h.length)),k=[];g(l,function(o,n){if(typeof o==="number"&&!isNaN(parseFloat(o))){k.push(parseFloat(o))}});return Math.min.apply(Math,k)};b.sum=function(h,m,j){var l=h.slice(m||0,(j?j+1:h.length)),k=0;g(l,function(o,n){if(typeof o==="number"&&!isNaN(parseFloat(o))){k+=parseFloat(o)}});return k};g(a,function(h,j){b["getColumn"+h]=b["getRow"+h]=function(k){return this[h.toLowerCase()](k,1)}});b.getColumnLabel=b.getRowIndex=function(h){return h[0]};f.exports=b},{"../../core/utils/each":31}],38:[function(d,f,c){var h=d("../../core/utils/each");var b=d("../utils/create-null-list");f.exports={appendColumn:g,appendRow:a};function g(n,k){var j=this,m=Array.prototype.slice.call(arguments,2),l=(n!==undefined)?n:null;if(typeof k==="function"){j.data.output[0].push(l);h(j.output(),function(q,p){var o;if(p>0){o=k.call(j,q,p);if(typeof o==="undefined"){o=null}j.data.output[p].push(o)}})}else{if(!k||k instanceof Array){k=k||[];if(k.length<=j.output().length-1){k=k.concat(b(j.output().length-1-k.length))}else{h(k,function(p,o){if(j.data.output.length-10){q=j.selectColumn(s);p=k.call(j,q,s);if(typeof p==="undefined"){p=null}l.push(p)}});j.data.output.push(l)}else{if(!k||k instanceof Array){k=k||[];if(k.length<=j.data.output[0].length-1){k=k.concat(b(j.data.output[0].length-1-k.length))}else{h(k,function(q,p){if(j.data.output[0].length-1-1){g(h.data.output,function(m,l){h.data.output[l].splice(j,1)})}return h}function b(j){var h=(typeof j==="number")?j:this.selectColumn(0).indexOf(j);if(h>-1){this.data.output.splice(h,1)}return this}},{"../../core/utils/each":31}],40:[function(c,d,b){var f=c("../../core/utils/each");d.exports={filterColumns:a,filterRows:g};function a(j){var h=this,k=new Array();f(h.data.output,function(m,l){k.push([])});f(h.data.output[0],function(l,m){var n=h.selectColumn(m);if(m==0||j.call(h,n,m)){f(n,function(o,p){k[p].push(o)})}});h.output(k);return h}function g(j){var h=this,k=[];f(h.output(),function(m,l){if(l==0||j.call(h,m,l)){k.push(m)}});h.output(k);return h}},{"../../core/utils/each":31}],41:[function(c,d,b){var f=c("../../core/utils/each");d.exports=function(h){var g=this;if(this.method()==="select"){f(g.output(),function(k,j){if(j==0){f(k,function(l,m){if(h[m]&&h[m].label){g.data.output[j][m]=h[m].label}})}else{f(k,function(l,m){g.data.output[j][m]=a(g.data.output[j][m],h[m])})}})}if(this.method()==="unpack"){if(h.index){f(g.output(),function(k,j){if(j==0){if(h.index.label){g.data.output[j][0]=h.index.label}}else{g.data.output[j][0]=a(g.data.output[j][0],h.index)}})}if(h.label){if(h.index){f(g.output(),function(k,j){f(k,function(l,m){if(j==0&&m>0){g.data.output[j][m]=a(g.data.output[j][m],h.label)}})})}else{f(g.output(),function(k,j){if(j>0){g.data.output[j][0]=a(g.data.output[j][0],h.label)}})}}if(h.value){if(h.index){f(g.output(),function(k,j){f(k,function(l,m){if(j>0&&m>0){g.data.output[j][m]=a(g.data.output[j][m],h.value)}})})}else{f(g.output(),function(k,j){f(k,function(l,m){if(j>0){g.data.output[j][m]=a(g.data.output[j][m],h.value)}})})}}}return g};function a(k,j){var g=k,h=j||{};if(h.replace){f(h.replace,function(m,l){if(g==l||String(g)==String(l)||parseFloat(g)==parseFloat(l)){g=m}})}if(h.type&&h.type=="date"){if(h.format&&moment&&moment(k).isValid()){g=moment(g).format(h.format)}else{g=new Date(g)}}if(h.type&&h.type=="string"){g=String(g)}if(h.type&&h.type=="number"&&!isNaN(parseFloat(g))){g=parseFloat(g)}return g}},{"../../core/utils/each":31}],42:[function(f,b,g){var j=f("../../core/utils/each");var h=f("../utils/create-null-list");var c=f("./append");var l=c.appendRow,d=c.appendColumn;b.exports={insertColumn:a,insertRow:k};function a(p,q,n){var m=this,o;o=(q!==undefined)?q:null;if(typeof n==="function"){m.data.output[0].splice(p,0,o);j(m.output(),function(t,s){var r;if(s>0){r=n.call(m,t,s);if(typeof r==="undefined"){r=null}m.data.output[s].splice(p,0,r)}})}else{if(!n||n instanceof Array){n=n||[];if(n.length<=m.output().length-1){n=n.concat(h(m.output().length-1-n.length))}else{j(n,function(s,r){if(m.data.output.length-10){t=m.selectColumn(v);s=n.call(m,t,v);if(typeof s==="undefined"){s=null}o.push(s)}});m.data.output.splice(q,0,o)}else{if(!n||n instanceof Array){n=n||[];if(n.length<=m.data.output[0].length-1){n=n.concat(h(m.data.output[0].length-1-n.length))}else{j(n,function(t,s){if(m.data.output[0].length-1-1&&"undefined"!==typeof this.data.output[0][j]){g(this.data.output,function(m,l){h.push(m[j])})}return h}function a(k){var h=new Array(),j=(typeof k==="number")?k:this.selectColumn(0).indexOf(k);if(j>-1&&"undefined"!==typeof this.data.output[j]){h=this.data.output[j]}return h}},{"../../core/utils/each":31}],44:[function(d,f,c){var g=d("../../core/utils/each");var b=d("./append");var a=d("./select");f.exports={set:h};function h(n,m){if(arguments.length<2||n.length<2){throw Error("Incorrect arguments provided for #set method")}var j="number"===typeof n[0]?n[0]:this.data.output[0].indexOf(n[0]),o="number"===typeof n[1]?n[1]:a.selectColumn.call(this,0).indexOf(n[1]);var l=a.selectColumn.call(this,n[0]),k=a.selectRow.call(this,n[1]);if(l.length<1){b.appendColumn.call(this,n[0]);j=this.data.output[0].length-1}if(k.length<1){b.appendRow.call(this,n[1]);o=this.data.output.length-1}this.data.output[o][j]=m;return this}},{"../../core/utils/each":31,"./append":38,"./select":43}],45:[function(d,f,c){var g=d("../../core/utils/each");f.exports={sortColumns:b,sortRows:a};function b(n,j){var h=this,k=this.output()[0].slice(1),m=[],o=[],l=j||this.getColumnLabel;g(k,function(p,q){m.push(h.selectColumn(q+1).slice(0))});m.sort(function(q,p){var r=l.call(h,q)>l.call(h,p);if(r){return(n==="asc"?1:-1)}else{if(!r){return(n==="asc"?-1:1)}else{return 0}}});g(m,function(p,q){h.deleteColumn(q+1).insertColumn(q+1,p[0],p.slice(1))});return h}function a(n,k){var j=this,l=this.output().slice(0,1),h=this.output().slice(1),m=k||this.getRowIndex;h.sort(function(p,o){var q=m.call(j,p)>m.call(j,o);if(q){return(n==="asc"?1:-1)}else{if(!q){return(n==="asc"?-1:1)}else{return 0}}});j.output(l.concat(h));return j}},{"../../core/utils/each":31}],46:[function(f,a,g){var k=f("../../core/utils/each");var h=f("../utils/create-null-list");var b=f("./append");var l=b.appendRow,d=b.appendColumn;a.exports={updateColumn:j,updateRow:c};function j(p,n){var m=this,o=(typeof p==="number")?p:this.data.output[0].indexOf(p);if(o>-1){if(typeof n==="function"){k(m.output(),function(s,r){var q;if(r>0){q=n.call(m,s[o],r,s);if(typeof q!=="undefined"){m.data.output[r][o]=q}}})}else{if(!n||n instanceof Array){n=n||[];if(n.length<=m.output().length-1){n=n.concat(h(m.output().length-1-n.length))}else{k(n,function(r,q){if(m.data.output.length-1-1){if(typeof n==="function"){k(m.output()[o],function(t,s){var r=m.selectColumn(s),q=n.call(m,t,s,r);if(typeof q!=="undefined"){m.data.output[o][s]=q}})}else{if(!n||n instanceof Array){n=n||[];if(n.length<=m.data.output[0].length-1){n=n.concat(h(m.data.output[0].length-1-n.length))}else{k(n,function(r,q){if(m.data.output[0].length-10){return f}};return g.apply(this,arguments)}},{"../../core/utils/each":31}],50:[function(b,c,a){ +/*! + * ---------------------- + * C3.js Adapter + * ---------------------- + */ +var f=b("../dataviz"),d=b("../../core/utils/each"),g=b("../../core/utils/extend");c.exports=function(){var j={singular:["gauge"],categorical:["donut","pie"],"cat-interval":["area-step","step","bar","area","area-spline","spline","line"],"cat-ordinal":["bar","area","area-spline","spline","line","step","area-step"],chronological:["area","area-spline","spline","line","bar","step","area-step"],"cat-chronological":["line","spline","area","area-spline","bar","step","area-step"]};var k={};d(["gauge","donut","pie","bar","area","area-spline","spline","line","step","area-step"],function(n,m){k[n]={render:function(){var o=h.call(this,n);this.view._artifacts.c3=c3.generate(o);this.update()},update:function(){var o=this,p=[];if(n==="gauge"){o.view._artifacts.c3.load({columns:[[o.title(),o.data()[1][1]]]})}else{if(n==="pie"||n==="donut"){o.view._artifacts.c3.load({columns:o.dataset.data.output.slice(1)})}else{if(this.dataType().indexOf("chron")>-1){p.push(o.dataset.selectColumn(0));p[0][0]="x"}d(o.data()[0],function(r,q){if(q>0){p.push(o.dataset.selectColumn(q))}});if(o.stacked()){o.view._artifacts.c3.groups([o.labels()])}o.view._artifacts.c3.load({columns:p})}}},destroy:function(){l.call(this)}}});function h(n){var m={axis:{},bindto:this.el(),data:{columns:[]},color:{pattern:this.colors()},size:{height:this.height(),width:this.width()}};m.data["type"]=n;if(n==="gauge"){}else{if(n==="pie"||n==="donut"){m[n]={title:this.title()}}else{if(this.dataType().indexOf("chron")>-1){m.data["x"]="x";m.axis["x"]={type:"timeseries",tick:{format:"%Y-%m-%d"}}}else{if(this.dataType()==="cat-ordinal"){m.axis["x"]={type:"category",categories:this.labels()}}}if(this.title()){m.axis["y"]={label:this.title()}}}}return g(m,this.chartOptions())}function l(){if(this.view._artifacts.c3){this.view._artifacts.c3.destroy();this.view._artifacts.c3=null}}f.register("c3",k,{capabilities:j})}},{"../../core/utils/each":31,"../../core/utils/extend":32,"../dataviz":54}],51:[function(b,c,a){ +/*! + * ---------------------- + * Chart.js Adapter + * ---------------------- + */ +var f=b("../dataviz"),d=b("../../core/utils/each"),g=b("../../core/utils/extend");c.exports=function(){if(typeof Chart!=="undefined"){Chart.defaults.global.responsive=true}var q={categorical:["doughnut","pie","polar-area","radar"],"cat-interval":["bar","line"],"cat-ordinal":["bar","line"],chronological:["line","bar"],"cat-chronological":["line","bar"]};var o={radar:"Radar","polar-area":"PolarArea",pie:"Pie",doughnut:"Doughnut",line:"Line",bar:"Bar"};var m={doughnut:p,pie:p,"polar-area":p,radar:n,line:n,bar:n};function p(){var u=this,t=[];d(u.dataset.selectColumn(0).slice(1),function(v,w){t.push({value:u.dataset.selectColumn(1).slice(1)[w],color:u.colors()[+w],hightlight:u.colors()[+w+9],label:v})});return t}function n(){var u=this,v,t={labels:[],datasets:[]};v=this.dataset.selectColumn(0).slice(1);d(v,function(w,x){if(w instanceof Date){t.labels.push((w.getMonth()+1)+"-"+w.getDate()+"-"+w.getFullYear())}else{t.labels.push(w)}});d(u.dataset.selectRow(0).slice(1),function(w,x){var y={r:r(u.colors()[x]),g:j(u.colors()[x]),b:l(u.colors()[x])};t.datasets.push({label:w,fillColor:"rgba("+y.r+","+y.g+","+y.b+",0.2)",strokeColor:"rgba("+y.r+","+y.g+","+y.b+",1)",pointColor:"rgba("+y.r+","+y.g+","+y.b+",1)",pointStrokeColor:"#fff",pointHighlightFill:"#fff",pointHighlightStroke:"rgba("+y.r+","+y.g+","+y.b+",1)",data:u.dataset.selectColumn(+x+1).slice(1)})});return t}var k={};d(["doughnut","pie","polar-area","radar","bar","line"],function(u,t){k[u]={initialize:function(){if(this.el().nodeName.toLowerCase()!=="canvas"){var v=document.createElement("canvas");this.el().innerHTML="";this.el().appendChild(v);this.view._artifacts.ctx=v.getContext("2d")}else{this.view._artifacts.ctx=this.el().getContext("2d")}if(this.height()){this.view._artifacts.ctx.canvas.height=this.height();this.view._artifacts.ctx.canvas.style.height=String(this.height()+"px")}if(this.width()){this.view._artifacts.ctx.canvas.width=this.width();this.view._artifacts.ctx.canvas.style.width=String(this.width()+"px")}return this},render:function(){var x=o[u],v=g({},this.chartOptions()),w=m[u].call(this);if(this.view._artifacts.chartjs){this.view._artifacts.chartjs.destroy()}this.view._artifacts.chartjs=new Chart(this.view._artifacts.ctx)[x](w,v);return this},destroy:function(){s.call(this)}}});function s(){if(this.view._artifacts.chartjs){this.view._artifacts.chartjs.destroy();this.view._artifacts.chartjs=null}}function r(t){return parseInt((h(t)).substring(0,2),16)}function j(t){return parseInt((h(t)).substring(2,4),16)}function l(t){return parseInt((h(t)).substring(4,6),16)}function h(t){return(t.charAt(0)=="#")?t.substring(1,7):t}f.register("chartjs",k,{capabilities:q})}},{"../../core/utils/each":31,"../../core/utils/extend":32,"../dataviz":54}],52:[function(c,d,b){ +/*! + * ---------------------- + * Google Charts Adapter + * ---------------------- + */ +var g=c("../dataviz"),f=c("../../core/utils/each"),h=c("../../core/utils/extend"),a=c("../../core");d.exports=function(){a.loaded=false;var j={"Data column(s) for axis #0 cannot be of type string":"No results to visualize"};var l=["AreaChart","BarChart","ColumnChart","LineChart","PieChart","Table"];var o={};var n={categorical:["piechart","barchart","columnchart","table"],"cat-interval":["columnchart","barchart","table"],"cat-ordinal":["barchart","columnchart","areachart","linechart","table"],chronological:["areachart","linechart","table"],"cat-chronological":["linechart","columnchart","barchart","areachart"],nominal:["table"],extraction:["table"]};f(l,function(q){var p=q.toLowerCase();o[p]={initialize:function(){},render:function(){if(typeof google==="undefined"){this.error("The Google Charts library could not be loaded.");return}var r=this;if(r.view._artifacts.googlechart){this.destroy()}r.view._artifacts.googlechart=r.view._artifacts.googlechart||new google.visualization[q](r.el());google.visualization.events.addListener(r.view._artifacts.googlechart,"error",function(s){k.call(r,s)});this.update()},update:function(){var r=m.call(this,q);h(r,this.chartOptions(),this.attributes());r.isStacked=(this.stacked()||r.isStacked);this.view._artifacts.datatable=google.visualization.arrayToDataTable(this.data());if(this.view._artifacts.googlechart){this.view._artifacts.googlechart.draw(this.view._artifacts.datatable,r)}},destroy:function(){if(this.view._artifacts.googlechart){google.visualization.events.removeAllListeners(this.view._artifacts.googlechart);this.view._artifacts.googlechart.clearChart();this.view._artifacts.googlechart=null;this.view._artifacts.datatable=null}}}});g.register("google",o,{capabilities:n,dependencies:[{type:"script",url:"https://www.google.com/jsapi",cb:function(p){if(typeof google==="undefined"){this.trigger("error","Problem loading Google Charts library. Please contact us!");p()}else{google.load("visualization","1.1",{packages:["corechart","table"],callback:function(){p()}})}}}]});function k(p){var q=j[p.message]||p.message||"An error occurred";this.error(q)}function m(q){var p={};switch(q.toLowerCase()){case"areachart":p.lineWidth=2;p.hAxis={baselineColor:"transparent",gridlines:{color:"transparent"}};p.vAxis={viewWindow:{min:0}};if(this.dataType()==="chronological"||this.dataType()==="cat-ordinal"){p.legend="none";p.chartArea={width:"85%"}}break;case"barchart":p.hAxis={viewWindow:{min:0}};p.vAxis={baselineColor:"transparent",gridlines:{color:"transparent"}};if(this.dataType()==="chronological"||this.dataType()==="cat-ordinal"){p.legend="none"}break;case"columnchart":p.hAxis={baselineColor:"transparent",gridlines:{color:"transparent"}};p.vAxis={viewWindow:{min:0}};if(this.dataType()==="chronological"||this.dataType()==="cat-ordinal"){p.legend="none";p.chartArea={width:"85%"}}break;case"linechart":p.lineWidth=2;p.hAxis={baselineColor:"transparent",gridlines:{color:"transparent"}};p.vAxis={viewWindow:{min:0}};if(this.dataType()==="chronological"||this.dataType()==="cat-ordinal"){p.legend="none";p.chartArea={width:"85%"}}break;case"piechart":p.sliceVisibilityThreshold=0.01;break;case"table":break}return p}}},{"../../core":19,"../../core/utils/each":31,"../../core/utils/extend":32,"../dataviz":54}],53:[function(d,b,f){ +/*! +* ---------------------- +* Keen IO Adapter +* ---------------------- +*/ +var g=d("../../core"),a=d("../dataviz");var j=d("../../core/utils/clone"),k=d("../../core/utils/each"),h=d("../../core/utils/extend"),c=d("../utils/prettyNumber");b.exports=function(){var l,o,n;g.Error={defaults:{backgroundColor:"",borderRadius:"4px",color:"#ccc",display:"block",fontFamily:"Helvetica Neue, Helvetica, Arial, sans-serif",fontSize:"21px",fontWeight:"light",textAlign:"center"}};g.Spinner.defaults={height:138,lines:10,length:8,width:3,radius:10,corners:1,rotate:0,direction:1,color:"#4d4d4d",speed:1.67,trail:60,shadow:false,hwaccel:false,className:"keen-spinner",zIndex:2000000000,top:"50%",left:"50%"};var m={singular:["metric"]};l={initialize:function(){var p=document.createElement("style"),q="#49c5b1";p.id="keen-widgets";p.type="text/css";p.innerHTML=" .keen-metric { \n background: "+q+"; \n border-radius: 4px; \n color: #fff; \n font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; \n padding: 10px 0; \n text-align: center; \n} .keen-metric-value { \n display: block; \n font-size: 84px; \n font-weight: 700; \n line-height: 84px; \n} .keen-metric-title { \n display: block; \n font-size: 24px; \n font-weight: 200; \n}";if(!document.getElementById(p.id)){document.body.appendChild(p)}},render:function(){var u=(this.colors().length==1)?this.colors()[0]:"#49c5b1",t=this.title()||"Result",v=this.data()[1][1]||0,r=this.width(),q=this.chartOptions()||{},s="",w="";var x={width:(r)?r+"px":"auto"};var p=v;if(typeof q.prettyNumber==="undefined"||q.prettyNumber==true){if(!isNaN(parseInt(v))){p=c(v)}}if(q.prefix){s=''+q.prefix+""}if(q.suffix){w=''+q.suffix+""}this.el().innerHTML='
'+s+p+w+''+t+"
"}};o={initialize:function(){},render:function(t,q){var r,s;var u=j(g.Error.defaults);var p=h(u,q);r=document.createElement("div");r.className="keen-error";k(p,function(w,v){r.style[v]=w});r.style.height=String(this.height()+"px");r.style.paddingTop=(this.height()/2-15)+"px";r.style.width=String(this.width()+"px");s=document.createElement("span");s.innerHTML=t||"Yikes! An error occurred!";r.appendChild(s);this.el().innerHTML="";this.el().appendChild(r)},destroy:function(){this.el().innerHTML=""}};n={initialize:function(){},render:function(){var q=document.createElement("div");var p=this.height()||g.Spinner.defaults.height;q.className="keen-loading";q.style.height=String(p+"px");q.style.position="relative";q.style.width=String(this.width()+"px");this.el().innerHTML="";this.el().appendChild(q);this.view._artifacts.spinner=new g.Spinner(g.Spinner.defaults).spin(q)},destroy:function(){this.view._artifacts.spinner.stop();this.view._artifacts.spinner=null}};g.Dataviz.register("keen-io",{metric:l,error:o,spinner:n},{capabilities:m})}},{"../../core":19,"../../core/utils/clone":30,"../../core/utils/each":31,"../../core/utils/extend":32,"../dataviz":54,"../utils/prettyNumber":93}],54:[function(f,d,g){var k=f("../core/utils/clone"),m=f("../core/utils/each"),j=f("../core/utils/extend"),a=f("./utils/loadScript"),n=f("./utils/loadStyle");var h=f("../core");var l=f("../core/helpers/emitter-shim");var c=f("../dataset");function b(){this.dataset=new c();this.view={_prepared:false,_initialized:false,_rendered:false,_artifacts:{},adapter:{library:undefined,chartOptions:{},chartType:undefined,defaultChartType:undefined,dataType:undefined},attributes:k(b.defaults),defaults:k(b.defaults),el:undefined,loader:{library:"keen-io",chartType:"spinner"}};b.visuals.push(this)}j(b,{dataTypeMap:{singular:{library:"keen-io",chartType:"metric"},categorical:{library:"google",chartType:"piechart"},"cat-interval":{library:"google",chartType:"columnchart"},"cat-ordinal":{library:"google",chartType:"barchart"},chronological:{library:"google",chartType:"areachart"},"cat-chronological":{library:"google",chartType:"linechart"},extraction:{library:"google",chartType:"table"},nominal:{library:"google",chartType:"table"}},defaults:{colors:["#00bbde","#fe6672","#eeb058","#8a8ad6","#ff855c","#00cfbb","#5a9eed","#73d483","#c879bb","#0099b6","#d74d58","#cb9141","#6b6bb6","#d86945","#00aa99","#4281c9","#57b566","#ac5c9e","#27cceb","#ff818b","#f6bf71","#9b9be1","#ff9b79","#26dfcd","#73aff4","#87e096","#d88bcb"],indexBy:"timeframe.start",stacked:false},dependencies:{loading:0,loaded:0,urls:{}},libraries:{},visuals:[]});l(b);l(b.prototype);b.register=function(r,p,q){var o=this;var s=function(t){t.loaded++;if(t.loaded===t.loading){h.loaded=true;h.trigger("ready")}};b.libraries[r]=b.libraries[r]||{};m(p,function(u,t){b.libraries[r][t]=u});if(q&&q.capabilities){b.libraries[r]._defaults=b.libraries[r]._defaults||{};m(q.capabilities,function(t,u){b.libraries[r]._defaults[u]=t})}if(q&&q.dependencies){m(q.dependencies,function(v,u,w){var t=b.dependencies;if(!t.urls[v.url]){t.urls[v.url]=true;t.loading++;var x=v.type==="script"?a:n;x(v.url,function(){if(v.cb){v.cb.call(o,function(){s(t)})}else{s(t)}})}})}};b.find=function(q){if(!arguments.length){return b.visuals}var p=q.nodeName?q:document.querySelector(q),o;m(b.visuals,function(r){if(p==r.el()){o=r;return false}});if(o){return o}};d.exports=b},{"../core":19,"../core/helpers/emitter-shim":11,"../core/utils/clone":30,"../core/utils/each":31,"../core/utils/extend":32,"../dataset":36,"./utils/loadScript":91,"./utils/loadStyle":92}],55:[function(b,d,a){var h=b("../../core/utils/clone"),g=b("../../core/utils/extend"),f=b("../dataviz"),c=b("../../core/request");d.exports=function(p,m,j){var l=h(f.defaults),o=new f(),n=new c(this,[p]),k=j?h(j):{};if(k.chartType){o.chartType(k.chartType);delete k.chartType}if(k.library){o.library(k.library);delete k.library}if(k.chartOptions){o.chartOptions(k.chartOptions);delete k.chartOptions}o.attributes(g(l,k)).el(m).prepare();n.refresh();n.on("complete",function(){o.parseRequest(this).call(function(){if(k.labels){this.labels(k.labels)}}).render()});n.on("error",function(q){o.error(q.message)});return o}},{"../../core/request":28,"../../core/utils/clone":30,"../../core/utils/extend":32,"../dataviz":54}],56:[function(b,c,a){var d=b("../dataviz"),f=b("../../core/utils/extend");c.exports=function(){var k=f({},d.dataTypeMap),h=this.dataType(),g=this.library(),j=this.chartType()||this.defaultChartType();if(!g&&k[h]){g=k[h].library}if(g&&!j&&h){j=d.libraries[g]._defaults[h][0]}if(g&&!j&&k[h]){j=k[h].chartType}return(g&&j)?d.libraries[g][j]:{}}},{"../../core/utils/extend":32,"../dataviz":54}],57:[function(c,d,b){var g=c("../../core/utils/each"),f=c("../../dataset");d.exports={extraction:a};function a(j){var k=(j.data instanceof Array?j.data[0]:j.data),l=j.queries[0].get("property_names")||[],h={records:"result",select:true};if(l){h.select=[];g(l,function(m){h.select.push({path:m})})}return new f(k,h)}},{"../../core/utils/each":31,"../../dataset":36}],58:[function(b,c,a){c.exports=function(f){var h=f.queries[0].analysis.replace("_"," "),g=f.queries[0].get("event_collection"),d;d=h.replace(/\b./g,function(j){return j.toUpperCase()});if(g){d+=" - "+g}return d}},{}],59:[function(b,c,a){c.exports=function(g){var h=typeof g.params.interval==="string",f=typeof g.params.group_by==="string",j=g.params.group_by instanceof Array,d;if(!f&&!h){d="singular"}if(f&&!h){d="categorical"}if(h&&!f){d="chronological"}if(h&&f){d="cat-chronological"}if(!h&&j){d="categorical"}if(h&&j){d="cat-chronological"}if(g.analysis==="funnel"){d="cat-ordinal"}if(g.analysis==="extraction"){d="extraction"}if(g.analysis==="select_unique"){d="nominal"}return d}},{}],60:[function(b,c,a){var f=b("../core/utils/extend"),d=b("./dataviz");f(d.prototype,{adapter:b("./lib/adapter"),attributes:b("./lib/attributes"),call:b("./lib/call"),chartOptions:b("./lib/chartOptions"),chartType:b("./lib/chartType"),colorMapping:b("./lib/colorMapping"),colors:b("./lib/colors"),data:b("./lib/data"),dataType:b("./lib/dataType"),defaultChartType:b("./lib/defaultChartType"),el:b("./lib/el"),height:b("./lib/height"),indexBy:b("./lib/indexBy"),labelMapping:b("./lib/labelMapping"),labels:b("./lib/labels"),library:b("./lib/library"),parseRawData:b("./lib/parseRawData"),parseRequest:b("./lib/parseRequest"),prepare:b("./lib/prepare"),sortGroups:b("./lib/sortGroups"),sortIntervals:b("./lib/sortIntervals"),stacked:b("./lib/stacked"),title:b("./lib/title"),width:b("./lib/width")});f(d.prototype,{destroy:b("./lib/actions/destroy"),error:b("./lib/actions/error"),initialize:b("./lib/actions/initialize"),render:b("./lib/actions/render"),update:b("./lib/actions/update")});c.exports=d},{"../core/utils/extend":32,"./dataviz":54,"./lib/actions/destroy":61,"./lib/actions/error":62,"./lib/actions/initialize":63,"./lib/actions/render":64,"./lib/actions/update":65,"./lib/adapter":66,"./lib/attributes":67,"./lib/call":68,"./lib/chartOptions":69,"./lib/chartType":70,"./lib/colorMapping":71,"./lib/colors":72,"./lib/data":73,"./lib/dataType":74,"./lib/defaultChartType":75,"./lib/el":76,"./lib/height":77,"./lib/indexBy":78,"./lib/labelMapping":79,"./lib/labels":80,"./lib/library":81,"./lib/parseRawData":82,"./lib/parseRequest":83,"./lib/prepare":84,"./lib/sortGroups":85,"./lib/sortIntervals":86,"./lib/stacked":87,"./lib/title":88,"./lib/width":89}],61:[function(b,c,a){var d=b("../../helpers/getAdapterActions");c.exports=function(){var f=d.call(this);if(f.destroy){f.destroy.apply(this,arguments)}if(this.el()){this.el().innerHTML=""}this.view._prepared=false;this.view._initialized=false;this.view._rendered=false;this.view._artifacts={};return this}},{"../../helpers/getAdapterActions":56}],62:[function(b,c,a){var f=b("../../helpers/getAdapterActions"),d=b("../../dataviz");c.exports=function(){var g=f.call(this);if(g.error){g.error.apply(this,arguments)}else{d.libraries["keen-io"]["error"].render.apply(this,arguments)}return this}},{"../../dataviz":54,"../../helpers/getAdapterActions":56}],63:[function(b,c,a){var f=b("../../helpers/getAdapterActions"),d=b("../../dataviz");c.exports=function(){var h=f.call(this);var g=d.libraries[this.view.loader.library][this.view.loader.chartType];if(this.view._prepared){if(g.destroy){g.destroy.apply(this,arguments)}}else{if(this.el()){this.el().innerHTML=""}}if(h.initialize){h.initialize.apply(this,arguments)}this.view._initialized=true;return this}},{"../../dataviz":54,"../../helpers/getAdapterActions":56}],64:[function(c,d,b){var f=c("../../helpers/getAdapterActions"),a=c("../../utils/applyTransforms");d.exports=function(){var g=f.call(this);a.call(this);if(!this.view._initialized){this.initialize()}if(this.el()&&g.render){g.render.apply(this,arguments);this.view._rendered=true}return this}},{"../../helpers/getAdapterActions":56,"../../utils/applyTransforms":90}],65:[function(c,d,b){var f=c("../../helpers/getAdapterActions"),a=c("../../utils/applyTransforms");d.exports=function(){var g=f.call(this);a.call(this);if(g.update){g.update.apply(this,arguments)}else{if(g.render){this.render()}}return this}},{"../../helpers/getAdapterActions":56,"../../utils/applyTransforms":90}],66:[function(b,c,a){var d=b("../../core/utils/each");c.exports=function(g){if(!arguments.length){return this.view.adapter}var f=this;d(g,function(j,h){f.view.adapter[h]=(j?j:null)});return this}},{"../../core/utils/each":31}],67:[function(b,c,a){var d=b("../../core/utils/each");var f=b("./chartOptions");c.exports=function(h){if(!arguments.length){return this.view.attributes}var g=this;d(h,function(k,j){if(j==="chartOptions"){f.call(g,k)}else{g.view.attributes[j]=k}});return this}},{"../../core/utils/each":31,"./chartOptions":69}],68:[function(b,c,a){c.exports=function(d){d.call(this);return this}},{}],69:[function(b,c,a){var d=b("../../core/utils/extend");c.exports=function(f){if(!arguments.length){return this.view.adapter.chartOptions}d(this.view.adapter.chartOptions,f);return this}},{"../../core/utils/extend":32}],70:[function(b,c,a){c.exports=function(d){if(!arguments.length){return this.view.adapter.chartType}this.view.adapter.chartType=(d?String(d):null);return this}},{}],71:[function(b,c,a){var d=b("../../core/utils/each");c.exports=function(g){if(!arguments.length){return this.view.attributes.colorMapping}this.view.attributes.colorMapping=(g?g:null);f.call(this);return this};function f(){var g=this,l=this.dataset.schema,m=this.dataset.output(),j=this.view.defaults.colors.slice(),h=this.colorMapping(),k=this.dataType()||"";if(h){if(k.indexOf("chronological")>-1||(l.unpack&&m[0].length>2)){d(m[0].slice(1),function(o,p){var n=h[o];if(n&&j[p]!==n){j.splice(p,0,n)}})}else{d(g.dataset.selectColumn(0).slice(1),function(o,p){var n=h[o];if(n&&j[p]!==n){j.splice(p,0,n)}})}g.view.attributes.colors=j}}},{"../../core/utils/each":31}],72:[function(b,c,a){c.exports=function(d){if(!arguments.length){return this.view.attributes.colors}this.view.attributes.colors=(d instanceof Array?d:null);this.view.defaults.colors=(d instanceof Array?d:null);return this}},{}],73:[function(b,d,a){var f=b("../../dataset"),c=b("../../core/request");d.exports=function(g){if(!arguments.length){return this.dataset.output()}if(g instanceof f){this.dataset=g}else{if(g instanceof c){this.parseRequest(g)}else{this.parseRawData(g)}}return this}},{"../../core/request":28,"../../dataset":36}],74:[function(b,c,a){c.exports=function(d){if(!arguments.length){return this.view.adapter.dataType}this.view.adapter.dataType=(d?String(d):null);return this}},{}],75:[function(b,c,a){c.exports=function(d){if(!arguments.length){return this.view.adapter.defaultChartType}this.view.adapter.defaultChartType=(d?String(d):null);return this}},{}],76:[function(b,c,a){c.exports=function(d){if(!arguments.length){return this.view.el}this.view.el=d;return this}},{}],77:[function(b,c,a){c.exports=function(d){if(!arguments.length){return this.view.attributes["height"]}this.view.attributes["height"]=(!isNaN(parseInt(d))?parseInt(d):null);return this}},{}],78:[function(b,d,a){var f=b("../../dataset"),h=b("../dataviz"),g=b("../../core/utils/each");d.exports=function(j){if(!arguments.length){return this.view.attributes.indexBy}this.view.attributes.indexBy=(j?String(j):h.defaults.indexBy);c.call(this);return this};function c(){var l=this,k=this.dataset.meta.schema||this.dataset.meta.unpack,j=this.indexBy().split(".").join(f.defaults.delimeter);g(k,function(n,m){if(m==="select"&&n instanceof Array){g(n,function(p,o){if(p.path.indexOf("timeframe -> ")>-1){l.dataset.meta.schema[m][o].path=j}})}else{if(m==="unpack"&&typeof n==="object"){l.dataset.meta.schema[m]["index"].path=j}}});this.dataset.parse()}},{"../../core/utils/each":31,"../../dataset":36,"../dataviz":54}],79:[function(b,c,a){var f=b("../../core/utils/each");c.exports=function(g){if(!arguments.length){return this.view.attributes.labelMapping}this.view.attributes.labelMapping=(g?g:null);d.call(this);return this};function d(){var g=this,k=this.labelMapping(),j=this.dataset.schema()||{},h=this.dataType()||"";if(k){if(h.indexOf("chronological")>-1||(j.unpack&&g.dataset.output()[0].length>2)){f(g.dataset.output()[0],function(m,l){if(l>0){g.dataset.data.output[0][l]=k[m]||m}})}else{if(j.select&&g.dataset.output()[0].length===2){g.dataset.updateColumn(0,function(m,l){return k[m]||m})}}}}},{"../../core/utils/each":31}],80:[function(c,d,b){var f=c("../../core/utils/each");d.exports=function(h){if(!arguments.length){if(!this.view.attributes.labels||!this.view.attributes.labels.length){return g.call(this)}else{return this.view.attributes.labels}}else{this.view.attributes.labels=(h instanceof Array?h:null);a.call(this);return this}};function a(){var h=this,m=this.labels()||null,k=this.dataset.schema()||{},l=this.dataset.output(),j=this.dataType()||"";if(m){if(j.indexOf("chronological")>-1||(k.unpack&&l[0].length>2)){f(l[0],function(n,o){if(o>0&&m[o-1]){h.dataset.data.output[0][o]=m[o-1]}})}else{f(l,function(o,n){if(n>0&&m[n-1]){h.dataset.data.output[n][0]=m[n-1]}})}}}function g(){var j=this.dataset.schema()||{},k=this.dataset.output(),h=this.dataType()||"",l;if(h.indexOf("chron")>-1||(j.unpack&&k[0].length>2)){l=this.dataset.selectRow(0).slice(1)}else{l=this.dataset.selectColumn(0).slice(1)}return l}},{"../../core/utils/each":31}],81:[function(b,c,a){c.exports=function(d){if(!arguments.length){return this.view.adapter.library}this.view.adapter.library=(d?String(d):null);return this}},{}],82:[function(b,c,a){var g=b("../dataviz"),d=b("../../dataset");var f=b("../../core/utils/each");c.exports=function(j){this.dataset=h.call(this,j);return this};function h(m){var t=this,l={},o,j,q,k,p,r,n;o=t.indexBy()?t.indexBy():g.defaults.indexBy;j=d.defaults.delimeter;q=o.split(".").join(j);k=t.labels()||null;p=t.labelMapping()||null;if(typeof m.result=="number"){r="singular";l={records:"",select:[{path:"result",type:"string",label:"Metric"}]}}if(m.result instanceof Array&&m.result.length>0){if(m.result[0].timeframe&&(typeof m.result[0].value=="number"||m.result[0].value==null)){r="chronological";l={records:"result",select:[{path:q,type:"date"},{path:"value",type:"number"}]}}if(typeof m.result[0].result=="number"){r="categorical";l={records:"result",select:[]};for(var s in m.result[0]){if(m.result[0].hasOwnProperty(s)&&s!=="result"){l.select.push({path:s,type:"string"});break}}l.select.push({path:"result",type:"number"})}if(m.result[0].value instanceof Array){r="cat-chronological";l={records:"result",unpack:{index:{path:q,type:"date"},value:{path:"value -> result",type:"number"}}};for(var s in m.result[0].value[0]){if(m.result[0].value[0].hasOwnProperty(s)&&s!=="result"){l.unpack.label={path:"value -> "+s,type:"string"};break}}}if(typeof m.result[0]=="number"){r="cat-ordinal";l={records:"",unpack:{index:{path:"steps -> event_collection",type:"string"},value:{path:"result -> ",type:"number"}}}}if(typeof m.result[0]=="string"){r="nominal";n=new d();n.appendColumn("unique values",[]);f(m.result,function(u,v){n.appendRow(u)})}if(r===void 0){r="extraction";l={records:"result",select:true}}}n=n instanceof d?n:new d(m,l);if(r){t.dataType(r)}return n}},{"../../core/utils/each":31,"../../dataset":36,"../dataviz":54}],83:[function(c,d,a){var j=c("../helpers/getDatasetSchemas"),b=c("../helpers/getDefaultTitle"),f=c("../helpers/getQueryDataType");var g=c("../../dataset"),h=c("./parseRawData");d.exports=function(l){var k=f(l.queries[0]);if(k==="extraction"){this.dataset=j.extraction(l)}else{this.parseRawData(l.data instanceof Array?l.data[0]:l.data)}this.dataType(k);this.view.defaults.title=b.call(this,l);if(!this.title()){this.title(this.view.defaults.title)}return this}},{"../../dataset":36,"../helpers/getDatasetSchemas":57,"../helpers/getDefaultTitle":58,"../helpers/getQueryDataType":59,"./parseRawData":82}],84:[function(b,c,a){var d=b("../dataviz");c.exports=function(){var f;if(this.view._rendered){this.destroy()}if(this.el()){this.el().innerHTML="";f=d.libraries[this.view.loader.library][this.view.loader.chartType];if(f.initialize){f.initialize.apply(this,arguments)}if(f.render){f.render.apply(this,arguments)}this.view._prepared=true}return this}},{"../dataviz":54}],85:[function(b,c,a){c.exports=function(f){if(!arguments.length){return this.view.attributes.sortGroups}this.view.attributes.sortGroups=(f?String(f):null);d.call(this);return this};function d(){var f=this.dataType();if(!this.sortGroups()){return}if((f&&f.indexOf("chronological")>-1)||this.data()[0].length>2){this.dataset.sortColumns(this.sortGroups(),this.dataset.getColumnSum)}else{if(f&&(f.indexOf("cat-")>-1||f.indexOf("categorical")>-1)){this.dataset.sortRows(this.sortGroups(),this.dataset.getRowSum)}}return}},{}],86:[function(b,c,a){c.exports=function(f){if(!arguments.length){return this.view.attributes.sortIntervals}this.view.attributes.sortIntervals=(f?String(f):null);d.call(this);return this};function d(){if(!this.sortIntervals()){return}this.dataset.sortRows(this.sortIntervals());return}},{}],87:[function(b,c,a){c.exports=function(d){if(!arguments.length){return this.view.attributes["stacked"]}this.view.attributes["stacked"]=d?true:false;return this}},{}],88:[function(b,c,a){c.exports=function(d){if(!arguments.length){return this.view.attributes["title"]}this.view.attributes["title"]=(d?String(d):null);return this}},{}],89:[function(b,c,a){c.exports=function(d){if(!arguments.length){return this.view.attributes["width"]}this.view.attributes["width"]=(!isNaN(parseInt(d))?parseInt(d):null);return this}},{}],90:[function(b,c,a){c.exports=function(){if(this.labelMapping()){this.labelMapping(this.labelMapping())}if(this.colorMapping()){this.colorMapping(this.colorMapping())}if(this.sortGroups()){this.sortGroups(this.sortGroups())}if(this.sortIntervals()){this.sortIntervals(this.sortIntervals())}}},{}],91:[function(b,c,a){c.exports=function(f,d){var j=document;var h;var g=j.head||j.getElementsByTagName("head");setTimeout(function(){if("item" in g){if(!g[0]){setTimeout(arguments.callee,25);return}g=g[0]}var k=j.createElement("script"),l=false;k.onload=k.onreadystatechange=function(){if((k.readyState&&k.readyState!=="complete"&&k.readyState!=="loaded")||l){return false}k.onload=k.onreadystatechange=null;l=true;d()};k.src=f;g.insertBefore(k,g.firstChild)},0);if(j.readyState===null&&j.addEventListener){j.readyState="loading";j.addEventListener("DOMContentLoaded",h=function(){j.removeEventListener("DOMContentLoaded",h,false);j.readyState="complete"},false)}}},{}],92:[function(b,c,a){c.exports=function(f,d){var g=document.createElement("link");g.setAttribute("rel","stylesheet");g.type="text/css";g.href=f;d();document.head.appendChild(g)}},{}],93:[function(b,c,a){c.exports=function(k){var d=Number(k),h=d.toPrecision(3),j="",f=["","k","M","B","T"];if(Number(h)==d&&String(d).length<=4){return String(d)}if(d>=1||d<=-1){if(d<0){d=-d;j="-"}return j+g(d,0)}else{return d.toPrecision(3)}function g(l,n){var l=String(l);var m=l.split(".");if(m.length>1){l=m[0];var p=m[1];if(l.length==2&&p.length>0){if(p.length>0){l=l+"."+p.charAt(0)}else{l+="0"}}else{if(l.length==1&&p.length>0){l=l+"."+p.charAt(0);if(p.length>1){l+=p.charAt(1)}else{l+="0"}}}}var o=l.length;if(l.split(".").length>1){o--}if(o<=3){return String(l)+f[n]}else{return g(Number(l)/1000,n+1)}}}},{}],94:[function(b,c,a){(function(d){(function(j){if(typeof define==="function"&&define.amd){define("keen",[],function(){return j()})}if(typeof a==="object"&&typeof c!=="undefined"){c.exports=j()}var h=null;if(typeof window!=="undefined"){h=window}else{if(typeof d!=="undefined"){h=d}else{if(typeof self!=="undefined"){h=self}}}if(h){h.Keen=j()}})(function(){var f=b("./core"),g=b("./core/utils/extend");g(f.prototype,{addEvent:b("./core/lib/addEvent"),addEvents:b("./core/lib/addEvents"),setGlobalProperties:b("./core/lib/setGlobalProperties"),trackExternalLink:b("./core/lib/trackExternalLink"),get:b("./core/lib/get"),post:b("./core/lib/post"),put:b("./core/lib/post"),run:b("./core/lib/run"),draw:b("./dataviz/extensions/draw")});f.Query=b("./core/query");f.Request=b("./core/request");f.Dataset=b("./dataset");f.Dataviz=b("./dataviz");f.Base64=b("./core/utils/base64");f.Spinner=b("spin.js");f.utils={domready:b("domready"),each:b("./core/utils/each"),extend:g,parseParams:b("./core/utils/parseParams"),prettyNumber:b("./dataviz/utils/prettyNumber")};b("./dataviz/adapters/keen-io")();b("./dataviz/adapters/google")();b("./dataviz/adapters/c3")();b("./dataviz/adapters/chartjs")();if(f.loaded){setTimeout(function(){f.utils.domready(function(){f.emit("ready")})},0)}b("./core/async")();c.exports=f;return f})}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"./core":19,"./core/async":10,"./core/lib/addEvent":20,"./core/lib/addEvents":21,"./core/lib/get":22,"./core/lib/post":23,"./core/lib/run":24,"./core/lib/setGlobalProperties":25,"./core/lib/trackExternalLink":26,"./core/query":27,"./core/request":28,"./core/utils/base64":29,"./core/utils/each":31,"./core/utils/extend":32,"./core/utils/parseParams":33,"./dataset":36,"./dataviz":60,"./dataviz/adapters/c3":50,"./dataviz/adapters/chartjs":51,"./dataviz/adapters/google":52,"./dataviz/adapters/keen-io":53,"./dataviz/extensions/draw":55,"./dataviz/utils/prettyNumber":93,domready:5,"spin.js":6}]},{},[94]); \ No newline at end of file