diff --git a/dist/keen-query.js b/dist/keen-query.js new file mode 100644 index 0000000..cdd6534 --- /dev/null +++ b/dist/keen-query.js @@ -0,0 +1,2444 @@ +(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;o 1))) / 4) - floor((year - 1901 + month) / 100) + floor((year - 1601 + month) / 400); + }; + } + if (!(isProperty = objectProto.hasOwnProperty)) { + isProperty = function (property) { + var members = {}, constructor; + if ((members.__proto__ = null, members.__proto__ = { + "toString": 1 + }, members).toString != getClass) { + isProperty = function (property) { + var original = this.__proto__, result = property in (this.__proto__ = null, this); + this.__proto__ = original; + return result; + }; + } else { + constructor = members.constructor; + isProperty = function (property) { + var parent = (this.constructor || constructor).prototype; + return property in this && !(property in parent && this[property] === parent[property]); + }; + } + members = null; + return isProperty.call(this, property); + }; + } + forEach = function (object, callback) { + var size = 0, Properties, members, property; + (Properties = function () { + this.valueOf = 0; + }).prototype.valueOf = 0; + members = new Properties(); + for (property in members) { + if (isProperty.call(members, property)) { + size++; + } + } + Properties = members = null; + if (!size) { + members = ["valueOf", "toString", "toLocaleString", "propertyIsEnumerable", "isPrototypeOf", "hasOwnProperty", "constructor"]; + forEach = function (object, callback) { + var isFunction = getClass.call(object) == functionClass, property, length; + var hasProperty = !isFunction && typeof object.constructor != "function" && objectTypes[typeof object.hasOwnProperty] && object.hasOwnProperty || isProperty; + for (property in object) { + if (!(isFunction && property == "prototype") && hasProperty.call(object, property)) { + callback(property); + } + } + for (length = members.length; property = members[--length]; hasProperty.call(object, property) && callback(property)); + }; + } else if (size == 2) { + forEach = function (object, callback) { + var members = {}, isFunction = getClass.call(object) == functionClass, property; + for (property in object) { + if (!(isFunction && property == "prototype") && !isProperty.call(members, property) && (members[property] = 1) && isProperty.call(object, property)) { + callback(property); + } + } + }; + } else { + forEach = function (object, callback) { + var isFunction = getClass.call(object) == functionClass, property, isConstructor; + for (property in object) { + if (!(isFunction && property == "prototype") && isProperty.call(object, property) && !(isConstructor = property === "constructor")) { + callback(property); + } + } + if (isConstructor || isProperty.call(object, (property = "constructor"))) { + callback(property); + } + }; + } + return forEach(object, callback); + }; + if (!has("json-stringify")) { + var Escapes = { + 92: "\\\\", + 34: '\\"', + 8: "\\b", + 12: "\\f", + 10: "\\n", + 13: "\\r", + 9: "\\t" + }; + var leadingZeroes = "000000"; + var toPaddedString = function (width, value) { + return (leadingZeroes + (value || 0)).slice(-width); + }; + var unicodePrefix = "\\u00"; + var quote = function (value) { + var result = '"', index = 0, length = value.length, useCharIndex = !charIndexBuggy || length > 10; + var symbols = useCharIndex && (charIndexBuggy ? value.split("") : value); + for (; index < length; index++) { + var charCode = value.charCodeAt(index); + switch (charCode) { + case 8: case 9: case 10: case 12: case 13: case 34: case 92: + result += Escapes[charCode]; + break; + default: + if (charCode < 32) { + result += unicodePrefix + toPaddedString(2, charCode.toString(16)); + break; + } + result += useCharIndex ? symbols[index] : value.charAt(index); + } + } + return result + '"'; + }; + var serialize = function (property, object, callback, properties, whitespace, indentation, stack) { + var value, className, year, month, date, time, hours, minutes, seconds, milliseconds, results, element, index, length, prefix, result; + try { + value = object[property]; + } catch (exception) {} + if (typeof value == "object" && value) { + className = getClass.call(value); + if (className == dateClass && !isProperty.call(value, "toJSON")) { + if (value > -1 / 0 && value < 1 / 0) { + if (getDay) { + date = floor(value / 864e5); + for (year = floor(date / 365.2425) + 1970 - 1; getDay(year + 1, 0) <= date; year++); + for (month = floor((date - getDay(year, 0)) / 30.42); getDay(year, month + 1) <= date; month++); + date = 1 + date - getDay(year, month); + time = (value % 864e5 + 864e5) % 864e5; + hours = floor(time / 36e5) % 24; + minutes = floor(time / 6e4) % 60; + seconds = floor(time / 1e3) % 60; + milliseconds = time % 1e3; + } else { + year = value.getUTCFullYear(); + month = value.getUTCMonth(); + date = value.getUTCDate(); + hours = value.getUTCHours(); + minutes = value.getUTCMinutes(); + seconds = value.getUTCSeconds(); + milliseconds = value.getUTCMilliseconds(); + } + value = (year <= 0 || year >= 1e4 ? (year < 0 ? "-" : "+") + toPaddedString(6, year < 0 ? -year : year) : toPaddedString(4, year)) + + "-" + toPaddedString(2, month + 1) + "-" + toPaddedString(2, date) + + "T" + toPaddedString(2, hours) + ":" + toPaddedString(2, minutes) + ":" + toPaddedString(2, seconds) + + "." + toPaddedString(3, milliseconds) + "Z"; + } else { + value = null; + } + } else if (typeof value.toJSON == "function" && ((className != numberClass && className != stringClass && className != arrayClass) || isProperty.call(value, "toJSON"))) { + value = value.toJSON(property); + } + } + if (callback) { + value = callback.call(object, property, value); + } + if (value === null) { + return "null"; + } + className = getClass.call(value); + if (className == booleanClass) { + return "" + value; + } else if (className == numberClass) { + return value > -1 / 0 && value < 1 / 0 ? "" + value : "null"; + } else if (className == stringClass) { + return quote("" + value); + } + if (typeof value == "object") { + for (length = stack.length; length--;) { + if (stack[length] === value) { + throw TypeError(); + } + } + stack.push(value); + results = []; + prefix = indentation; + indentation += whitespace; + if (className == arrayClass) { + for (index = 0, length = value.length; index < length; index++) { + element = serialize(index, value, callback, properties, whitespace, indentation, stack); + results.push(element === undef ? "null" : element); + } + result = results.length ? (whitespace ? "[\n" + indentation + results.join(",\n" + indentation) + "\n" + prefix + "]" : ("[" + results.join(",") + "]")) : "[]"; + } else { + forEach(properties || value, function (property) { + var element = serialize(property, value, callback, properties, whitespace, indentation, stack); + if (element !== undef) { + results.push(quote(property) + ":" + (whitespace ? " " : "") + element); + } + }); + result = results.length ? (whitespace ? "{\n" + indentation + results.join(",\n" + indentation) + "\n" + prefix + "}" : ("{" + results.join(",") + "}")) : "{}"; + } + stack.pop(); + return result; + } + }; + exports.stringify = function (source, filter, width) { + var whitespace, callback, properties, className; + if (objectTypes[typeof filter] && filter) { + if ((className = getClass.call(filter)) == functionClass) { + callback = filter; + } else if (className == arrayClass) { + properties = {}; + for (var index = 0, length = filter.length, value; index < length; value = filter[index++], ((className = getClass.call(value)), className == stringClass || className == numberClass) && (properties[value] = 1)); + } + } + if (width) { + if ((className = getClass.call(width)) == numberClass) { + if ((width -= width % 1) > 0) { + for (whitespace = "", width > 10 && (width = 10); whitespace.length < width; whitespace += " "); + } + } else if (className == stringClass) { + whitespace = width.length <= 10 ? width : width.slice(0, 10); + } + } + return serialize("", (value = {}, value[""] = source, value), callback, properties, whitespace, "", []); + }; + } + if (!has("json-parse")) { + var fromCharCode = String.fromCharCode; + var Unescapes = { + 92: "\\", + 34: '"', + 47: "/", + 98: "\b", + 116: "\t", + 110: "\n", + 102: "\f", + 114: "\r" + }; + var Index, Source; + var abort = function () { + Index = Source = null; + throw SyntaxError(); + }; + var lex = function () { + var source = Source, length = source.length, value, begin, position, isSigned, charCode; + while (Index < length) { + charCode = source.charCodeAt(Index); + switch (charCode) { + case 9: case 10: case 13: case 32: + Index++; + break; + case 123: case 125: case 91: case 93: case 58: case 44: + value = charIndexBuggy ? source.charAt(Index) : source[Index]; + Index++; + return value; + case 34: + for (value = "@", Index++; Index < length;) { + charCode = source.charCodeAt(Index); + if (charCode < 32) { + abort(); + } else if (charCode == 92) { + charCode = source.charCodeAt(++Index); + switch (charCode) { + case 92: case 34: case 47: case 98: case 116: case 110: case 102: case 114: + value += Unescapes[charCode]; + Index++; + break; + case 117: + begin = ++Index; + for (position = Index + 4; Index < position; Index++) { + charCode = source.charCodeAt(Index); + if (!(charCode >= 48 && charCode <= 57 || charCode >= 97 && charCode <= 102 || charCode >= 65 && charCode <= 70)) { + abort(); + } + } + value += fromCharCode("0x" + source.slice(begin, Index)); + break; + default: + abort(); + } + } else { + if (charCode == 34) { + break; + } + charCode = source.charCodeAt(Index); + begin = Index; + while (charCode >= 32 && charCode != 92 && charCode != 34) { + charCode = source.charCodeAt(++Index); + } + value += source.slice(begin, Index); + } + } + if (source.charCodeAt(Index) == 34) { + Index++; + return value; + } + abort(); + default: + begin = Index; + if (charCode == 45) { + isSigned = true; + charCode = source.charCodeAt(++Index); + } + if (charCode >= 48 && charCode <= 57) { + if (charCode == 48 && ((charCode = source.charCodeAt(Index + 1)), charCode >= 48 && charCode <= 57)) { + abort(); + } + isSigned = false; + for (; Index < length && ((charCode = source.charCodeAt(Index)), charCode >= 48 && charCode <= 57); Index++); + if (source.charCodeAt(Index) == 46) { + position = ++Index; + for (; position < length && ((charCode = source.charCodeAt(position)), charCode >= 48 && charCode <= 57); position++); + if (position == Index) { + abort(); + } + Index = position; + } + charCode = source.charCodeAt(Index); + if (charCode == 101 || charCode == 69) { + charCode = source.charCodeAt(++Index); + if (charCode == 43 || charCode == 45) { + Index++; + } + for (position = Index; position < length && ((charCode = source.charCodeAt(position)), charCode >= 48 && charCode <= 57); position++); + if (position == Index) { + abort(); + } + Index = position; + } + return +source.slice(begin, Index); + } + if (isSigned) { + abort(); + } + if (source.slice(Index, Index + 4) == "true") { + Index += 4; + return true; + } else if (source.slice(Index, Index + 5) == "false") { + Index += 5; + return false; + } else if (source.slice(Index, Index + 4) == "null") { + Index += 4; + return null; + } + abort(); + } + } + return "$"; + }; + var get = function (value) { + var results, hasMembers; + if (value == "$") { + abort(); + } + if (typeof value == "string") { + if ((charIndexBuggy ? value.charAt(0) : value[0]) == "@") { + return value.slice(1); + } + if (value == "[") { + results = []; + for (;; hasMembers || (hasMembers = true)) { + value = lex(); + if (value == "]") { + break; + } + if (hasMembers) { + if (value == ",") { + value = lex(); + if (value == "]") { + abort(); + } + } else { + abort(); + } + } + if (value == ",") { + abort(); + } + results.push(get(value)); + } + return results; + } else if (value == "{") { + results = {}; + for (;; hasMembers || (hasMembers = true)) { + value = lex(); + if (value == "}") { + break; + } + if (hasMembers) { + if (value == ",") { + value = lex(); + if (value == "}") { + abort(); + } + } else { + abort(); + } + } + if (value == "," || typeof value != "string" || (charIndexBuggy ? value.charAt(0) : value[0]) != "@" || lex() != ":") { + abort(); + } + results[value.slice(1)] = get(lex()); + } + return results; + } + abort(); + } + return value; + }; + var update = function (source, property, callback) { + var element = walk(source, property, callback); + if (element === undef) { + delete source[property]; + } else { + source[property] = element; + } + }; + var walk = function (source, property, callback) { + var value = source[property], length; + if (typeof value == "object" && value) { + if (getClass.call(value) == arrayClass) { + for (length = value.length; length--;) { + update(value, length, callback); + } + } else { + forEach(value, function (property) { + update(value, property, callback); + }); + } + } + return callback.call(source, property, value); + }; + exports.parse = function (source, callback) { + var result, value; + Index = 0; + Source = "" + source; + result = get(lex()); + if (lex() != "$") { + abort(); + } + Index = Source = null; + return callback && getClass.call(callback) == functionClass ? walk((value = {}, value[""] = result, value), "", callback) : result; + }; + } + } + exports["runInContext"] = runInContext; + return exports; + } + if (freeExports && !isLoader) { + runInContext(root, freeExports); + } else { + var nativeJSON = root.JSON, + previousJSON = root["JSON3"], + isRestored = false; + var JSON3 = runInContext(root, (root["JSON3"] = { + "noConflict": function () { + if (!isRestored) { + isRestored = true; + root.JSON = nativeJSON; + root["JSON3"] = previousJSON; + nativeJSON = previousJSON = null; + } + return JSON3; + } + })); + root.JSON = { + "parse": JSON3.parse, + "stringify": JSON3.stringify + }; + } + if (isLoader) { + define(function () { + return JSON3; + }); + } +}).call(this); +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{}],3:[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":4,"reduce":5}],4:[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; +}; +},{}],5:[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; +}; +},{}],6:[function(require,module,exports){ +module.exports = function(){ + return "undefined" == typeof window ? "server" : "browser"; +}; +},{}],7:[function(require,module,exports){ +var each = require('../utils/each'), + json = require('../utils/json-shim'); +module.exports = function(params){ + var query = []; + each(params, function(value, key){ + if ('string' !== typeof value) { + value = json.stringify(value); + } + query.push(key + '=' + encodeURIComponent(value)); + }); + return '?' + query.join('&'); +}; +},{"../utils/each":18,"../utils/json-shim":21}],8:[function(require,module,exports){ +module.exports = function(){ + return new Date().getTimezoneOffset() * -60; +}; +},{}],9:[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; +}; +},{}],10:[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; +}; +},{}],11:[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; +}; +},{}],12:[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":18,"./get-xhr-object":10,"superagent":3}],13:[function(require,module,exports){ +var root = 'undefined' !== typeof window ? window : this; +var previous_Keen = root.Keen; +var Emitter = require('./utils/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.7'; +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; +},{"./utils/emitter-shim":19}],14:[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":7,"../helpers/superagent-handle-response":11,"../helpers/superagent-request-types":12,"superagent":3}],15:[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":17}],16:[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('./utils/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/get-query-string":7,"./helpers/get-timezone-offset":8,"./utils/each":18,"./utils/emitter-shim":19,"./utils/extend":20}],17:[function(require,module,exports){ +var each = require("./utils/each"), + extend = require("./utils/extend"), + sendQuery = require("./utils/sendQuery"); +var Keen = require("./"); +var Emitter = require('./utils/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 (errored) { + return; + } + 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; +},{"./":13,"./utils/each":18,"./utils/emitter-shim":19,"./utils/extend":20,"./utils/sendQuery":23}],18:[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; n1)))/4)-w((ag-1901+ah)/100)+w((ag-1601+ah)/400)}}if(!(v=r.hasOwnProperty)){v=function(ai){var ag={},ah;if((ag.__proto__=null,ag.__proto__={toString:1},ag).toString!=y){v=function(al){var ak=this.__proto__,aj=al in (this.__proto__=null,this);this.__proto__=ak;return aj}}else{ah=ag.constructor;v=function(ak){var aj=(this.constructor||ah).prototype;return ak in this&&!(ak in aj&&this[ak]===aj[ak])}}ag=null;return v.call(this,ai)}}q=function(ai,al){var aj=0,ag,ah,ak;(ag=function(){this.valueOf=0}).prototype.valueOf=0;ah=new ag();for(ak in ah){if(v.call(ah,ak)){aj++}}ag=ah=null;if(!aj){ah=["valueOf","toString","toLocaleString","propertyIsEnumerable","isPrototypeOf","hasOwnProperty","constructor"];q=function(an,ar){var aq=y.call(an)==Y,ap,ao;var am=!aq&&typeof an.constructor!="function"&&i[typeof an.hasOwnProperty]&&an.hasOwnProperty||v;for(ap in an){if(!(aq&&ap=="prototype")&&am.call(an,ap)){ar(ap)}}for(ao=ah.length;ap=ah[--ao];am.call(an,ap)&&ar(ap)){}}}else{if(aj==2){q=function(an,aq){var am={},ap=y.call(an)==Y,ao;for(ao in an){if(!(ap&&ao=="prototype")&&!v.call(am,ao)&&(am[ao]=1)&&v.call(an,ao)){aq(ao)}}}}else{q=function(an,aq){var ap=y.call(an)==Y,ao,am;for(ao in an){if(!(ap&&ao=="prototype")&&v.call(an,ao)&&!(am=ao==="constructor")){aq(ao)}}if(am||v.call(an,(ao="constructor"))){aq(ao)}}}}return q(ai,al)};if(!s("json-stringify")){var u={92:"\\\\",34:'\\"',8:"\\b",12:"\\f",10:"\\n",13:"\\r",9:"\\t"};var M="000000";var x=function(ag,ah){return(M+(ah||0)).slice(-ag)};var D="\\u00";var G=function(am){var ah='"',ak=0,al=am.length,ag=!J||al>10;var aj=ag&&(J?am.split(""):am);for(;ak-1/0&&ax<1/0){if(H){aC=w(ax/86400000);for(au=w(aC/365.2425)+1970-1;H(au+1,0)<=aC;au++){}for(aD=w((aC-H(au,0))/30.42);H(au,aD+1)<=aC;aD++){}aC=1+aC-H(au,aD);ao=(ax%86400000+86400000)%86400000;aA=w(ao/3600000)%24;ay=w(ao/60000)%60;av=w(ao/1000)%60;ar=ao%1000}else{au=ax.getUTCFullYear();aD=ax.getUTCMonth();aC=ax.getUTCDate();aA=ax.getUTCHours();ay=ax.getUTCMinutes();av=ax.getUTCSeconds();ar=ax.getUTCMilliseconds()}ax=(au<=0||au>=10000?(au<0?"-":"+")+x(6,au<0?-au:au):x(4,au))+"-"+x(2,aD+1)+"-"+x(2,aC)+"T"+x(2,aA)+":"+x(2,ay)+":"+x(2,av)+"."+x(3,ar)+"Z"}else{ax=null}}else{if(typeof ax.toJSON=="function"&&((ai!=R&&ai!=S&&ai!=I)||v.call(ax,"toJSON"))){ax=ax.toJSON(am)}}}if(ak){ax=ak.call(aE,am,ax)}if(ax===null){return"null"}ai=y.call(ax);if(ai==E){return""+ax}else{if(ai==R){return ax>-1/0&&ax<1/0?""+ax:"null"}else{if(ai==S){return G(""+ax)}}}if(typeof ax=="object"){for(aj=an.length;aj--;){if(an[aj]===ax){throw ae()}}an.push(ax);aw=[];az=ag;ag+=aB;if(ai==I){for(al=0,aj=ax.length;al0){for(ah="",aj>10&&(aj=10);ah.length=48&&ah<=57||ah>=97&&ah<=102||ah>=65&&ah<=70)){L()}}ak+=Q("0x"+al.slice(ai,K));break;default:L()}}else{if(ah==34){break}ah=al.charCodeAt(K);ai=K;while(ah>=32&&ah!=92&&ah!=34){ah=al.charCodeAt(++K)}ak+=al.slice(ai,K)}}}if(al.charCodeAt(K)==34){K++;return ak}L();default:ai=K;if(ah==45){am=true;ah=al.charCodeAt(++K)}if(ah>=48&&ah<=57){if(ah==48&&((ah=al.charCodeAt(K+1)),ah>=48&&ah<=57)){L()}am=false;for(;K=48&&ah<=57);K++){}if(al.charCodeAt(K)==46){ag=++K;for(;ag=48&&ah<=57);ag++){}if(ag==K){L()}K=ag}ah=al.charCodeAt(K);if(ah==101||ah==69){ah=al.charCodeAt(++K);if(ah==43||ah==45){K++}for(ag=K;ag=48&&ah<=57);ag++){}if(ag==K){L()}K=ag}return +al.slice(ai,K)}if(am){L()}if(al.slice(K,K+4)=="true"){K+=4;return true}else{if(al.slice(K,K+5)=="false"){K+=5;return false}else{if(al.slice(K,K+4)=="null"){K+=4;return null}}}L()}}return"$"};var aa=function(ah){var ag,ai;if(ah=="$"){L()}if(typeof ah=="string"){if((J?ah.charAt(0):ah[0])=="@"){return ah.slice(1)}if(ah=="["){ag=[];for(;;ai||(ai=true)){ah=C();if(ah=="]"){break}if(ai){if(ah==","){ah=C();if(ah=="]"){L()}}else{L()}}if(ah==","){L()}ag.push(aa(ah))}return ag}else{if(ah=="{"){ag={};for(;;ai||(ai=true)){ah=C();if(ah=="}"){break}if(ai){if(ah==","){ah=C();if(ah=="}"){L()}}else{L()}}if(ah==","||typeof ah!="string"||(J?ah.charAt(0):ah[0])!="@"||C()!=":"){L()}ag[ah.slice(1)]=aa(C())}return ag}}L()}return ah};var T=function(ai,ah,aj){var ag=A(ai,ah,aj);if(ag===P){delete ai[ah]}else{ai[ah]=ag}};var A=function(aj,ai,ak){var ah=aj[ai],ag;if(typeof ah=="object"&&ah){if(y.call(ah)==I){for(ag=ah.length;ag--;){T(ah,ag,ak)}}else{q(ah,function(al){T(ah,al,ak)})}}return ak.call(aj,ai,ah)};Z.parse=function(ai,aj){var ag,ah;K=0;ab=""+ai;ag=aa(C());if(C()!="$"){L()}K=ab=null;return aj&&y.call(aj)==Y?A((ah={},ah[""]=ag,ah),"",aj):ag}}}Z.runInContext=n;return Z}if(l&&!g){n(m,l)}else{var j=m.JSON,o=m.JSON3,h=false;var k=n(m,(m.JSON3={noConflict:function(){if(!h){h=true;m.JSON=j;m.JSON3=o;j=o=null}return k}}));m.JSON={parse:k.parse,stringify:k.stringify}}if(g){define(function(){return k})}}).call(this)}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{}],3:[function(i,b,t){var l=i("emitter");var k=i("reduce");var p="undefined"==typeof window?this:window;function f(){}function m(u){var v={}.toString.call(u);switch(v){case"[object File]":case"[object Blob]":case"[object FormData]":return true;default:return false}}function n(){if(p.XMLHttpRequest&&("file:"!=p.location.protocol||!p.ActiveXObject)){return new XMLHttpRequest}else{try{return new ActiveXObject("Microsoft.XMLHTTP")}catch(u){}try{return new ActiveXObject("Msxml2.XMLHTTP.6.0")}catch(u){}try{return new ActiveXObject("Msxml2.XMLHTTP.3.0")}catch(u){}try{return new ActiveXObject("Msxml2.XMLHTTP")}catch(u){}}return false}var r="".trim?function(u){return u.trim()}:function(u){return u.replace(/(^\s*|\s*$)/g,"")};function j(u){return u===Object(u)}function o(w){if(!j(w)){return w}var v=[];for(var u in w){if(null!=w[u]){v.push(encodeURIComponent(u)+"="+encodeURIComponent(w[u]))}}return v.join("&")}d.serializeObject=o;function h(A){var y={};var w=A.split("&");var x;var z;for(var v=0,u=w.length;v0){return 2000}}return 16000}},{}],10:[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}},{}],11:[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}},{}],12:[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":18,"./get-xhr-object":10,superagent:3}],13:[function(d,f,c){var b="undefined"!==typeof window?window:this;var h=b.Keen;var g=d("./utils/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.7";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},{"./utils/emitter-shim":19}],14:[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":7,"../helpers/superagent-handle-response":11,"../helpers/superagent-request-types":12,superagent:3}],15:[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":17}],16:[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("./utils/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/get-query-string":7,"./helpers/get-timezone-offset":8,"./utils/each":18,"./utils/emitter-shim":19,"./utils/extend":20}],17:[function(c,b,d){var j=c("./utils/each"),h=c("./utils/extend"),g=c("./utils/sendQuery");var f=c("./");var i=c("./utils/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(o){return}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},{"./":13,"./utils/each":18,"./utils/emitter-shim":19,"./utils/extend":20,"./utils/sendQuery":23}],18:[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))) / 4) - floor((year - 1901 + month) / 100) + floor((year - 1601 + month) / 400); + }; + } + if (!(isProperty = objectProto.hasOwnProperty)) { + isProperty = function (property) { + var members = {}, constructor; + if ((members.__proto__ = null, members.__proto__ = { + "toString": 1 + }, members).toString != getClass) { + isProperty = function (property) { + var original = this.__proto__, result = property in (this.__proto__ = null, this); + this.__proto__ = original; + return result; + }; + } else { + constructor = members.constructor; + isProperty = function (property) { + var parent = (this.constructor || constructor).prototype; + return property in this && !(property in parent && this[property] === parent[property]); + }; + } + members = null; + return isProperty.call(this, property); + }; + } + forEach = function (object, callback) { + var size = 0, Properties, members, property; + (Properties = function () { + this.valueOf = 0; + }).prototype.valueOf = 0; + members = new Properties(); + for (property in members) { + if (isProperty.call(members, property)) { + size++; + } + } + Properties = members = null; + if (!size) { + members = ["valueOf", "toString", "toLocaleString", "propertyIsEnumerable", "isPrototypeOf", "hasOwnProperty", "constructor"]; + forEach = function (object, callback) { + var isFunction = getClass.call(object) == functionClass, property, length; + var hasProperty = !isFunction && typeof object.constructor != "function" && objectTypes[typeof object.hasOwnProperty] && object.hasOwnProperty || isProperty; + for (property in object) { + if (!(isFunction && property == "prototype") && hasProperty.call(object, property)) { + callback(property); + } + } + for (length = members.length; property = members[--length]; hasProperty.call(object, property) && callback(property)); + }; + } else if (size == 2) { + forEach = function (object, callback) { + var members = {}, isFunction = getClass.call(object) == functionClass, property; + for (property in object) { + if (!(isFunction && property == "prototype") && !isProperty.call(members, property) && (members[property] = 1) && isProperty.call(object, property)) { + callback(property); + } + } + }; + } else { + forEach = function (object, callback) { + var isFunction = getClass.call(object) == functionClass, property, isConstructor; + for (property in object) { + if (!(isFunction && property == "prototype") && isProperty.call(object, property) && !(isConstructor = property === "constructor")) { + callback(property); + } + } + if (isConstructor || isProperty.call(object, (property = "constructor"))) { + callback(property); + } + }; + } + return forEach(object, callback); + }; + if (!has("json-stringify")) { + var Escapes = { + 92: "\\\\", + 34: '\\"', + 8: "\\b", + 12: "\\f", + 10: "\\n", + 13: "\\r", + 9: "\\t" + }; + var leadingZeroes = "000000"; + var toPaddedString = function (width, value) { + return (leadingZeroes + (value || 0)).slice(-width); + }; + var unicodePrefix = "\\u00"; + var quote = function (value) { + var result = '"', index = 0, length = value.length, useCharIndex = !charIndexBuggy || length > 10; + var symbols = useCharIndex && (charIndexBuggy ? value.split("") : value); + for (; index < length; index++) { + var charCode = value.charCodeAt(index); + switch (charCode) { + case 8: case 9: case 10: case 12: case 13: case 34: case 92: + result += Escapes[charCode]; + break; + default: + if (charCode < 32) { + result += unicodePrefix + toPaddedString(2, charCode.toString(16)); + break; + } + result += useCharIndex ? symbols[index] : value.charAt(index); + } + } + return result + '"'; + }; + var serialize = function (property, object, callback, properties, whitespace, indentation, stack) { + var value, className, year, month, date, time, hours, minutes, seconds, milliseconds, results, element, index, length, prefix, result; + try { + value = object[property]; + } catch (exception) {} + if (typeof value == "object" && value) { + className = getClass.call(value); + if (className == dateClass && !isProperty.call(value, "toJSON")) { + if (value > -1 / 0 && value < 1 / 0) { + if (getDay) { + date = floor(value / 864e5); + for (year = floor(date / 365.2425) + 1970 - 1; getDay(year + 1, 0) <= date; year++); + for (month = floor((date - getDay(year, 0)) / 30.42); getDay(year, month + 1) <= date; month++); + date = 1 + date - getDay(year, month); + time = (value % 864e5 + 864e5) % 864e5; + hours = floor(time / 36e5) % 24; + minutes = floor(time / 6e4) % 60; + seconds = floor(time / 1e3) % 60; + milliseconds = time % 1e3; + } else { + year = value.getUTCFullYear(); + month = value.getUTCMonth(); + date = value.getUTCDate(); + hours = value.getUTCHours(); + minutes = value.getUTCMinutes(); + seconds = value.getUTCSeconds(); + milliseconds = value.getUTCMilliseconds(); + } + value = (year <= 0 || year >= 1e4 ? (year < 0 ? "-" : "+") + toPaddedString(6, year < 0 ? -year : year) : toPaddedString(4, year)) + + "-" + toPaddedString(2, month + 1) + "-" + toPaddedString(2, date) + + "T" + toPaddedString(2, hours) + ":" + toPaddedString(2, minutes) + ":" + toPaddedString(2, seconds) + + "." + toPaddedString(3, milliseconds) + "Z"; + } else { + value = null; + } + } else if (typeof value.toJSON == "function" && ((className != numberClass && className != stringClass && className != arrayClass) || isProperty.call(value, "toJSON"))) { + value = value.toJSON(property); + } + } + if (callback) { + value = callback.call(object, property, value); + } + if (value === null) { + return "null"; + } + className = getClass.call(value); + if (className == booleanClass) { + return "" + value; + } else if (className == numberClass) { + return value > -1 / 0 && value < 1 / 0 ? "" + value : "null"; + } else if (className == stringClass) { + return quote("" + value); + } + if (typeof value == "object") { + for (length = stack.length; length--;) { + if (stack[length] === value) { + throw TypeError(); + } + } + stack.push(value); + results = []; + prefix = indentation; + indentation += whitespace; + if (className == arrayClass) { + for (index = 0, length = value.length; index < length; index++) { + element = serialize(index, value, callback, properties, whitespace, indentation, stack); + results.push(element === undef ? "null" : element); + } + result = results.length ? (whitespace ? "[\n" + indentation + results.join(",\n" + indentation) + "\n" + prefix + "]" : ("[" + results.join(",") + "]")) : "[]"; + } else { + forEach(properties || value, function (property) { + var element = serialize(property, value, callback, properties, whitespace, indentation, stack); + if (element !== undef) { + results.push(quote(property) + ":" + (whitespace ? " " : "") + element); + } + }); + result = results.length ? (whitespace ? "{\n" + indentation + results.join(",\n" + indentation) + "\n" + prefix + "}" : ("{" + results.join(",") + "}")) : "{}"; + } + stack.pop(); + return result; + } + }; + exports.stringify = function (source, filter, width) { + var whitespace, callback, properties, className; + if (objectTypes[typeof filter] && filter) { + if ((className = getClass.call(filter)) == functionClass) { + callback = filter; + } else if (className == arrayClass) { + properties = {}; + for (var index = 0, length = filter.length, value; index < length; value = filter[index++], ((className = getClass.call(value)), className == stringClass || className == numberClass) && (properties[value] = 1)); + } + } + if (width) { + if ((className = getClass.call(width)) == numberClass) { + if ((width -= width % 1) > 0) { + for (whitespace = "", width > 10 && (width = 10); whitespace.length < width; whitespace += " "); + } + } else if (className == stringClass) { + whitespace = width.length <= 10 ? width : width.slice(0, 10); + } + } + return serialize("", (value = {}, value[""] = source, value), callback, properties, whitespace, "", []); + }; + } + if (!has("json-parse")) { + var fromCharCode = String.fromCharCode; + var Unescapes = { + 92: "\\", + 34: '"', + 47: "/", + 98: "\b", + 116: "\t", + 110: "\n", + 102: "\f", + 114: "\r" + }; + var Index, Source; + var abort = function () { + Index = Source = null; + throw SyntaxError(); + }; + var lex = function () { + var source = Source, length = source.length, value, begin, position, isSigned, charCode; + while (Index < length) { + charCode = source.charCodeAt(Index); + switch (charCode) { + case 9: case 10: case 13: case 32: + Index++; + break; + case 123: case 125: case 91: case 93: case 58: case 44: + value = charIndexBuggy ? source.charAt(Index) : source[Index]; + Index++; + return value; + case 34: + for (value = "@", Index++; Index < length;) { + charCode = source.charCodeAt(Index); + if (charCode < 32) { + abort(); + } else if (charCode == 92) { + charCode = source.charCodeAt(++Index); + switch (charCode) { + case 92: case 34: case 47: case 98: case 116: case 110: case 102: case 114: + value += Unescapes[charCode]; + Index++; + break; + case 117: + begin = ++Index; + for (position = Index + 4; Index < position; Index++) { + charCode = source.charCodeAt(Index); + if (!(charCode >= 48 && charCode <= 57 || charCode >= 97 && charCode <= 102 || charCode >= 65 && charCode <= 70)) { + abort(); + } + } + value += fromCharCode("0x" + source.slice(begin, Index)); + break; + default: + abort(); + } + } else { + if (charCode == 34) { + break; + } + charCode = source.charCodeAt(Index); + begin = Index; + while (charCode >= 32 && charCode != 92 && charCode != 34) { + charCode = source.charCodeAt(++Index); + } + value += source.slice(begin, Index); + } + } + if (source.charCodeAt(Index) == 34) { + Index++; + return value; + } + abort(); + default: + begin = Index; + if (charCode == 45) { + isSigned = true; + charCode = source.charCodeAt(++Index); + } + if (charCode >= 48 && charCode <= 57) { + if (charCode == 48 && ((charCode = source.charCodeAt(Index + 1)), charCode >= 48 && charCode <= 57)) { + abort(); + } + isSigned = false; + for (; Index < length && ((charCode = source.charCodeAt(Index)), charCode >= 48 && charCode <= 57); Index++); + if (source.charCodeAt(Index) == 46) { + position = ++Index; + for (; position < length && ((charCode = source.charCodeAt(position)), charCode >= 48 && charCode <= 57); position++); + if (position == Index) { + abort(); + } + Index = position; + } + charCode = source.charCodeAt(Index); + if (charCode == 101 || charCode == 69) { + charCode = source.charCodeAt(++Index); + if (charCode == 43 || charCode == 45) { + Index++; + } + for (position = Index; position < length && ((charCode = source.charCodeAt(position)), charCode >= 48 && charCode <= 57); position++); + if (position == Index) { + abort(); + } + Index = position; + } + return +source.slice(begin, Index); + } + if (isSigned) { + abort(); + } + if (source.slice(Index, Index + 4) == "true") { + Index += 4; + return true; + } else if (source.slice(Index, Index + 5) == "false") { + Index += 5; + return false; + } else if (source.slice(Index, Index + 4) == "null") { + Index += 4; + return null; + } + abort(); + } + } + return "$"; + }; + var get = function (value) { + var results, hasMembers; + if (value == "$") { + abort(); + } + if (typeof value == "string") { + if ((charIndexBuggy ? value.charAt(0) : value[0]) == "@") { + return value.slice(1); + } + if (value == "[") { + results = []; + for (;; hasMembers || (hasMembers = true)) { + value = lex(); + if (value == "]") { + break; + } + if (hasMembers) { + if (value == ",") { + value = lex(); + if (value == "]") { + abort(); + } + } else { + abort(); + } + } + if (value == ",") { + abort(); + } + results.push(get(value)); + } + return results; + } else if (value == "{") { + results = {}; + for (;; hasMembers || (hasMembers = true)) { + value = lex(); + if (value == "}") { + break; + } + if (hasMembers) { + if (value == ",") { + value = lex(); + if (value == "}") { + abort(); + } + } else { + abort(); + } + } + if (value == "," || typeof value != "string" || (charIndexBuggy ? value.charAt(0) : value[0]) != "@" || lex() != ":") { + abort(); + } + results[value.slice(1)] = get(lex()); + } + return results; + } + abort(); + } + return value; + }; + var update = function (source, property, callback) { + var element = walk(source, property, callback); + if (element === undef) { + delete source[property]; + } else { + source[property] = element; + } + }; + var walk = function (source, property, callback) { + var value = source[property], length; + if (typeof value == "object" && value) { + if (getClass.call(value) == arrayClass) { + for (length = value.length; length--;) { + update(value, length, callback); + } + } else { + forEach(value, function (property) { + update(value, property, callback); + }); + } + } + return callback.call(source, property, value); + }; + exports.parse = function (source, callback) { + var result, value; + Index = 0; + Source = "" + source; + result = get(lex()); + if (lex() != "$") { + abort(); + } + Index = Source = null; + return callback && getClass.call(callback) == functionClass ? walk((value = {}, value[""] = result, value), "", callback) : result; + }; + } + } + exports["runInContext"] = runInContext; + return exports; + } + if (freeExports && !isLoader) { + runInContext(root, freeExports); + } else { + var nativeJSON = root.JSON, + previousJSON = root["JSON3"], + isRestored = false; + var JSON3 = runInContext(root, (root["JSON3"] = { + "noConflict": function () { + if (!isRestored) { + isRestored = true; + root.JSON = nativeJSON; + root["JSON3"] = previousJSON; + nativeJSON = previousJSON = null; + } + return JSON3; + } + })); + root.JSON = { + "parse": JSON3.parse, + "stringify": JSON3.stringify + }; + } + if (isLoader) { + define(function () { + return JSON3; + }); + } +}).call(this); +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{}],4:[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":5,"reduce":6}],5:[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; +}; +},{}],6:[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; +}; +},{}],7:[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":14,"./utils/each":20}],8:[function(require,module,exports){ +module.exports = function(){ + return "undefined" == typeof window ? "server" : "browser"; +}; +},{}],9:[function(require,module,exports){ +var each = require('../utils/each'), + json = require('../utils/json-shim'); +module.exports = function(params){ + var query = []; + each(params, function(value, key){ + if ('string' !== typeof value) { + value = json.stringify(value); + } + query.push(key + '=' + encodeURIComponent(value)); + }); + return '?' + query.join('&'); +}; +},{"../utils/each":20,"../utils/json-shim":23}],10:[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; +}; +},{}],11:[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; +}; +},{}],12:[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; +}; +},{}],13:[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":20,"./get-xhr-object":11,"superagent":4}],14:[function(require,module,exports){ +var root = 'undefined' !== typeof window ? window : this; +var previous_Keen = root.Keen; +var Emitter = require('./utils/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.7'; +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; +},{"./utils/emitter-shim":21}],15:[function(require,module,exports){ +var json = require('../utils/json-shim'); +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( json.stringify(data) ), + modified : new Date().getTime() + }); + return ( url.length < getUrlMaxLength() ) ? url : false; +} +},{"../helpers/get-context":8,"../helpers/get-query-string":9,"../helpers/get-url-max-length":10,"../helpers/get-xhr-object":11,"../helpers/superagent-handle-response":12,"../helpers/superagent-request-types":13,"../index":14,"../utils/base64":19,"../utils/each":20,"../utils/json-shim":23,"superagent":4}],16:[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":8,"../helpers/get-xhr-object":11,"../helpers/superagent-handle-response":12,"../helpers/superagent-request-types":13,"../index":14,"../utils/each":20,"superagent":4}],17:[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); + } +}; +},{}],18:[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":15}],19:[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; + } + } +}; +},{}],20:[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; n1)))/4)-w((ag-1901+ah)/100)+w((ag-1601+ah)/400)}}if(!(v=r.hasOwnProperty)){v=function(ai){var ag={},ah;if((ag.__proto__=null,ag.__proto__={toString:1},ag).toString!=y){v=function(al){var ak=this.__proto__,aj=al in (this.__proto__=null,this);this.__proto__=ak;return aj}}else{ah=ag.constructor;v=function(ak){var aj=(this.constructor||ah).prototype;return ak in this&&!(ak in aj&&this[ak]===aj[ak])}}ag=null;return v.call(this,ai)}}q=function(ai,al){var aj=0,ag,ah,ak;(ag=function(){this.valueOf=0}).prototype.valueOf=0;ah=new ag();for(ak in ah){if(v.call(ah,ak)){aj++}}ag=ah=null;if(!aj){ah=["valueOf","toString","toLocaleString","propertyIsEnumerable","isPrototypeOf","hasOwnProperty","constructor"];q=function(an,ar){var aq=y.call(an)==Y,ap,ao;var am=!aq&&typeof an.constructor!="function"&&i[typeof an.hasOwnProperty]&&an.hasOwnProperty||v;for(ap in an){if(!(aq&&ap=="prototype")&&am.call(an,ap)){ar(ap)}}for(ao=ah.length;ap=ah[--ao];am.call(an,ap)&&ar(ap)){}}}else{if(aj==2){q=function(an,aq){var am={},ap=y.call(an)==Y,ao;for(ao in an){if(!(ap&&ao=="prototype")&&!v.call(am,ao)&&(am[ao]=1)&&v.call(an,ao)){aq(ao)}}}}else{q=function(an,aq){var ap=y.call(an)==Y,ao,am;for(ao in an){if(!(ap&&ao=="prototype")&&v.call(an,ao)&&!(am=ao==="constructor")){aq(ao)}}if(am||v.call(an,(ao="constructor"))){aq(ao)}}}}return q(ai,al)};if(!s("json-stringify")){var u={92:"\\\\",34:'\\"',8:"\\b",12:"\\f",10:"\\n",13:"\\r",9:"\\t"};var M="000000";var x=function(ag,ah){return(M+(ah||0)).slice(-ag)};var D="\\u00";var G=function(am){var ah='"',ak=0,al=am.length,ag=!J||al>10;var aj=ag&&(J?am.split(""):am);for(;ak-1/0&&ax<1/0){if(H){aC=w(ax/86400000);for(au=w(aC/365.2425)+1970-1;H(au+1,0)<=aC;au++){}for(aD=w((aC-H(au,0))/30.42);H(au,aD+1)<=aC;aD++){}aC=1+aC-H(au,aD);ao=(ax%86400000+86400000)%86400000;aA=w(ao/3600000)%24;ay=w(ao/60000)%60;av=w(ao/1000)%60;ar=ao%1000}else{au=ax.getUTCFullYear();aD=ax.getUTCMonth();aC=ax.getUTCDate();aA=ax.getUTCHours();ay=ax.getUTCMinutes();av=ax.getUTCSeconds();ar=ax.getUTCMilliseconds()}ax=(au<=0||au>=10000?(au<0?"-":"+")+x(6,au<0?-au:au):x(4,au))+"-"+x(2,aD+1)+"-"+x(2,aC)+"T"+x(2,aA)+":"+x(2,ay)+":"+x(2,av)+"."+x(3,ar)+"Z"}else{ax=null}}else{if(typeof ax.toJSON=="function"&&((ai!=R&&ai!=S&&ai!=I)||v.call(ax,"toJSON"))){ax=ax.toJSON(am)}}}if(ak){ax=ak.call(aE,am,ax)}if(ax===null){return"null"}ai=y.call(ax);if(ai==E){return""+ax}else{if(ai==R){return ax>-1/0&&ax<1/0?""+ax:"null"}else{if(ai==S){return G(""+ax)}}}if(typeof ax=="object"){for(aj=an.length;aj--;){if(an[aj]===ax){throw ae()}}an.push(ax);aw=[];az=ag;ag+=aB;if(ai==I){for(al=0,aj=ax.length;al0){for(ah="",aj>10&&(aj=10);ah.length=48&&ah<=57||ah>=97&&ah<=102||ah>=65&&ah<=70)){L()}}ak+=Q("0x"+al.slice(ai,K));break;default:L()}}else{if(ah==34){break}ah=al.charCodeAt(K);ai=K;while(ah>=32&&ah!=92&&ah!=34){ah=al.charCodeAt(++K)}ak+=al.slice(ai,K)}}}if(al.charCodeAt(K)==34){K++;return ak}L();default:ai=K;if(ah==45){am=true;ah=al.charCodeAt(++K)}if(ah>=48&&ah<=57){if(ah==48&&((ah=al.charCodeAt(K+1)),ah>=48&&ah<=57)){L()}am=false;for(;K=48&&ah<=57);K++){}if(al.charCodeAt(K)==46){ag=++K;for(;ag=48&&ah<=57);ag++){}if(ag==K){L()}K=ag}ah=al.charCodeAt(K);if(ah==101||ah==69){ah=al.charCodeAt(++K);if(ah==43||ah==45){K++}for(ag=K;ag=48&&ah<=57);ag++){}if(ag==K){L()}K=ag}return +al.slice(ai,K)}if(am){L()}if(al.slice(K,K+4)=="true"){K+=4;return true}else{if(al.slice(K,K+5)=="false"){K+=5;return false}else{if(al.slice(K,K+4)=="null"){K+=4;return null}}}L()}}return"$"};var aa=function(ah){var ag,ai;if(ah=="$"){L()}if(typeof ah=="string"){if((J?ah.charAt(0):ah[0])=="@"){return ah.slice(1)}if(ah=="["){ag=[];for(;;ai||(ai=true)){ah=C();if(ah=="]"){break}if(ai){if(ah==","){ah=C();if(ah=="]"){L()}}else{L()}}if(ah==","){L()}ag.push(aa(ah))}return ag}else{if(ah=="{"){ag={};for(;;ai||(ai=true)){ah=C();if(ah=="}"){break}if(ai){if(ah==","){ah=C();if(ah=="}"){L()}}else{L()}}if(ah==","||typeof ah!="string"||(J?ah.charAt(0):ah[0])!="@"||C()!=":"){L()}ag[ah.slice(1)]=aa(C())}return ag}}L()}return ah};var T=function(ai,ah,aj){var ag=A(ai,ah,aj);if(ag===P){delete ai[ah]}else{ai[ah]=ag}};var A=function(aj,ai,ak){var ah=aj[ai],ag;if(typeof ah=="object"&&ah){if(y.call(ah)==I){for(ag=ah.length;ag--;){T(ah,ag,ak)}}else{q(ah,function(al){T(ah,al,ak)})}}return ak.call(aj,ai,ah)};Z.parse=function(ai,aj){var ag,ah;K=0;ab=""+ai;ag=aa(C());if(C()!="$"){L()}K=ab=null;return aj&&y.call(aj)==Y?A((ah={},ah[""]=ag,ah),"",aj):ag}}}Z.runInContext=n;return Z}if(l&&!g){n(m,l)}else{var j=m.JSON,o=m.JSON3,h=false;var k=n(m,(m.JSON3={noConflict:function(){if(!h){h=true;m.JSON=j;m.JSON3=o;j=o=null}return k}}));m.JSON={parse:k.parse,stringify:k.stringify}}if(g){define(function(){return k})}}).call(this)}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{}],4:[function(i,b,t){var l=i("emitter");var k=i("reduce");var p="undefined"==typeof window?this:window;function f(){}function m(u){var v={}.toString.call(u);switch(v){case"[object File]":case"[object Blob]":case"[object FormData]":return true;default:return false}}function n(){if(p.XMLHttpRequest&&("file:"!=p.location.protocol||!p.ActiveXObject)){return new XMLHttpRequest}else{try{return new ActiveXObject("Microsoft.XMLHTTP")}catch(u){}try{return new ActiveXObject("Msxml2.XMLHTTP.6.0")}catch(u){}try{return new ActiveXObject("Msxml2.XMLHTTP.3.0")}catch(u){}try{return new ActiveXObject("Msxml2.XMLHTTP")}catch(u){}}return false}var r="".trim?function(u){return u.trim()}:function(u){return u.replace(/(^\s*|\s*$)/g,"")};function j(u){return u===Object(u)}function o(w){if(!j(w)){return w}var v=[];for(var u in w){if(null!=w[u]){v.push(encodeURIComponent(u)+"="+encodeURIComponent(w[u]))}}return v.join("&")}d.serializeObject=o;function h(A){var y={};var w=A.split("&");var x;var z;for(var v=0,u=w.length;v0){return 2000}}return 16000}},{}],11:[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}},{}],12:[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}},{}],13:[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":20,"./get-xhr-object":11,superagent:4}],14:[function(d,f,c){var b="undefined"!==typeof window?window:this;var h=b.Keen;var g=d("./utils/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.7";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},{"./utils/emitter-shim":21}],15:[function(f,c,h){var p=f("../utils/json-shim");var g=f("superagent");var i=f("../index");var j=f("../utils/base64"),m=f("../utils/each"),n=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"),o=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&&n()==="browser"){g.get(z).use(k(q,{async:r})).end(w)}else{if(a()||n()==="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){o(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(p.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":8,"../helpers/get-xhr-object":11,"../helpers/superagent-handle-response":12,"../helpers/superagent-request-types":13,"../index":14,"../utils/each":20,superagent:4}],17:[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)}}},{}],18:[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":15}],19:[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}}}},{}],20:[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))) / 4) - floor((year - 1901 + month) / 100) + floor((year - 1601 + month) / 400); + }; + } + if (!(isProperty = objectProto.hasOwnProperty)) { + isProperty = function (property) { + var members = {}, constructor; + if ((members.__proto__ = null, members.__proto__ = { + "toString": 1 + }, members).toString != getClass) { + isProperty = function (property) { + var original = this.__proto__, result = property in (this.__proto__ = null, this); + this.__proto__ = original; + return result; + }; + } else { + constructor = members.constructor; + isProperty = function (property) { + var parent = (this.constructor || constructor).prototype; + return property in this && !(property in parent && this[property] === parent[property]); + }; + } + members = null; + return isProperty.call(this, property); + }; + } + forEach = function (object, callback) { + var size = 0, Properties, members, property; + (Properties = function () { + this.valueOf = 0; + }).prototype.valueOf = 0; + members = new Properties(); + for (property in members) { + if (isProperty.call(members, property)) { + size++; + } + } + Properties = members = null; + if (!size) { + members = ["valueOf", "toString", "toLocaleString", "propertyIsEnumerable", "isPrototypeOf", "hasOwnProperty", "constructor"]; + forEach = function (object, callback) { + var isFunction = getClass.call(object) == functionClass, property, length; + var hasProperty = !isFunction && typeof object.constructor != "function" && objectTypes[typeof object.hasOwnProperty] && object.hasOwnProperty || isProperty; + for (property in object) { + if (!(isFunction && property == "prototype") && hasProperty.call(object, property)) { + callback(property); + } + } + for (length = members.length; property = members[--length]; hasProperty.call(object, property) && callback(property)); + }; + } else if (size == 2) { + forEach = function (object, callback) { + var members = {}, isFunction = getClass.call(object) == functionClass, property; + for (property in object) { + if (!(isFunction && property == "prototype") && !isProperty.call(members, property) && (members[property] = 1) && isProperty.call(object, property)) { + callback(property); + } + } + }; + } else { + forEach = function (object, callback) { + var isFunction = getClass.call(object) == functionClass, property, isConstructor; + for (property in object) { + if (!(isFunction && property == "prototype") && isProperty.call(object, property) && !(isConstructor = property === "constructor")) { + callback(property); + } + } + if (isConstructor || isProperty.call(object, (property = "constructor"))) { + callback(property); + } + }; + } + return forEach(object, callback); + }; + if (!has("json-stringify")) { + var Escapes = { + 92: "\\\\", + 34: '\\"', + 8: "\\b", + 12: "\\f", + 10: "\\n", + 13: "\\r", + 9: "\\t" + }; + var leadingZeroes = "000000"; + var toPaddedString = function (width, value) { + return (leadingZeroes + (value || 0)).slice(-width); + }; + var unicodePrefix = "\\u00"; + var quote = function (value) { + var result = '"', index = 0, length = value.length, useCharIndex = !charIndexBuggy || length > 10; + var symbols = useCharIndex && (charIndexBuggy ? value.split("") : value); + for (; index < length; index++) { + var charCode = value.charCodeAt(index); + switch (charCode) { + case 8: case 9: case 10: case 12: case 13: case 34: case 92: + result += Escapes[charCode]; + break; + default: + if (charCode < 32) { + result += unicodePrefix + toPaddedString(2, charCode.toString(16)); + break; + } + result += useCharIndex ? symbols[index] : value.charAt(index); + } + } + return result + '"'; + }; + var serialize = function (property, object, callback, properties, whitespace, indentation, stack) { + var value, className, year, month, date, time, hours, minutes, seconds, milliseconds, results, element, index, length, prefix, result; + try { + value = object[property]; + } catch (exception) {} + if (typeof value == "object" && value) { + className = getClass.call(value); + if (className == dateClass && !isProperty.call(value, "toJSON")) { + if (value > -1 / 0 && value < 1 / 0) { + if (getDay) { + date = floor(value / 864e5); + for (year = floor(date / 365.2425) + 1970 - 1; getDay(year + 1, 0) <= date; year++); + for (month = floor((date - getDay(year, 0)) / 30.42); getDay(year, month + 1) <= date; month++); + date = 1 + date - getDay(year, month); + time = (value % 864e5 + 864e5) % 864e5; + hours = floor(time / 36e5) % 24; + minutes = floor(time / 6e4) % 60; + seconds = floor(time / 1e3) % 60; + milliseconds = time % 1e3; + } else { + year = value.getUTCFullYear(); + month = value.getUTCMonth(); + date = value.getUTCDate(); + hours = value.getUTCHours(); + minutes = value.getUTCMinutes(); + seconds = value.getUTCSeconds(); + milliseconds = value.getUTCMilliseconds(); + } + value = (year <= 0 || year >= 1e4 ? (year < 0 ? "-" : "+") + toPaddedString(6, year < 0 ? -year : year) : toPaddedString(4, year)) + + "-" + toPaddedString(2, month + 1) + "-" + toPaddedString(2, date) + + "T" + toPaddedString(2, hours) + ":" + toPaddedString(2, minutes) + ":" + toPaddedString(2, seconds) + + "." + toPaddedString(3, milliseconds) + "Z"; + } else { + value = null; + } + } else if (typeof value.toJSON == "function" && ((className != numberClass && className != stringClass && className != arrayClass) || isProperty.call(value, "toJSON"))) { + value = value.toJSON(property); + } + } + if (callback) { + value = callback.call(object, property, value); + } + if (value === null) { + return "null"; + } + className = getClass.call(value); + if (className == booleanClass) { + return "" + value; + } else if (className == numberClass) { + return value > -1 / 0 && value < 1 / 0 ? "" + value : "null"; + } else if (className == stringClass) { + return quote("" + value); + } + if (typeof value == "object") { + for (length = stack.length; length--;) { + if (stack[length] === value) { + throw TypeError(); + } + } + stack.push(value); + results = []; + prefix = indentation; + indentation += whitespace; + if (className == arrayClass) { + for (index = 0, length = value.length; index < length; index++) { + element = serialize(index, value, callback, properties, whitespace, indentation, stack); + results.push(element === undef ? "null" : element); + } + result = results.length ? (whitespace ? "[\n" + indentation + results.join(",\n" + indentation) + "\n" + prefix + "]" : ("[" + results.join(",") + "]")) : "[]"; + } else { + forEach(properties || value, function (property) { + var element = serialize(property, value, callback, properties, whitespace, indentation, stack); + if (element !== undef) { + results.push(quote(property) + ":" + (whitespace ? " " : "") + element); + } + }); + result = results.length ? (whitespace ? "{\n" + indentation + results.join(",\n" + indentation) + "\n" + prefix + "}" : ("{" + results.join(",") + "}")) : "{}"; + } + stack.pop(); + return result; + } + }; + exports.stringify = function (source, filter, width) { + var whitespace, callback, properties, className; + if (objectTypes[typeof filter] && filter) { + if ((className = getClass.call(filter)) == functionClass) { + callback = filter; + } else if (className == arrayClass) { + properties = {}; + for (var index = 0, length = filter.length, value; index < length; value = filter[index++], ((className = getClass.call(value)), className == stringClass || className == numberClass) && (properties[value] = 1)); + } + } + if (width) { + if ((className = getClass.call(width)) == numberClass) { + if ((width -= width % 1) > 0) { + for (whitespace = "", width > 10 && (width = 10); whitespace.length < width; whitespace += " "); + } + } else if (className == stringClass) { + whitespace = width.length <= 10 ? width : width.slice(0, 10); + } + } + return serialize("", (value = {}, value[""] = source, value), callback, properties, whitespace, "", []); + }; + } + if (!has("json-parse")) { + var fromCharCode = String.fromCharCode; + var Unescapes = { + 92: "\\", + 34: '"', + 47: "/", + 98: "\b", + 116: "\t", + 110: "\n", + 102: "\f", + 114: "\r" + }; + var Index, Source; + var abort = function () { + Index = Source = null; + throw SyntaxError(); + }; + var lex = function () { + var source = Source, length = source.length, value, begin, position, isSigned, charCode; + while (Index < length) { + charCode = source.charCodeAt(Index); + switch (charCode) { + case 9: case 10: case 13: case 32: + Index++; + break; + case 123: case 125: case 91: case 93: case 58: case 44: + value = charIndexBuggy ? source.charAt(Index) : source[Index]; + Index++; + return value; + case 34: + for (value = "@", Index++; Index < length;) { + charCode = source.charCodeAt(Index); + if (charCode < 32) { + abort(); + } else if (charCode == 92) { + charCode = source.charCodeAt(++Index); + switch (charCode) { + case 92: case 34: case 47: case 98: case 116: case 110: case 102: case 114: + value += Unescapes[charCode]; + Index++; + break; + case 117: + begin = ++Index; + for (position = Index + 4; Index < position; Index++) { + charCode = source.charCodeAt(Index); + if (!(charCode >= 48 && charCode <= 57 || charCode >= 97 && charCode <= 102 || charCode >= 65 && charCode <= 70)) { + abort(); + } + } + value += fromCharCode("0x" + source.slice(begin, Index)); + break; + default: + abort(); + } + } else { + if (charCode == 34) { + break; + } + charCode = source.charCodeAt(Index); + begin = Index; + while (charCode >= 32 && charCode != 92 && charCode != 34) { + charCode = source.charCodeAt(++Index); + } + value += source.slice(begin, Index); + } + } + if (source.charCodeAt(Index) == 34) { + Index++; + return value; + } + abort(); + default: + begin = Index; + if (charCode == 45) { + isSigned = true; + charCode = source.charCodeAt(++Index); + } + if (charCode >= 48 && charCode <= 57) { + if (charCode == 48 && ((charCode = source.charCodeAt(Index + 1)), charCode >= 48 && charCode <= 57)) { + abort(); + } + isSigned = false; + for (; Index < length && ((charCode = source.charCodeAt(Index)), charCode >= 48 && charCode <= 57); Index++); + if (source.charCodeAt(Index) == 46) { + position = ++Index; + for (; position < length && ((charCode = source.charCodeAt(position)), charCode >= 48 && charCode <= 57); position++); + if (position == Index) { + abort(); + } + Index = position; + } + charCode = source.charCodeAt(Index); + if (charCode == 101 || charCode == 69) { + charCode = source.charCodeAt(++Index); + if (charCode == 43 || charCode == 45) { + Index++; + } + for (position = Index; position < length && ((charCode = source.charCodeAt(position)), charCode >= 48 && charCode <= 57); position++); + if (position == Index) { + abort(); + } + Index = position; + } + return +source.slice(begin, Index); + } + if (isSigned) { + abort(); + } + if (source.slice(Index, Index + 4) == "true") { + Index += 4; + return true; + } else if (source.slice(Index, Index + 5) == "false") { + Index += 5; + return false; + } else if (source.slice(Index, Index + 4) == "null") { + Index += 4; + return null; + } + abort(); + } + } + return "$"; + }; + var get = function (value) { + var results, hasMembers; + if (value == "$") { + abort(); + } + if (typeof value == "string") { + if ((charIndexBuggy ? value.charAt(0) : value[0]) == "@") { + return value.slice(1); + } + if (value == "[") { + results = []; + for (;; hasMembers || (hasMembers = true)) { + value = lex(); + if (value == "]") { + break; + } + if (hasMembers) { + if (value == ",") { + value = lex(); + if (value == "]") { + abort(); + } + } else { + abort(); + } + } + if (value == ",") { + abort(); + } + results.push(get(value)); + } + return results; + } else if (value == "{") { + results = {}; + for (;; hasMembers || (hasMembers = true)) { + value = lex(); + if (value == "}") { + break; + } + if (hasMembers) { + if (value == ",") { + value = lex(); + if (value == "}") { + abort(); + } + } else { + abort(); + } + } + if (value == "," || typeof value != "string" || (charIndexBuggy ? value.charAt(0) : value[0]) != "@" || lex() != ":") { + abort(); + } + results[value.slice(1)] = get(lex()); + } + return results; + } + abort(); + } + return value; + }; + var update = function (source, property, callback) { + var element = walk(source, property, callback); + if (element === undef) { + delete source[property]; + } else { + source[property] = element; + } + }; + var walk = function (source, property, callback) { + var value = source[property], length; + if (typeof value == "object" && value) { + if (getClass.call(value) == arrayClass) { + for (length = value.length; length--;) { + update(value, length, callback); + } + } else { + forEach(value, function (property) { + update(value, property, callback); + }); + } + } + return callback.call(source, property, value); + }; + exports.parse = function (source, callback) { + var result, value; + Index = 0; + Source = "" + source; + result = get(lex()); + if (lex() != "$") { + abort(); + } + Index = Source = null; + return callback && getClass.call(callback) == functionClass ? walk((value = {}, value[""] = result, value), "", callback) : result; + }; + } + } + exports["runInContext"] = runInContext; + return exports; + } + if (freeExports && !isLoader) { + runInContext(root, freeExports); + } else { + var nativeJSON = root.JSON, + previousJSON = root["JSON3"], + isRestored = false; + var JSON3 = runInContext(root, (root["JSON3"] = { + "noConflict": function () { + if (!isRestored) { + isRestored = true; + root.JSON = nativeJSON; + root["JSON3"] = previousJSON; + nativeJSON = previousJSON = null; + } + return JSON3; + } + })); + root.JSON = { + "parse": JSON3.parse, + "stringify": JSON3.stringify + }; + } + if (isLoader) { + define(function () { + return JSON3; + }); + } +}).call(this); +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{}],4:[function(require,module,exports){ +/** + * Copyright (c) 2011-2014 Felix Gnass + * Licensed under the MIT license + * http://spin.js.org/ + * + * Example: + var opts = { + lines: 12 + , length: 7 + , width: 5 + , radius: 10 + , scale: 1.0 + , corners: 1 + , color: '#000' + , opacity: 1/4 + , rotate: 0 + , direction: 1 + , speed: 1 + , trail: 100 + , fps: 20 + , zIndex: 2e9 + , className: 'spinner' + , top: '50%' + , left: '50%' + , shadow: false + , hwaccel: false + , position: 'absolute' + } + var target = document.getElementById('foo') + var spinner = new Spinner(opts).spin(target) + */ +;(function (root, factory) { + /* CommonJS */ + if (typeof exports == 'object') module.exports = factory() + /* AMD module */ + else if (typeof define == 'function' && define.amd) define(factory) + /* Browser global */ + else root.Spinner = factory() +}(this, function () { + "use strict" + var prefixes = ['webkit', 'Moz', 'ms', 'O'] /* Vendor prefixes */ + , animations = {} /* Animation rules keyed by their name */ + , useCssAnimations /* Whether to use CSS animations or setTimeout */ + , sheet /* A stylesheet to hold the @keyframe or VML rules. */ + /** + * Utility function to create elements. If no tag name is given, + * a DIV is created. Optionally properties can be passed. + */ + function createEl (tag, prop) { + var el = document.createElement(tag || 'div') + , n + for (n in prop) el[n] = prop[n] + return el + } + /** + * Appends children and returns the parent. + */ + function ins (parent /* child1, child2, ...*/) { + for (var i = 1, n = arguments.length; i < n; i++) { + parent.appendChild(arguments[i]) + } + return parent + } + /** + * Creates an opacity keyframe animation rule and returns its name. + * Since most mobile Webkits have timing issues with animation-delay, + * we create separate rules for each line/segment. + */ + function addAnimation (alpha, trail, i, lines) { + var name = ['opacity', trail, ~~(alpha * 100), i, lines].join('-') + , start = 0.01 + i/lines * 100 + , z = Math.max(1 - (1-alpha) / trail * (100-start), alpha) + , prefix = useCssAnimations.substring(0, useCssAnimations.indexOf('Animation')).toLowerCase() + , pre = prefix && '-' + prefix + '-' || '' + if (!animations[name]) { + sheet.insertRule( + '@' + pre + 'keyframes ' + name + '{' + + '0%{opacity:' + z + '}' + + start + '%{opacity:' + alpha + '}' + + (start+0.01) + '%{opacity:1}' + + (start+trail) % 100 + '%{opacity:' + alpha + '}' + + '100%{opacity:' + z + '}' + + '}', sheet.cssRules.length) + animations[name] = 1 + } + return name + } + /** + * Tries various vendor prefixes and returns the first supported property. + */ + function vendor (el, prop) { + var s = el.style + , pp + , i + prop = prop.charAt(0).toUpperCase() + prop.slice(1) + if (s[prop] !== undefined) return prop + for (i = 0; i < prefixes.length; i++) { + pp = prefixes[i]+prop + if (s[pp] !== undefined) return pp + } + } + /** + * Sets multiple style properties at once. + */ + function css (el, prop) { + for (var n in prop) { + el.style[vendor(el, n) || n] = prop[n] + } + return el + } + /** + * Fills in default values. + */ + function merge (obj) { + for (var i = 1; i < arguments.length; i++) { + var def = arguments[i] + for (var n in def) { + if (obj[n] === undefined) obj[n] = def[n] + } + } + return obj + } + /** + * Returns the line color from the given string or array. + */ + function getColor (color, idx) { + return typeof color == 'string' ? color : color[idx % color.length] + } + var defaults = { + lines: 12 + , length: 7 + , width: 5 + , radius: 10 + , scale: 1.0 + , corners: 1 + , color: '#000' + , opacity: 1/4 + , rotate: 0 + , direction: 1 + , speed: 1 + , trail: 100 + , fps: 20 + , zIndex: 2e9 + , className: 'spinner' + , top: '50%' + , left: '50%' + , shadow: false + , hwaccel: false + , position: 'absolute' + } + /** The constructor */ + function Spinner (o) { + this.opts = merge(o || {}, Spinner.defaults, defaults) + } + Spinner.defaults = {} + merge(Spinner.prototype, { + /** + * Adds the spinner to the given target element. If this instance is already + * spinning, it is automatically removed from its previous target b calling + * stop() internally. + */ + spin: function (target) { + this.stop() + var self = this + , o = self.opts + , el = self.el = createEl(null, {className: o.className}) + css(el, { + position: o.position + , width: 0 + , zIndex: o.zIndex + , left: o.left + , top: o.top + }) + if (target) { + target.insertBefore(el, target.firstChild || null) + } + el.setAttribute('role', 'progressbar') + self.lines(el, self.opts) + if (!useCssAnimations) { + var i = 0 + , start = (o.lines - 1) * (1 - o.direction) / 2 + , alpha + , fps = o.fps + , f = fps / o.speed + , ostep = (1 - o.opacity) / (f * o.trail / 100) + , astep = f / o.lines + ;(function anim () { + i++ + for (var j = 0; j < o.lines; j++) { + alpha = Math.max(1 - (i + (o.lines - j) * astep) % f * ostep, o.opacity) + self.opacity(el, j * o.direction + start, alpha, o) + } + self.timeout = self.el && setTimeout(anim, ~~(1000 / fps)) + })() + } + return self + } + /** + * Stops and removes the Spinner. + */ + , stop: function () { + var el = this.el + if (el) { + clearTimeout(this.timeout) + if (el.parentNode) el.parentNode.removeChild(el) + this.el = undefined + } + return this + } + /** + * Internal method that draws the individual lines. Will be overwritten + * in VML fallback mode below. + */ + , lines: function (el, o) { + var i = 0 + , start = (o.lines - 1) * (1 - o.direction) / 2 + , seg + function fill (color, shadow) { + return css(createEl(), { + position: 'absolute' + , width: o.scale * (o.length + o.width) + 'px' + , height: o.scale * o.width + 'px' + , background: color + , boxShadow: shadow + , transformOrigin: 'left' + , transform: 'rotate(' + ~~(360/o.lines*i + o.rotate) + 'deg) translate(' + o.scale*o.radius + 'px' + ',0)' + , borderRadius: (o.corners * o.scale * o.width >> 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 +})); +},{}],5:[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":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 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":16,"./utils/each":28}],9:[function(require,module,exports){ +module.exports = function(){ + return "undefined" == typeof window ? "server" : "browser"; +}; +},{}],10:[function(require,module,exports){ +var each = require('../utils/each'), + json = require('../utils/json-shim'); +module.exports = function(params){ + var query = []; + each(params, function(value, key){ + if ('string' !== typeof value) { + value = json.stringify(value); + } + query.push(key + '=' + encodeURIComponent(value)); + }); + return '?' + query.join('&'); +}; +},{"../utils/each":28,"../utils/json-shim":31}],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":28,"./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('./utils/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.7'; +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; +},{"./utils/emitter-shim":29}],17:[function(require,module,exports){ +var json = require('../utils/json-shim'); +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( json.stringify(data) ), + modified : new Date().getTime() + }); + return ( url.length < getUrlMaxLength() ) ? url : false; +} +},{"../helpers/get-context":9,"../helpers/get-query-string":10,"../helpers/get-url-max-length":12,"../helpers/get-xhr-object":13,"../helpers/superagent-handle-response":14,"../helpers/superagent-request-types":15,"../index":16,"../utils/base64":26,"../utils/each":28,"../utils/json-shim":31,"superagent":5}],18:[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":9,"../helpers/get-xhr-object":13,"../helpers/superagent-handle-response":14,"../helpers/superagent-request-types":15,"../index":16,"../utils/each":28,"superagent":5}],19:[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}],20:[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":14,"superagent":5}],21:[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":25}],22:[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); + } +}; +},{}],23:[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":17}],24:[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('./utils/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/get-query-string":10,"./helpers/get-timezone-offset":11,"./utils/each":28,"./utils/emitter-shim":29,"./utils/extend":30}],25:[function(require,module,exports){ +var each = require("./utils/each"), + extend = require("./utils/extend"), + sendQuery = require("./utils/sendQuery"); +var Keen = require("./"); +var Emitter = require('./utils/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 (errored) { + return; + } + 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,"./utils/each":28,"./utils/emitter-shim":29,"./utils/extend":30,"./utils/sendQuery":33}],26:[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; + } + } +}; +},{}],27:[function(require,module,exports){ +var json = require('./json-shim'); +module.exports = function(target) { + return json.parse( json.stringify( target ) ); +}; +},{"./json-shim":31}],28:[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/utils/clone":27,"../core/utils/each":28,"../core/utils/emitter-shim":29,"./utils/flatten":47,"./utils/parse":48}],35:[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":30,"./dataset":34,"./lib/analyses":36,"./lib/append":37,"./lib/delete":38,"./lib/filter":39,"./lib/format":40,"./lib/insert":41,"./lib/select":42,"./lib/set":43,"./lib/sort":44,"./lib/update":45}],36:[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":28}],37:[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":28,"../utils/create-null-list":46}],38:[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":28}],39:[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":28}],40:[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":28}],41:[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":28,"../utils/create-null-list":46,"./append":37}],42:[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":28}],43:[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":28,"./append":37,"./select":42}],44:[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":28}],45:[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":28,"../utils/create-null-list":46,"./append":37}],46:[function(require,module,exports){ +module.exports = function(len){ + var list = new Array(); + for (i = 0; i < len; i++) { + list.push(null); + } + return list; +}; +},{}],47:[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; +} +},{}],48:[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":28}],49:[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":28,"../../core/utils/extend":30,"../dataviz":53}],50:[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":28,"../../core/utils/extend":30,"../dataviz":53}],51:[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":16,"../../core/utils/each":28,"../../core/utils/extend":30,"../dataviz":53}],52:[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":16,"../../core/utils/clone":27,"../../core/utils/each":28,"../../core/utils/extend":30,"../dataviz":53,"../utils/prettyNumber":92}],53:[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/utils/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":16,"../core/utils/clone":27,"../core/utils/each":28,"../core/utils/emitter-shim":29,"../core/utils/extend":30,"../dataset":35,"./utils/loadScript":90,"./utils/loadStyle":91}],54:[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":25,"../../core/utils/clone":27,"../../core/utils/extend":30,"../dataviz":53}],55:[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":30,"../dataviz":53}],56:[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":28,"../../dataset":35}],57:[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; +}; +},{}],58:[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; +}; +},{}],59:[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":30,"./dataviz":53,"./lib/actions/destroy":60,"./lib/actions/error":61,"./lib/actions/initialize":62,"./lib/actions/render":63,"./lib/actions/update":64,"./lib/adapter":65,"./lib/attributes":66,"./lib/call":67,"./lib/chartOptions":68,"./lib/chartType":69,"./lib/colorMapping":70,"./lib/colors":71,"./lib/data":72,"./lib/dataType":73,"./lib/defaultChartType":74,"./lib/el":75,"./lib/height":76,"./lib/indexBy":77,"./lib/labelMapping":78,"./lib/labels":79,"./lib/library":80,"./lib/parseRawData":81,"./lib/parseRequest":82,"./lib/prepare":83,"./lib/sortGroups":84,"./lib/sortIntervals":85,"./lib/stacked":86,"./lib/title":87,"./lib/width":88}],60:[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":55}],61:[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":53,"../../helpers/getAdapterActions":55}],62:[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":53,"../../helpers/getAdapterActions":55}],63:[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":55,"../../utils/applyTransforms":89}],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 (actions.update) { + actions.update.apply(this, arguments); + } else if (actions.render) { + this.render(); + } + return this; +}; +},{"../../helpers/getAdapterActions":55,"../../utils/applyTransforms":89}],65:[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":28}],66:[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":28,"./chartOptions":68}],67:[function(require,module,exports){ +module.exports = function(fn){ + fn.call(this); + return this; +}; +},{}],68:[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":30}],69:[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; +}; +},{}],70:[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":28}],71:[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; +}; +},{}],72:[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":25,"../../dataset":35}],73:[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; +}; +},{}],74:[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; +}; +},{}],75:[function(require,module,exports){ +module.exports = function(el){ + if (!arguments.length) return this.view.el; + this.view.el = el; + return this; +}; +},{}],76:[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; +}; +},{}],77:[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":28,"../../dataset":35,"../dataviz":53}],78:[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":28}],79:[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":28}],80:[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; +}; +},{}],81:[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' && typeof response.steps !== "undefined"){ + dataType = 'cat-ordinal'; + schema = { + records: '', + unpack: { + index: { + path: 'steps -> event_collection', + type: 'string' + }, + value: { + path: 'result -> ', + type: 'number' + } + } + } + } + if ((typeof response.result[0] == 'string' || typeof response.result[0] == 'number') && typeof response.steps === "undefined"){ + 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":28,"../../dataset":35,"../dataviz":53}],82:[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":35,"../helpers/getDatasetSchemas":56,"../helpers/getDefaultTitle":57,"../helpers/getQueryDataType":58,"./parseRawData":81}],83:[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":53}],84:[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; +} +},{}],85:[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; +} +},{}],86:[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; +}; +},{}],87:[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; +}; +},{}],88:[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; +}; +},{}],89:[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()); + } +}; +},{}],90:[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); + } +}; +},{}],91:[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); +}; +},{}],92:[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); + } + } +}; +},{}],93:[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":16,"./core/async":8,"./core/lib/addEvent":17,"./core/lib/addEvents":18,"./core/lib/get":19,"./core/lib/post":20,"./core/lib/run":21,"./core/lib/setGlobalProperties":22,"./core/lib/trackExternalLink":23,"./core/query":24,"./core/request":25,"./core/utils/base64":26,"./core/utils/each":28,"./core/utils/extend":30,"./core/utils/parseParams":32,"./dataset":35,"./dataviz":59,"./dataviz/adapters/c3":49,"./dataviz/adapters/chartjs":50,"./dataviz/adapters/google":51,"./dataviz/adapters/keen-io":52,"./dataviz/extensions/draw":54,"./dataviz/utils/prettyNumber":92,"domready":2,"spin.js":4}]},{},[93]); diff --git a/dist/keen.min.js b/dist/keen.min.js new file mode 100644 index 0000000..c45df8c --- /dev/null +++ b/dist/keen.min.js @@ -0,0 +1,31 @@ +(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;f1)))/4)-x((ah-1901+ai)/100)+x((ah-1601+ai)/400)}}if(!(w=s.hasOwnProperty)){w=function(aj){var ah={},ai;if((ah.__proto__=null,ah.__proto__={toString:1},ah).toString!=z){w=function(am){var al=this.__proto__,ak=am in (this.__proto__=null,this);this.__proto__=al;return ak}}else{ai=ah.constructor;w=function(al){var ak=(this.constructor||ai).prototype;return al in this&&!(al in ak&&this[al]===ak[al])}}ah=null;return w.call(this,aj)}}r=function(aj,am){var ak=0,ah,ai,al;(ah=function(){this.valueOf=0}).prototype.valueOf=0;ai=new ah();for(al in ai){if(w.call(ai,al)){ak++}}ah=ai=null;if(!ak){ai=["valueOf","toString","toLocaleString","propertyIsEnumerable","isPrototypeOf","hasOwnProperty","constructor"];r=function(ao,at){var ar=z.call(ao)==Z,aq,ap;var an=!ar&&typeof ao.constructor!="function"&&j[typeof ao.hasOwnProperty]&&ao.hasOwnProperty||w;for(aq in ao){if(!(ar&&aq=="prototype")&&an.call(ao,aq)){at(aq)}}for(ap=ai.length;aq=ai[--ap];an.call(ao,aq)&&at(aq)){}}}else{if(ak==2){r=function(ao,ar){var an={},aq=z.call(ao)==Z,ap;for(ap in ao){if(!(aq&&ap=="prototype")&&!w.call(an,ap)&&(an[ap]=1)&&w.call(ao,ap)){ar(ap)}}}}else{r=function(ao,ar){var aq=z.call(ao)==Z,ap,an;for(ap in ao){if(!(aq&&ap=="prototype")&&w.call(ao,ap)&&!(an=ap==="constructor")){ar(ap)}}if(an||w.call(ao,(ap="constructor"))){ar(ap)}}}}return r(aj,am)};if(!t("json-stringify")){var v={92:"\\\\",34:'\\"',8:"\\b",12:"\\f",10:"\\n",13:"\\r",9:"\\t"};var N="000000";var y=function(ah,ai){return(N+(ai||0)).slice(-ah)};var E="\\u00";var H=function(an){var ai='"',al=0,am=an.length,ah=!K||am>10;var ak=ah&&(K?an.split(""):an);for(;al-1/0&&ay<1/0){if(I){aD=x(ay/86400000);for(av=x(aD/365.2425)+1970-1;I(av+1,0)<=aD;av++){}for(aE=x((aD-I(av,0))/30.42);I(av,aE+1)<=aD;aE++){}aD=1+aD-I(av,aE);ap=(ay%86400000+86400000)%86400000;aB=x(ap/3600000)%24;az=x(ap/60000)%60;aw=x(ap/1000)%60;at=ap%1000}else{av=ay.getUTCFullYear();aE=ay.getUTCMonth();aD=ay.getUTCDate();aB=ay.getUTCHours();az=ay.getUTCMinutes();aw=ay.getUTCSeconds();at=ay.getUTCMilliseconds()}ay=(av<=0||av>=10000?(av<0?"-":"+")+y(6,av<0?-av:av):y(4,av))+"-"+y(2,aE+1)+"-"+y(2,aD)+"T"+y(2,aB)+":"+y(2,az)+":"+y(2,aw)+"."+y(3,at)+"Z"}else{ay=null}}else{if(typeof ay.toJSON=="function"&&((aj!=S&&aj!=T&&aj!=J)||w.call(ay,"toJSON"))){ay=ay.toJSON(an)}}}if(al){ay=al.call(aF,an,ay)}if(ay===null){return"null"}aj=z.call(ay);if(aj==F){return""+ay}else{if(aj==S){return ay>-1/0&&ay<1/0?""+ay:"null"}else{if(aj==T){return H(""+ay)}}}if(typeof ay=="object"){for(ak=ao.length;ak--;){if(ao[ak]===ay){throw af()}}ao.push(ay);ax=[];aA=ah;ah+=aC;if(aj==J){for(am=0,ak=ay.length;am0){for(ai="",ak>10&&(ak=10);ai.length=48&&ai<=57||ai>=97&&ai<=102||ai>=65&&ai<=70)){M()}}al+=R("0x"+am.slice(aj,L));break;default:M()}}else{if(ai==34){break}ai=am.charCodeAt(L);aj=L;while(ai>=32&&ai!=92&&ai!=34){ai=am.charCodeAt(++L)}al+=am.slice(aj,L)}}}if(am.charCodeAt(L)==34){L++;return al}M();default:aj=L;if(ai==45){an=true;ai=am.charCodeAt(++L)}if(ai>=48&&ai<=57){if(ai==48&&((ai=am.charCodeAt(L+1)),ai>=48&&ai<=57)){M()}an=false;for(;L=48&&ai<=57);L++){}if(am.charCodeAt(L)==46){ah=++L;for(;ah=48&&ai<=57);ah++){}if(ah==L){M()}L=ah}ai=am.charCodeAt(L);if(ai==101||ai==69){ai=am.charCodeAt(++L);if(ai==43||ai==45){L++}for(ah=L;ah=48&&ai<=57);ah++){}if(ah==L){M()}L=ah}return +am.slice(aj,L)}if(an){M()}if(am.slice(L,L+4)=="true"){L+=4;return true}else{if(am.slice(L,L+5)=="false"){L+=5;return false}else{if(am.slice(L,L+4)=="null"){L+=4;return null}}}M()}}return"$"};var ab=function(ai){var ah,aj;if(ai=="$"){M()}if(typeof ai=="string"){if((K?ai.charAt(0):ai[0])=="@"){return ai.slice(1)}if(ai=="["){ah=[];for(;;aj||(aj=true)){ai=D();if(ai=="]"){break}if(aj){if(ai==","){ai=D();if(ai=="]"){M()}}else{M()}}if(ai==","){M()}ah.push(ab(ai))}return ah}else{if(ai=="{"){ah={};for(;;aj||(aj=true)){ai=D();if(ai=="}"){break}if(aj){if(ai==","){ai=D();if(ai=="}"){M()}}else{M()}}if(ai==","||typeof ai!="string"||(K?ai.charAt(0):ai[0])!="@"||D()!=":"){M()}ah[ai.slice(1)]=ab(D())}return ah}}M()}return ai};var U=function(aj,ai,ak){var ah=B(aj,ai,ak);if(ah===Q){delete aj[ai]}else{aj[ai]=ah}};var B=function(ak,aj,al){var ai=ak[aj],ah;if(typeof ai=="object"&&ai){if(z.call(ai)==J){for(ah=ai.length;ah--;){U(ai,ah,al)}}else{r(ai,function(am){U(ai,am,al)})}}return al.call(ak,aj,ai)};aa.parse=function(aj,ak){var ah,ai;L=0;ac=""+aj;ah=ab(D());if(D()!="$"){M()}L=ac=null;return ak&&z.call(ak)==Z?B((ai={},ai[""]=ah,ai),"",ak):ah}}}aa.runInContext=o;return aa}if(m&&!g){o(n,m)}else{var k=n.JSON,p=n.JSON3,h=false;var l=o(n,(n.JSON3={noConflict:function(){if(!h){h=true;n.JSON=k;n.JSON3=p;k=p=null}return l}}));n.JSON={parse:l.parse,stringify:l.stringify}}if(g){define(function(){return l})}}).call(this)}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{}],4:[function(b,c,a){(function(d,f){if(typeof a=="object"){c.exports=f()}else{if(typeof define=="function"&&define.amd){define(f)}else{d.Spinner=f()}}}(this,function(){var j=["webkit","Moz","ms","O"],t={},s,n;function l(u,x){var v=document.createElement(u||"div"),w;for(w in x){v[w]=x[w]}return v}function m(v){for(var u=1,w=arguments.length;u>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}},{}],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,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}},{}],15:[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":28,"./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("./utils/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.7";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},{"./utils/emitter-shim":29}],17:[function(f,c,h){var q=f("../utils/json-shim");var g=f("superagent");var j=f("../index");var k=f("../utils/base64"),n=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"),l=f("../helpers/superagent-request-types"),p=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&&o()==="browser"){g.get(A).use(l(r,{async:s})).end(x)}else{if(a()||o()==="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){p(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(q.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":9,"../helpers/get-xhr-object":13,"../helpers/superagent-handle-response":14,"../helpers/superagent-request-types":15,"../index":16,"../utils/each":28,superagent:5}],19:[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":10,"../helpers/superagent-handle-response":14,"../helpers/superagent-request-types":15,superagent:5}],20:[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":14,superagent:5}],21:[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":25}],22:[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)}}},{}],23:[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":17}],24:[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("./utils/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/get-query-string":10,"./helpers/get-timezone-offset":11,"./utils/each":28,"./utils/emitter-shim":29,"./utils/extend":30}],25:[function(c,b,d){var k=c("./utils/each"),h=c("./utils/extend"),g=c("./utils/sendQuery");var f=c("./");var j=c("./utils/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(p){return}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},{"./":16,"./utils/each":28,"./utils/emitter-shim":29,"./utils/extend":30,"./utils/sendQuery":33}],26:[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}}}},{}],27:[function(b,d,a){var c=b("./json-shim");d.exports=function(f){return c.parse(c.stringify(f))}},{"./json-shim":31}],28:[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/utils/clone":27,"../core/utils/each":28,"../core/utils/emitter-shim":29,"./utils/flatten":47,"./utils/parse":48}],35:[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":30,"./dataset":34,"./lib/analyses":36,"./lib/append":37,"./lib/delete":38,"./lib/filter":39,"./lib/format":40,"./lib/insert":41,"./lib/select":42,"./lib/set":43,"./lib/sort":44,"./lib/update":45}],36:[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":28}],37:[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":28}],39:[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":28}],40:[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":28}],41:[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":28}],43:[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":28,"./append":37,"./select":42}],44:[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":28}],45:[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":28}],49:[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":28,"../../core/utils/extend":30,"../dataviz":53}],50:[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":28,"../../core/utils/extend":30,"../dataviz":53}],51:[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":16,"../../core/utils/each":28,"../../core/utils/extend":30,"../dataviz":53}],52:[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":16,"../../core/utils/clone":27,"../../core/utils/each":28,"../../core/utils/extend":30,"../dataviz":53,"../utils/prettyNumber":92}],53:[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/utils/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":16,"../core/utils/clone":27,"../core/utils/each":28,"../core/utils/emitter-shim":29,"../core/utils/extend":30,"../dataset":35,"./utils/loadScript":90,"./utils/loadStyle":91}],54:[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":25,"../../core/utils/clone":27,"../../core/utils/extend":30,"../dataviz":53}],55:[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":30,"../dataviz":53}],56:[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":28,"../../dataset":35}],57:[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}},{}],58:[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}},{}],59:[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":30,"./dataviz":53,"./lib/actions/destroy":60,"./lib/actions/error":61,"./lib/actions/initialize":62,"./lib/actions/render":63,"./lib/actions/update":64,"./lib/adapter":65,"./lib/attributes":66,"./lib/call":67,"./lib/chartOptions":68,"./lib/chartType":69,"./lib/colorMapping":70,"./lib/colors":71,"./lib/data":72,"./lib/dataType":73,"./lib/defaultChartType":74,"./lib/el":75,"./lib/height":76,"./lib/indexBy":77,"./lib/labelMapping":78,"./lib/labels":79,"./lib/library":80,"./lib/parseRawData":81,"./lib/parseRequest":82,"./lib/prepare":83,"./lib/sortGroups":84,"./lib/sortIntervals":85,"./lib/stacked":86,"./lib/title":87,"./lib/width":88}],60:[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":55}],61:[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":53,"../../helpers/getAdapterActions":55}],62:[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":53,"../../helpers/getAdapterActions":55}],63:[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":55,"../../utils/applyTransforms":89}],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(g.update){g.update.apply(this,arguments)}else{if(g.render){this.render()}}return this}},{"../../helpers/getAdapterActions":55,"../../utils/applyTransforms":89}],65:[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":28}],66:[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":28,"./chartOptions":68}],67:[function(b,c,a){c.exports=function(d){d.call(this);return this}},{}],68:[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":30}],69:[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}},{}],70:[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":28}],71:[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}},{}],72:[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":25,"../../dataset":35}],73:[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}},{}],74:[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}},{}],75:[function(b,c,a){c.exports=function(d){if(!arguments.length){return this.view.el}this.view.el=d;return this}},{}],76:[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}},{}],77:[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":28,"../../dataset":35,"../dataviz":53}],78:[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":28}],79:[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":28}],80:[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}},{}],81:[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"&&typeof m.steps!=="undefined"){r="cat-ordinal";l={records:"",unpack:{index:{path:"steps -> event_collection",type:"string"},value:{path:"result -> ",type:"number"}}}}if((typeof m.result[0]=="string"||typeof m.result[0]=="number")&&typeof m.steps==="undefined"){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":28,"../../dataset":35,"../dataviz":53}],82:[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":35,"../helpers/getDatasetSchemas":56,"../helpers/getDefaultTitle":57,"../helpers/getQueryDataType":58,"./parseRawData":81}],83:[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":53}],84:[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}},{}],85:[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}},{}],86:[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}},{}],87:[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}},{}],88:[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}},{}],89:[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())}}},{}],90:[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)}}},{}],91:[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)}},{}],92:[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)}}}},{}],93:[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":16,"./core/async":8,"./core/lib/addEvent":17,"./core/lib/addEvents":18,"./core/lib/get":19,"./core/lib/post":20,"./core/lib/run":21,"./core/lib/setGlobalProperties":22,"./core/lib/trackExternalLink":23,"./core/query":24,"./core/request":25,"./core/utils/base64":26,"./core/utils/each":28,"./core/utils/extend":30,"./core/utils/parseParams":32,"./dataset":35,"./dataviz":59,"./dataviz/adapters/c3":49,"./dataviz/adapters/chartjs":50,"./dataviz/adapters/google":51,"./dataviz/adapters/keen-io":52,"./dataviz/extensions/draw":54,"./dataviz/utils/prettyNumber":92,domready:2,"spin.js":4}]},{},[93]); \ No newline at end of file