diff --git a/bower.json b/bower.json index daefcad..e7d91b0 100644 --- a/bower.json +++ b/bower.json @@ -1,7 +1,7 @@ { "name": "hook-javascript", "description": "hook javascript client", - "version": "0.2.1", + "version": "0.3.4", "homepage": "https://github.com/doubleleft/hook-javascript", "main": "./dist/hook.js", "ignore": [ diff --git a/dist/hook.js b/dist/hook.js index 8268f1c..154aea0 100644 --- a/dist/hook.js +++ b/dist/hook.js @@ -3,7 +3,7 @@ * https://github.com/doubleleft/hook-javascript * * @copyright 2015 Doubleleft - * @build 3/4/2015 + * @build 5/22/2015 */ (function(window) { // @@ -7986,1714 +7986,11 @@ define(function (require) { } }.call(this)); -!function(a){"use strict";var b=a.HTMLCanvasElement&&a.HTMLCanvasElement.prototype,c=a.Blob&&function(){try{return Boolean(new Blob)}catch(a){return!1}}(),d=c&&a.Uint8Array&&function(){try{return 100===new Blob([new Uint8Array(100)]).size}catch(a){return!1}}(),e=a.BlobBuilder||a.WebKitBlobBuilder||a.MozBlobBuilder||a.MSBlobBuilder,f=(c||e)&&a.atob&&a.ArrayBuffer&&a.Uint8Array&&function(a){var b,f,g,h,i,j;for(b=a.split(",")[0].indexOf("base64")>=0?atob(a.split(",")[1]):decodeURIComponent(a.split(",")[1]),f=new ArrayBuffer(b.length),g=new Uint8Array(f),h=0;h= 0) { - if (typeListeners[i] === callback) { - return; - } - } - typeListeners.push(callback); - }, - removeEventListener: function (type, callback) { - type = String(type); - var listeners = this.listeners; - var typeListeners = listeners.get(type); - if (!typeListeners) { - return; - } - var length = typeListeners.length; - var filtered = []; - var i = -1; - while (++i < length) { - if (typeListeners[i] !== callback) { - filtered.push(typeListeners[i]); - } - } - if (filtered.length === 0) { - listeners["delete"](type); - } else { - listeners.set(type, filtered); - } - } - }; - - function Event(type) { - this.type = type; - this.target = null; - } - - function MessageEvent(type, options) { - Event.call(this, type); - this.data = options.data; - this.lastEventId = options.lastEventId; - } - - MessageEvent.prototype = Event.prototype; - - var XHR = global.XMLHttpRequest; - var XDR = global.XDomainRequest; - var isCORSSupported = Boolean(XHR && ((new XHR()).withCredentials !== undefined)); - var isXHR = isCORSSupported; - var Transport = isCORSSupported ? XHR : XDR; - var WAITING = -1; - var CONNECTING = 0; - var OPEN = 1; - var CLOSED = 2; - var AFTER_CR = 3; - var FIELD_START = 4; - var FIELD = 5; - var VALUE_START = 6; - var VALUE = 7; - var contentTypeRegExp = /^text\/event\-stream;?(\s*charset\=utf\-8)?$/i; - - var MINIMUM_DURATION = 1000; - var MAXIMUM_DURATION = 18000000; - - function getDuration(value, def) { - var n = Number(value) || def; - return (n < MINIMUM_DURATION ? MINIMUM_DURATION : (n > MAXIMUM_DURATION ? MAXIMUM_DURATION : n)); - } - - function fire(that, f, event) { - try { - if (typeof f === "function") { - f.call(that, event); - } - } catch (e) { - throwError(e); - } - } - - function EventSource(url, options) { - url = String(url); - - var withCredentials = Boolean(isCORSSupported && options && options.withCredentials); - var initialRetry = getDuration(options ? options.retry : NaN, 1000); - var heartbeatTimeout = getDuration(options ? options.heartbeatTimeout : NaN, 45000); - var lastEventId = (options && options.lastEventId && String(options.lastEventId)) || ""; - var that = this; - var retry = initialRetry; - var wasActivity = false; - var xhr = new Transport(); - var timeout = 0; - var timeout0 = 0; - var charOffset = 0; - var currentState = WAITING; - var dataBuffer = []; - var lastEventIdBuffer = ""; - var eventTypeBuffer = ""; - var onTimeout = null; - - var state = FIELD_START; - var field = ""; - var value = ""; - - options = null; - - function close() { - currentState = CLOSED; - if (xhr !== null) { - xhr.abort(); - xhr = null; - } - if (timeout !== 0) { - clearTimeout(timeout); - timeout = 0; - } - if (timeout0 !== 0) { - clearTimeout(timeout0); - timeout0 = 0; - } - that.readyState = CLOSED; - } - - function onProgress(isLoadEnd) { - var responseText = currentState === OPEN || currentState === CONNECTING ? xhr.responseText || "" : ""; - var event = null; - var isWrongStatusCodeOrContentType = false; - - if (currentState === CONNECTING) { - var status = 0; - var statusText = ""; - var contentType = ""; - if (isXHR) { - try { - status = Number(xhr.status || 0); - statusText = String(xhr.statusText || ""); - contentType = String(xhr.getResponseHeader("Content-Type") || ""); - } catch (error) { - // https://bugs.webkit.org/show_bug.cgi?id=29121 - status = 0; - // FF < 14, WebKit - // https://bugs.webkit.org/show_bug.cgi?id=29658 - // https://bugs.webkit.org/show_bug.cgi?id=77854 - } - } else { - status = 200; - contentType = xhr.contentType; - } - if (status === 200 && contentTypeRegExp.test(contentType)) { - currentState = OPEN; - wasActivity = true; - retry = initialRetry; - that.readyState = OPEN; - event = new Event("open"); - that.dispatchEvent(event); - fire(that, that.onopen, event); - if (currentState === CLOSED) { - return; - } - } else { - if (status !== 0) { - var message = ""; - if (status !== 200) { - message = "EventSource's response has a status " + status + " " + statusText.replace(/\s+/g, " ") + " that is not 200. Aborting the connection."; - } else { - message = "EventSource's response has a Content-Type specifying an unsupported type: " + contentType.replace(/\s+/g, " ") + ". Aborting the connection."; - } - setTimeout(function () { - throw new Error(message); - }); - isWrongStatusCodeOrContentType = true; - } - } - } - - if (currentState === OPEN) { - if (responseText.length > charOffset) { - wasActivity = true; - } - var i = charOffset - 1; - var length = responseText.length; - var c = "\n"; - while (++i < length) { - c = responseText[i]; - if (state === AFTER_CR && c === "\n") { - state = FIELD_START; - } else { - if (state === AFTER_CR) { - state = FIELD_START; - } - if (c === "\r" || c === "\n") { - if (field === "data") { - dataBuffer.push(value); - } else if (field === "id") { - lastEventIdBuffer = value; - } else if (field === "event") { - eventTypeBuffer = value; - } else if (field === "retry") { - initialRetry = getDuration(value, initialRetry); - retry = initialRetry; - } else if (field === "heartbeatTimeout") { - heartbeatTimeout = getDuration(value, heartbeatTimeout); - if (timeout !== 0) { - clearTimeout(timeout); - timeout = setTimeout(onTimeout, heartbeatTimeout); - } - } - value = ""; - field = ""; - if (state === FIELD_START) { - if (dataBuffer.length !== 0) { - lastEventId = lastEventIdBuffer; - if (eventTypeBuffer === "") { - eventTypeBuffer = "message"; - } - event = new MessageEvent(eventTypeBuffer, { - data: dataBuffer.join("\n"), - lastEventId: lastEventIdBuffer - }); - that.dispatchEvent(event); - if (eventTypeBuffer === "message") { - fire(that, that.onmessage, event); - } - if (currentState === CLOSED) { - return; - } - } - dataBuffer.length = 0; - eventTypeBuffer = ""; - } - state = c === "\r" ? AFTER_CR : FIELD_START; - } else { - if (state === FIELD_START) { - state = FIELD; - } - if (state === FIELD) { - if (c === ":") { - state = VALUE_START; - } else { - field += c; - } - } else if (state === VALUE_START) { - if (c !== " ") { - value += c; - } - state = VALUE; - } else if (state === VALUE) { - value += c; - } - } - } - } - charOffset = length; - } - - if ((currentState === OPEN || currentState === CONNECTING) && - (isLoadEnd || isWrongStatusCodeOrContentType || (charOffset > 1024 * 1024) || (timeout === 0 && !wasActivity))) { - currentState = WAITING; - xhr.abort(); - if (timeout !== 0) { - clearTimeout(timeout); - timeout = 0; - } - if (retry > initialRetry * 16) { - retry = initialRetry * 16; - } - if (retry > MAXIMUM_DURATION) { - retry = MAXIMUM_DURATION; - } - timeout = setTimeout(onTimeout, retry); - retry = retry * 2 + 1; - - that.readyState = CONNECTING; - event = new Event("error"); - that.dispatchEvent(event); - fire(that, that.onerror, event); - } else { - if (timeout === 0) { - wasActivity = false; - timeout = setTimeout(onTimeout, heartbeatTimeout); - } - } - } - - function onProgress2() { - onProgress(false); - } - - function onLoadEnd() { - onProgress(true); - } - - if (isXHR) { - // workaround for Opera issue with "progress" events - timeout0 = setTimeout(function f() { - if (xhr.readyState === 3) { - onProgress2(); - } - timeout0 = setTimeout(f, 500); - }, 0); - } - - onTimeout = function () { - timeout = 0; - if (currentState !== WAITING) { - onProgress(false); - return; - } - // loading indicator in Safari, Chrome < 14, Firefox - // https://bugzilla.mozilla.org/show_bug.cgi?id=736723 - if (isXHR && (xhr.sendAsBinary !== undefined || xhr.onloadend === undefined) && global.document && global.document.readyState && global.document.readyState !== "complete") { - timeout = setTimeout(onTimeout, 4); - return; - } - // XDomainRequest#abort removes onprogress, onerror, onload - - xhr.onload = xhr.onerror = onLoadEnd; - - if (isXHR) { - // improper fix to match Firefox behaviour, but it is better than just ignore abort - // see https://bugzilla.mozilla.org/show_bug.cgi?id=768596 - // https://bugzilla.mozilla.org/show_bug.cgi?id=880200 - // https://code.google.com/p/chromium/issues/detail?id=153570 - xhr.onabort = onLoadEnd; - - // Firefox 3.5 - 3.6 - ? < 9.0 - // onprogress is not fired sometimes or delayed - xhr.onreadystatechange = onProgress2; - } - - xhr.onprogress = onProgress2; - - wasActivity = false; - timeout = setTimeout(onTimeout, heartbeatTimeout); - - charOffset = 0; - currentState = CONNECTING; - dataBuffer.length = 0; - eventTypeBuffer = ""; - lastEventIdBuffer = lastEventId; - value = ""; - field = ""; - state = FIELD_START; - - var s = url.slice(0, 5); - if (s !== "data:" && s !== "blob:") { - s = url + ((url.indexOf("?", 0) === -1 ? "?" : "&") + "lastEventId=" + encodeURIComponent(lastEventId) + "&r=" + String(Math.random() + 1).slice(2)); - } else { - s = url; - } - xhr.open("GET", s, true); - - if (isXHR) { - // withCredentials should be set after "open" for Safari and Chrome (< 19 ?) - xhr.withCredentials = withCredentials; - - xhr.responseType = "text"; - - // Request header field Cache-Control is not allowed by Access-Control-Allow-Headers. - // "Cache-control: no-cache" are not honored in Chrome and Firefox - // https://bugzilla.mozilla.org/show_bug.cgi?id=428916 - //xhr.setRequestHeader("Cache-Control", "no-cache"); - xhr.setRequestHeader("Accept", "text/event-stream"); - // Request header field Last-Event-ID is not allowed by Access-Control-Allow-Headers. - //xhr.setRequestHeader("Last-Event-ID", lastEventId); - } - - xhr.send(null); - }; - - EventTarget.call(this); - this.close = close; - this.url = url; - this.readyState = CONNECTING; - this.withCredentials = withCredentials; - - this.onopen = null; - this.onmessage = null; - this.onerror = null; - - onTimeout(); - } - - function F() { - this.CONNECTING = CONNECTING; - this.OPEN = OPEN; - this.CLOSED = CLOSED; - } - F.prototype = EventTarget.prototype; - - EventSource.prototype = new F(); - F.call(EventSource); - - if (Transport) { - // Why replace a native EventSource ? - // https://bugzilla.mozilla.org/show_bug.cgi?id=444328 - // https://bugzilla.mozilla.org/show_bug.cgi?id=831392 - // https://code.google.com/p/chromium/issues/detail?id=260144 - // https://code.google.com/p/chromium/issues/detail?id=225654 - // ... - global.NativeEventSource = global.EventSource; - global.EventSource = EventSource; - } - -}(this)); - -/** @license MIT License (c) 2011-2013 Copyright Tavendo GmbH. */ - -/** - * AutobahnJS - http://autobahn.ws - * - * A lightweight implementation of - * - * WAMP (The WebSocket Application Messaging Protocol) - http://wamp.ws - * - * Provides asynchronous RPC/PubSub over WebSocket. - * - * Copyright (C) 2011-2014 Tavendo GmbH. Licensed under the MIT License. - * See license text at http://www.opensource.org/licenses/mit-license.php - */ - -/* global console: false, MozWebSocket: false, when: false, CryptoJS: false */ - -/** - * @define {string} - */ -var AUTOBAHNJS_VERSION = '?.?.?'; -var global = this; - -(function (root, factory) { - if (typeof define === 'function' && define.amd) { - // AMD. Register as an anonymous module. - define(['when'], function (when) { - // Also create a global in case some scripts - // that are loaded still are looking for - // a global even when an AMD loader is in use. - return (root.ab = factory(root, when)); - }); - - } else if (typeof exports !== 'undefined') { - // Support Node.js specific `module.exports` (which can be a function) - if (typeof module != 'undefined' && module.exports) { - exports = module.exports = factory(root, root.when); - } - // But always support CommonJS module 1.1.1 spec (`exports` cannot be a function) - //exports.ab = exports; - - } else { - // Browser globals - root.ab = factory(root, root.when); - } -} (global, function (root, when) { - - "use strict"; - - var ab = {}; - ab._version = AUTOBAHNJS_VERSION; - - /** - * Fallbacks for browsers lacking - * - * Array.prototype.indexOf - * Array.prototype.forEach - * - * most notably MSIE8. - * - * Source: - * https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/indexOf - * https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/forEach - */ - (function () { - if (!Array.prototype.indexOf) { - Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) { - "use strict"; - if (this === null) { - throw new TypeError(); - } - var t = new Object(this); - var len = t.length >>> 0; - if (len === 0) { - return -1; - } - var n = 0; - if (arguments.length > 0) { - n = Number(arguments[1]); - if (n !== n) { // shortcut for verifying if it's NaN - n = 0; - } else if (n !== 0 && n !== Infinity && n !== -Infinity) { - n = (n > 0 || -1) * Math.floor(Math.abs(n)); - } - } - if (n >= len) { - return -1; - } - var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0); - for (; k < len; k++) { - if (k in t && t[k] === searchElement) { - return k; - } - } - return -1; - }; - } - - if (!Array.prototype.forEach) { - - Array.prototype.forEach = function (callback, thisArg) { - - var T, k; - - if (this === null) { - throw new TypeError(" this is null or not defined"); - } - - // 1. Let O be the result of calling ToObject passing the |this| value as the argument. - var O = new Object(this); - - // 2. Let lenValue be the result of calling the Get internal method of O with the argument "length". - // 3. Let len be ToUint32(lenValue). - var len = O.length >>> 0; // Hack to convert O.length to a UInt32 - - // 4. If IsCallable(callback) is false, throw a TypeError exception. - // See: http://es5.github.com/#x9.11 - if ({}.toString.call(callback) !== "[object Function]") { - throw new TypeError(callback + " is not a function"); - } - - // 5. If thisArg was supplied, let T be thisArg; else let T be undefined. - if (thisArg) { - T = thisArg; - } - - // 6. Let k be 0 - k = 0; - - // 7. Repeat, while k < len - while (k < len) { - - var kValue; - - // a. Let Pk be ToString(k). - // This is implicit for LHS operands of the in operator - // b. Let kPresent be the result of calling the HasProperty internal method of O with argument Pk. - // This step can be combined with c - // c. If kPresent is true, then - if (k in O) { - - // i. Let kValue be the result of calling the Get internal method of O with argument Pk. - kValue = O[k]; - - // ii. Call the Call internal method of callback with T as the this value and - // argument list containing kValue, k, and O. - callback.call(T, kValue, k, O); - } - // d. Increase k by 1. - k++; - } - // 8. return undefined - }; - } - - })(); - - - // Helper to slice out browser / version from userAgent - ab._sliceUserAgent = function (str, delim, delim2) { - var ver = []; - var ua = navigator.userAgent; - var i = ua.indexOf(str); - var j = ua.indexOf(delim, i); - if (j < 0) { - j = ua.length; - } - var agent = ua.slice(i, j).split(delim2); - var v = agent[1].split('.'); - for (var k = 0; k < v.length; ++k) { - ver.push(parseInt(v[k], 10)); - } - return {name: agent[0], version: ver}; - }; - - /** - * Detect browser and browser version. - */ - ab.getBrowser = function () { - - var ua = navigator.userAgent; - if (ua.indexOf("Chrome") > -1) { - return ab._sliceUserAgent("Chrome", " ", "/"); - } else if (ua.indexOf("Safari") > -1) { - return ab._sliceUserAgent("Safari", " ", "/"); - } else if (ua.indexOf("Firefox") > -1) { - return ab._sliceUserAgent("Firefox", " ", "/"); - } else if (ua.indexOf("MSIE") > -1) { - return ab._sliceUserAgent("MSIE", ";", " "); - } else { - return null; - } - }; - - - ab.getServerUrl = function (wsPath, fallbackUrl) { - if (root.location.protocol === "file:") { - if (fallbackUrl) { - return fallbackUrl; - } else { - return "ws://127.0.0.1/ws"; - } - } else { - var scheme = root.location.protocol === 'https:' ? 'wss://' : 'ws://'; - var port = root.location.port !== "" ? ':' + root.location.port : ''; - var path = wsPath ? wsPath : 'ws'; - return scheme + root.location.hostname + port + "/" + path; - } - }; - - - // Logging message for unsupported browser. - ab.browserNotSupportedMessage = "Browser does not support WebSockets (RFC6455)"; - - - // PBKDF2-base key derivation function for salted WAMP-CRA - ab.deriveKey = function (secret, extra) { - if (extra && extra.salt) { - var salt = extra.salt; - var keylen = extra.keylen || 32; - var iterations = extra.iterations || 10000; - var key = CryptoJS.PBKDF2(secret, salt, { keySize: keylen / 4, iterations: iterations, hasher: CryptoJS.algo.SHA256 }); - return key.toString(CryptoJS.enc.Base64); - } else { - return secret; - } - }; - - - ab._idchars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; - ab._idlen = 16; - ab._subprotocol = "wamp"; - - ab._newid = function () { - var id = ""; - for (var i = 0; i < ab._idlen; i += 1) { - id += ab._idchars.charAt(Math.floor(Math.random() * ab._idchars.length)); - } - return id; - }; - - ab._newidFast = function () { - return Math.random().toString(36); - }; - - ab.log = function () { - //console.log.apply(console, !!arguments.length ? arguments : [this]); - if (arguments.length > 1) { - console.group("Log Item"); - for (var i = 0; i < arguments.length; i += 1) { - console.log(arguments[i]); - } - console.groupEnd(); - } else { - console.log(arguments[0]); - } - }; - - ab._debugrpc = false; - ab._debugpubsub = false; - ab._debugws = false; - ab._debugconnect = false; - - ab.debug = function (debugWamp, debugWs, debugConnect) { - if ("console" in root) { - ab._debugrpc = debugWamp; - ab._debugpubsub = debugWamp; - ab._debugws = debugWs; - ab._debugconnect = debugConnect; - } else { - throw "browser does not support console object"; - } - }; - - ab.version = function () { - return ab._version; - }; - - ab.PrefixMap = function () { - - var self = this; - self._index = {}; - self._rindex = {}; - }; - - ab.PrefixMap.prototype.get = function (prefix) { - - var self = this; - return self._index[prefix]; - }; - - ab.PrefixMap.prototype.set = function (prefix, uri) { - - var self = this; - self._index[prefix] = uri; - self._rindex[uri] = prefix; - }; - - ab.PrefixMap.prototype.setDefault = function (uri) { - - var self = this; - self._index[""] = uri; - self._rindex[uri] = ""; - }; - - ab.PrefixMap.prototype.remove = function (prefix) { - - var self = this; - var uri = self._index[prefix]; - if (uri) { - delete self._index[prefix]; - delete self._rindex[uri]; - } - }; - - ab.PrefixMap.prototype.resolve = function (curie, pass) { - - var self = this; - - // skip if not a CURIE - var i = curie.indexOf(":"); - if (i >= 0) { - var prefix = curie.substring(0, i); - if (self._index[prefix]) { - return self._index[prefix] + curie.substring(i + 1); - } - } - - // either pass-through or null - if (pass === true) { - return curie; - } else { - return null; - } - }; - - ab.PrefixMap.prototype.shrink = function (uri, pass) { - - var self = this; - - for (var i = uri.length; i > 0; i -= 1) { - var u = uri.substring(0, i); - var p = self._rindex[u]; - if (p) { - return p + ":" + uri.substring(i); - } - } - - // either pass-through or null - if (pass === true) { - return uri; - } else { - return null; - } - }; - - - ab._MESSAGE_TYPEID_WELCOME = 0; - ab._MESSAGE_TYPEID_PREFIX = 1; - ab._MESSAGE_TYPEID_CALL = 2; - ab._MESSAGE_TYPEID_CALL_RESULT = 3; - ab._MESSAGE_TYPEID_CALL_ERROR = 4; - ab._MESSAGE_TYPEID_SUBSCRIBE = 5; - ab._MESSAGE_TYPEID_UNSUBSCRIBE = 6; - ab._MESSAGE_TYPEID_PUBLISH = 7; - ab._MESSAGE_TYPEID_EVENT = 8; - - ab.CONNECTION_CLOSED = 0; - ab.CONNECTION_LOST = 1; - ab.CONNECTION_RETRIES_EXCEEDED = 2; - ab.CONNECTION_UNREACHABLE = 3; - ab.CONNECTION_UNSUPPORTED = 4; - ab.CONNECTION_UNREACHABLE_SCHEDULED_RECONNECT = 5; - ab.CONNECTION_LOST_SCHEDULED_RECONNECT = 6; - - ab.Deferred = when.defer; - //ab.Deferred = jQuery.Deferred; - - ab._construct = function (url, protocols) { - if ("WebSocket" in root) { - // Chrome, MSIE, newer Firefox - if (protocols) { - return new WebSocket(url, protocols); - } else { - return new WebSocket(url); - } - } else if ("MozWebSocket" in root) { - // older versions of Firefox prefix the WebSocket object - if (protocols) { - return new MozWebSocket(url, protocols); - } else { - return new MozWebSocket(url); - } - } else { - return null; - } - }; - - ab.Session = function (wsuri, onopen, onclose, options) { - - var self = this; - - self._wsuri = wsuri; - self._options = options; - self._websocket_onopen = onopen; - self._websocket_onclose = onclose; - - self._websocket = null; - self._websocket_connected = false; - - self._session_id = null; - self._wamp_version = null; - self._server = null; - - self._calls = {}; - self._subscriptions = {}; - self._prefixes = new ab.PrefixMap(); - - self._txcnt = 0; - self._rxcnt = 0; - - if (self._options && self._options.skipSubprotocolAnnounce) { - self._websocket = ab._construct(self._wsuri); - } else { - self._websocket = ab._construct(self._wsuri, [ab._subprotocol]); - } - - if (!self._websocket) { - if (onclose !== undefined) { - onclose(ab.CONNECTION_UNSUPPORTED); - return; - } else { - throw ab.browserNotSupportedMessage; - } - } - - self._websocket.onmessage = function (e) - { - if (ab._debugws) { - self._rxcnt += 1; - console.group("WS Receive"); - console.info(self._wsuri + " [" + self._session_id + "]"); - console.log(self._rxcnt); - console.log(e.data); - console.groupEnd(); - } - - var o = JSON.parse(e.data); - if (o[1] in self._calls) - { - if (o[0] === ab._MESSAGE_TYPEID_CALL_RESULT) { - - var dr = self._calls[o[1]]; - var r = o[2]; - - if (ab._debugrpc && dr._ab_callobj !== undefined) { - console.group("WAMP Call", dr._ab_callobj[2]); - console.timeEnd(dr._ab_tid); - console.group("Arguments"); - for (var i = 3; i < dr._ab_callobj.length; i += 1) { - var arg = dr._ab_callobj[i]; - if (arg !== undefined) { - console.log(arg); - } else { - break; - } - } - console.groupEnd(); - console.group("Result"); - console.log(r); - console.groupEnd(); - console.groupEnd(); - } - - dr.resolve(r); - } - else if (o[0] === ab._MESSAGE_TYPEID_CALL_ERROR) { - - var de = self._calls[o[1]]; - var uri_ = o[2]; - var desc_ = o[3]; - var detail_ = o[4]; - - if (ab._debugrpc && de._ab_callobj !== undefined) { - console.group("WAMP Call", de._ab_callobj[2]); - console.timeEnd(de._ab_tid); - console.group("Arguments"); - for (var j = 3; j < de._ab_callobj.length; j += 1) { - var arg2 = de._ab_callobj[j]; - if (arg2 !== undefined) { - console.log(arg2); - } else { - break; - } - } - console.groupEnd(); - console.group("Error"); - console.log(uri_); - console.log(desc_); - if (detail_ !== undefined) { - console.log(detail_); - } - console.groupEnd(); - console.groupEnd(); - } - - if (detail_ !== undefined) { - de.reject({uri: uri_, desc: desc_, detail: detail_}); - } else { - de.reject({uri: uri_, desc: desc_}); - } - } - delete self._calls[o[1]]; - } - else if (o[0] === ab._MESSAGE_TYPEID_EVENT) - { - var subid = self._prefixes.resolve(o[1], true); - if (subid in self._subscriptions) { - - var uri2 = o[1]; - var val = o[2]; - - if (ab._debugpubsub) { - console.group("WAMP Event"); - console.info(self._wsuri + " [" + self._session_id + "]"); - console.log(uri2); - console.log(val); - console.groupEnd(); - } - - self._subscriptions[subid].forEach(function (callback) { - - callback(uri2, val); - }); - } - else { - // ignore unsolicited event! - } - } - else if (o[0] === ab._MESSAGE_TYPEID_WELCOME) - { - if (self._session_id === null) { - self._session_id = o[1]; - self._wamp_version = o[2]; - self._server = o[3]; - - if (ab._debugrpc || ab._debugpubsub) { - console.group("WAMP Welcome"); - console.info(self._wsuri + " [" + self._session_id + "]"); - console.log(self._wamp_version); - console.log(self._server); - console.groupEnd(); - } - - // only now that we have received the initial server-to-client - // welcome message, fire application onopen() hook - if (self._websocket_onopen !== null) { - self._websocket_onopen(); - } - } else { - throw "protocol error (welcome message received more than once)"; - } - } - }; - - self._websocket.onopen = function (e) - { - // check if we can speak WAMP! - if (self._websocket.protocol !== ab._subprotocol) { - - if (typeof self._websocket.protocol === 'undefined') { - // i.e. Safari does subprotocol negotiation (broken), but then - // does NOT set the protocol attribute of the websocket object (broken) - // - if (ab._debugws) { - console.group("WS Warning"); - console.info(self._wsuri); - console.log("WebSocket object has no protocol attribute: WAMP subprotocol check skipped!"); - console.groupEnd(); - } - } - else if (self._options && self._options.skipSubprotocolCheck) { - // WAMP subprotocol check disabled by session option - // - if (ab._debugws) { - console.group("WS Warning"); - console.info(self._wsuri); - console.log("Server does not speak WAMP, but subprotocol check disabled by option!"); - console.log(self._websocket.protocol); - console.groupEnd(); - } - } else { - // we only speak WAMP .. if the server denied us this, we bail out. - // - self._websocket.close(1000, "server does not speak WAMP"); - throw "server does not speak WAMP (but '" + self._websocket.protocol + "' !)"; - } - } - if (ab._debugws) { - console.group("WAMP Connect"); - console.info(self._wsuri); - console.log(self._websocket.protocol); - console.groupEnd(); - } - self._websocket_connected = true; - }; - - self._websocket.onerror = function (e) - { - // FF fires this upon unclean closes - // Chrome does not fire this - }; - - self._websocket.onclose = function (e) - { - if (ab._debugws) { - if (self._websocket_connected) { - console.log("Autobahn connection to " + self._wsuri + " lost (code " + e.code + ", reason '" + e.reason + "', wasClean " + e.wasClean + ")."); - } else { - console.log("Autobahn could not connect to " + self._wsuri + " (code " + e.code + ", reason '" + e.reason + "', wasClean " + e.wasClean + ")."); - } - } - - // fire app callback - if (self._websocket_onclose !== undefined) { - if (self._websocket_connected) { - if (e.wasClean) { - // connection was closed cleanly (closing HS was performed) - self._websocket_onclose(ab.CONNECTION_CLOSED, "WS-" + e.code + ": " + e.reason); - } else { - // connection was closed uncleanly (lost without closing HS) - self._websocket_onclose(ab.CONNECTION_LOST); - } - } else { - // connection could not be established in the first place - self._websocket_onclose(ab.CONNECTION_UNREACHABLE); - } - } - - // cleanup - reconnect requires a new session object! - self._websocket_connected = false; - self._wsuri = null; - self._websocket_onopen = null; - self._websocket_onclose = null; - self._websocket = null; - }; - - self.log = function () { - if (self._options && 'sessionIdent' in self._options) { - console.group("WAMP Session '" + self._options.sessionIdent + "' [" + self._session_id + "]"); - } else { - console.group("WAMP Session " + "[" + self._session_id + "]"); - } - for (var i = 0; i < arguments.length; ++i) { - console.log(arguments[i]); - } - console.groupEnd(); - }; - }; - - - ab.Session.prototype._send = function (msg) { - - var self = this; - - if (!self._websocket_connected) { - throw "Autobahn not connected"; - } - - var rmsg; - switch (true) - { - // In the event that prototype library is in existance run the toJSON method prototype provides - // else run the standard JSON.stringify - // this is a very clever problem that causes json to be double-quote-encoded. - case root.Prototype && typeof top.root.__prototype_deleted === 'undefined': - case typeof msg.toJSON === 'function': - rmsg = msg.toJSON(); - break; - - // we could do instead - // msg.toJSON = function(){return msg}; - // rmsg = JSON.stringify(msg); - default: - rmsg = JSON.stringify(msg); - } - - self._websocket.send(rmsg); - self._txcnt += 1; - - if (ab._debugws) { - console.group("WS Send"); - console.info(self._wsuri + " [" + self._session_id + "]"); - console.log(self._txcnt); - console.log(rmsg); - console.groupEnd(); - } - }; - - - ab.Session.prototype.close = function () { - - var self = this; - - if (self._websocket_connected) { - self._websocket.close(); - } else { - //throw "Autobahn not connected"; - } - }; - - - ab.Session.prototype.sessionid = function () { - - var self = this; - return self._session_id; - }; - - - ab.Session.prototype.wsuri = function () { - - var self = this; - return self._wsuri; - }; - - - ab.Session.prototype.shrink = function (uri, pass) { - - var self = this; - if (pass === undefined) pass = true; - return self._prefixes.shrink(uri, pass); - }; - - - ab.Session.prototype.resolve = function (curie, pass) { - - var self = this; - if (pass === undefined) pass = true; - return self._prefixes.resolve(curie, pass); - }; - - - ab.Session.prototype.prefix = function (prefix, uri) { - - var self = this; - - /* - if (self._prefixes.get(prefix) !== undefined) { - throw "prefix '" + prefix + "' already defined"; - } - */ - - self._prefixes.set(prefix, uri); - - if (ab._debugrpc || ab._debugpubsub) { - console.group("WAMP Prefix"); - console.info(self._wsuri + " [" + self._session_id + "]"); - console.log(prefix); - console.log(uri); - console.groupEnd(); - } - - var msg = [ab._MESSAGE_TYPEID_PREFIX, prefix, uri]; - self._send(msg); - }; - - - ab.Session.prototype.call = function () { - - var self = this; - - var d = new ab.Deferred(); - var callid; - while (true) { - callid = ab._newidFast(); - if (!(callid in self._calls)) { - break; - } - } - self._calls[callid] = d; - - var procuri = self._prefixes.shrink(arguments[0], true); - var obj = [ab._MESSAGE_TYPEID_CALL, callid, procuri]; - for (var i = 1; i < arguments.length; i += 1) { - obj.push(arguments[i]); - } - - self._send(obj); - - if (ab._debugrpc) { - d._ab_callobj = obj; - d._ab_tid = self._wsuri + " [" + self._session_id + "][" + callid + "]"; - console.time(d._ab_tid); - console.info(); - } - - if (d.promise.then) { - // whenjs has the actual user promise in an attribute - return d.promise; - } else { - return d; - } - }; - - - ab.Session.prototype.subscribe = function (topicuri, callback) { - - var self = this; - - // subscribe by sending WAMP message when topic not already subscribed - // - var rtopicuri = self._prefixes.resolve(topicuri, true); - if (!(rtopicuri in self._subscriptions)) { - - if (ab._debugpubsub) { - console.group("WAMP Subscribe"); - console.info(self._wsuri + " [" + self._session_id + "]"); - console.log(topicuri); - console.log(callback); - console.groupEnd(); - } - - var msg = [ab._MESSAGE_TYPEID_SUBSCRIBE, topicuri]; - self._send(msg); - - self._subscriptions[rtopicuri] = []; - } - - // add callback to event listeners list if not already in list - // - var i = self._subscriptions[rtopicuri].indexOf(callback); - if (i === -1) { - self._subscriptions[rtopicuri].push(callback); - } - else { - throw "callback " + callback + " already subscribed for topic " + rtopicuri; - } - }; - - - ab.Session.prototype.unsubscribe = function (topicuri, callback) { - - var self = this; - - var rtopicuri = self._prefixes.resolve(topicuri, true); - if (!(rtopicuri in self._subscriptions)) { - throw "not subscribed to topic " + rtopicuri; - } - else { - var removed; - if (callback !== undefined) { - var idx = self._subscriptions[rtopicuri].indexOf(callback); - if (idx !== -1) { - removed = callback; - self._subscriptions[rtopicuri].splice(idx, 1); - } - else { - throw "no callback " + callback + " subscribed on topic " + rtopicuri; - } - } - else { - removed = self._subscriptions[rtopicuri].slice(); - self._subscriptions[rtopicuri] = []; - } - - if (self._subscriptions[rtopicuri].length === 0) { - - delete self._subscriptions[rtopicuri]; - - if (ab._debugpubsub) { - console.group("WAMP Unsubscribe"); - console.info(self._wsuri + " [" + self._session_id + "]"); - console.log(topicuri); - console.log(removed); - console.groupEnd(); - } - - var msg = [ab._MESSAGE_TYPEID_UNSUBSCRIBE, topicuri]; - self._send(msg); - } - } - }; - - - ab.Session.prototype.publish = function () { - - var self = this; - - var topicuri = arguments[0]; - var event = arguments[1]; - - var excludeMe = null; - var exclude = null; - var eligible = null; - - var msg = null; - - if (arguments.length > 3) { - - if (!(arguments[2] instanceof Array)) { - throw "invalid argument type(s)"; - } - if (!(arguments[3] instanceof Array)) { - throw "invalid argument type(s)"; - } - - exclude = arguments[2]; - eligible = arguments[3]; - msg = [ab._MESSAGE_TYPEID_PUBLISH, topicuri, event, exclude, eligible]; - - } else if (arguments.length > 2) { - - if (typeof(arguments[2]) === 'boolean') { - - excludeMe = arguments[2]; - msg = [ab._MESSAGE_TYPEID_PUBLISH, topicuri, event, excludeMe]; - - } else if (arguments[2] instanceof Array) { - - exclude = arguments[2]; - msg = [ab._MESSAGE_TYPEID_PUBLISH, topicuri, event, exclude]; - - } else { - throw "invalid argument type(s)"; - } - - } else { - - msg = [ab._MESSAGE_TYPEID_PUBLISH, topicuri, event]; - } - - if (ab._debugpubsub) { - console.group("WAMP Publish"); - console.info(self._wsuri + " [" + self._session_id + "]"); - console.log(topicuri); - console.log(event); - - if (excludeMe !== null) { - console.log(excludeMe); - } else { - if (exclude !== null) { - console.log(exclude); - if (eligible !== null) { - console.log(eligible); - } - } - } - console.groupEnd(); - } - - self._send(msg); - }; - - - // allow both 2-party and 3-party authentication/authorization - // for 3-party: let C sign, but let both the B and C party authorize - - ab.Session.prototype.authreq = function (appkey, extra) { - return this.call("http://api.wamp.ws/procedure#authreq", appkey, extra); - }; - - ab.Session.prototype.authsign = function (challenge, secret) { - if (!secret) { - secret = ""; - } - - return CryptoJS.HmacSHA256(challenge, secret).toString(CryptoJS.enc.Base64); - }; - - ab.Session.prototype.auth = function (signature) { - return this.call("http://api.wamp.ws/procedure#auth", signature); - }; - - - ab._connect = function (peer) { - - // establish session to WAMP server - var sess = new ab.Session(peer.wsuri, - - // fired when session has been opened - function() { - - peer.connects += 1; - peer.retryCount = 0; - - // we are connected .. do awesome stuff! - peer.onConnect(sess); - }, - - // fired when session has been closed - function(code, reason) { - - var stop = null; - - switch (code) { - - case ab.CONNECTION_CLOSED: - // the session was closed by the app - peer.onHangup(code, "Connection was closed properly [" + reason + "]"); - break; - - case ab.CONNECTION_UNSUPPORTED: - // fatal: we miss our WebSocket object! - peer.onHangup(code, "Browser does not support WebSocket."); - break; - - case ab.CONNECTION_UNREACHABLE: - - peer.retryCount += 1; - - if (peer.connects === 0) { - - // the connection could not be established in the first place - // which likely means invalid server WS URI or such things - peer.onHangup(code, "Connection could not be established."); - - } else { - - // the connection was established at least once successfully, - // but now lost .. sane thing is to try automatic reconnects - if (peer.retryCount <= peer.options.maxRetries) { - - // notify the app of scheduled reconnect - stop = peer.onHangup(ab.CONNECTION_UNREACHABLE_SCHEDULED_RECONNECT, - "Connection unreachable - scheduled reconnect to occur in " + (peer.options.retryDelay / 1000) + " second(s) - attempt " + peer.retryCount + " of " + peer.options.maxRetries + ".", - {delay: peer.options.retryDelay, - retries: peer.retryCount, - maxretries: peer.options.maxRetries}); - - if (!stop) { - if (ab._debugconnect) { - console.log("Connection unreachable - retrying (" + peer.retryCount + ") .."); - } - root.setTimeout(function () { - ab._connect(peer); - }, peer.options.retryDelay); - } else { - if (ab._debugconnect) { - console.log("Connection unreachable - retrying stopped by app"); - } - peer.onHangup(ab.CONNECTION_RETRIES_EXCEEDED, "Number of connection retries exceeded."); - } - - } else { - peer.onHangup(ab.CONNECTION_RETRIES_EXCEEDED, "Number of connection retries exceeded."); - } - } - break; - - case ab.CONNECTION_LOST: - - peer.retryCount += 1; - - if (peer.retryCount <= peer.options.maxRetries) { - - // notify the app of scheduled reconnect - stop = peer.onHangup(ab.CONNECTION_LOST_SCHEDULED_RECONNECT, - "Connection lost - scheduled " + peer.retryCount + "th reconnect to occur in " + (peer.options.retryDelay / 1000) + " second(s).", - {delay: peer.options.retryDelay, - retries: peer.retryCount, - maxretries: peer.options.maxRetries}); - - if (!stop) { - if (ab._debugconnect) { - console.log("Connection lost - retrying (" + peer.retryCount + ") .."); - } - root.setTimeout(function () { - ab._connect(peer); - }, peer.options.retryDelay); - } else { - if (ab._debugconnect) { - console.log("Connection lost - retrying stopped by app"); - } - peer.onHangup(ab.CONNECTION_RETRIES_EXCEEDED, "Connection lost."); - } - } else { - peer.onHangup(ab.CONNECTION_RETRIES_EXCEEDED, "Connection lost."); - } - break; - - default: - throw "unhandled close code in ab._connect"; - } - }, - - peer.options // forward options to session class for specific WS/WAMP options - ); - }; - - - ab.connect = function (wsuri, onconnect, onhangup, options) { - - var peer = {}; - peer.wsuri = wsuri; - - if (!options) { - peer.options = {}; - } else { - peer.options = options; - } - - if (peer.options.retryDelay === undefined) { - peer.options.retryDelay = 5000; - } - - if (peer.options.maxRetries === undefined) { - peer.options.maxRetries = 10; - } - - if (peer.options.skipSubprotocolCheck === undefined) { - peer.options.skipSubprotocolCheck = false; - } - - if (peer.options.skipSubprotocolAnnounce === undefined) { - peer.options.skipSubprotocolAnnounce = false; - } - - if (!onconnect) { - throw "onConnect handler required!"; - } else { - peer.onConnect = onconnect; - } - - if (!onhangup) { - peer.onHangup = function (code, reason, detail) { - if (ab._debugconnect) { - console.log(code, reason, detail); - } - }; - } else { - peer.onHangup = onhangup; - } - - peer.connects = 0; // total number of successful connects - peer.retryCount = 0; // number of retries since last successful connect - - ab._connect(peer); - }; - - - ab.launch = function (appConfig, onOpen, onClose) { - - function Rpc(session, uri) { - return function() { - var args = [uri]; - for (var j = 0; j < arguments.length; ++j) { - args.push(arguments[j]); - } - //arguments.unshift(uri); - return ab.Session.prototype.call.apply(session, args); - }; - } - - function createApi(session, perms) { - session.api = {}; - for (var i = 0; i < perms.rpc.length; ++i) { - var uri = perms.rpc[i].uri; - - var _method = uri.split("#")[1]; - var _class = uri.split("#")[0].split("/"); - _class = _class[_class.length - 1]; - - if (!(_class in session.api)) { - session.api[_class] = {}; - } - - session.api[_class][_method] = new Rpc(session, uri); - } - } - - ab.connect(appConfig.wsuri, - - // connection established handler - function (session) { - if (!appConfig.appkey || appConfig.appkey === "") { - // Authenticate as anonymous .. - session.authreq().then(function () { - session.auth().then(function (permissions) { - //createApi(session, permissions); - if (onOpen) { - onOpen(session); - } else if (ab._debugconnect) { - session.log('Session opened.'); - } - }, session.log); - }, session.log); - } else { - // Authenticate as appkey .. - session.authreq(appConfig.appkey, appConfig.appextra).then(function (challenge) { - - var signature = null; - - if (typeof(appConfig.appsecret) === 'function') { - signature = appConfig.appsecret(challenge); - } else { - // derive secret if salted WAMP-CRA - var secret = ab.deriveKey(appConfig.appsecret, JSON.parse(challenge).authextra); - - // direct sign - signature = session.authsign(challenge, secret); - } - - session.auth(signature).then(function (permissions) { - //createApi(session, permissions); - if (onOpen) { - onOpen(session); - } else if (ab._debugconnect) { - session.log('Session opened.'); - } - }, session.log); - }, session.log); - } - }, - - // connection lost handler - function (code, reason, detail) { - if (onClose) { - onClose(code, reason, detail); - } else if (ab._debugconnect) { - ab.log('Session closed.', code, reason, detail); - } - }, - - // WAMP session config - appConfig.sessionConfig - ); - }; - - return ab; -})); - /** * @module Hook */ var Hook = { - VERSION: "0.1.0", + VERSION: "0.3.4", defaults: { perPage: 50 } @@ -9980,55 +8277,72 @@ Hook.Client.prototype.getPayload = function(method, data) { if (data instanceof FormData){ payload = data; } else if (method !== "GET") { - var field, value, filename, - formdata = new FormData(), + var formdata = new FormData(), worth = false; - for (field in data) { - value = data[field]; - filename = null; + var getFieldName = function(nested) { + var name = nested.shift(); + return (nested.length > 0) ? name + '[' + getFieldName(nested) + ']' : name; + }; - if (typeof(value)==='undefined' || value === null) { - continue; + var appendFormdataRecursively = function(formdata, data, previous) { + var field, value, filename, isFile = false; - } else if (typeof(value)==='boolean' || typeof(value)==='number' || typeof(value)==="string") { - value = value.toString(); + for (field in data) { + value = data[field]; + filename = null; - // IE8 can't compare instanceof String with HTMLInputElement. - } else if (value instanceof HTMLInputElement && value.files && value.files.length > 0) { - filename = value.files[0].name; - value = value.files[0]; - worth = true; + if (typeof(value)==='undefined' || value === null) { + continue; - } else if (value instanceof HTMLInputElement) { - value = value.value; + } else if (typeof(value)==='boolean' || typeof(value)==='number' || typeof(value)==="string") { + value = value.toString(); - } else if (value instanceof HTMLCanvasElement) { - value = dataURLtoBlob(value.toDataURL()); - worth = true; - filename = 'canvas.png'; + // IE8 can't compare instanceof String with HTMLInputElement. + } else if (value instanceof HTMLInputElement && value.files && value.files.length > 0) { + filename = value.files[0].name; + value = value.files[0]; + worth = true; + isFile = true; - } else if (typeof(Blob) !== "undefined" && value instanceof Blob) { - worth = true; - filename = 'blob.' + value.type.match(/\/(.*)/)[1]; // get extension from blob mime/type - } + } else if (value instanceof HTMLInputElement) { + value = value.value; - // - // Consider serialization to keep data types here: http://phpjs.org/functions/serialize/ - // - if (!(value instanceof Array)) { // fixme - if (typeof(value)==="string") { - formdata.append(field, value); - } else { - try { - formdata.append(field, value, filename || "file"); - } catch (e) { - // TODO: - // Node.js (CLI console) throws exception here + } else if (value instanceof HTMLCanvasElement) { + value = dataURLtoBlob(value.toDataURL()); + worth = true; + filename = 'canvas.png'; + + } else if (typeof(Blob) !== "undefined" && value instanceof Blob) { + worth = true; + filename = 'blob.' + value.type.match(/\/(.*)/)[1]; // get extension from blob mime/type + + } else if (typeof(value)==="object") { + appendFormdataRecursively(formdata, value, previous.concat(field)); + continue; + } + + // + // Consider serialization to keep data types here: http://phpjs.org/functions/serialize/ + // + if (!(value instanceof Array)) { // fixme + var fieldname = (isFile) ? field : getFieldName(previous.concat(field)); + + if (typeof(value)==="string") { + formdata.append(fieldname, value); + } else { + try { + formdata.append(fieldname, value, filename || "file"); + } catch (e) { + // TODO: + // Node.js (CLI console) throws exception here + } } } } - } + }; + + appendFormdataRecursively(formdata, data, []); if (worth) { payload = formdata; diff --git a/dist/hook.min.js b/dist/hook.min.js index f02a89a..733e54d 100644 --- a/dist/hook.min.js +++ b/dist/hook.min.js @@ -1,3 +1,2 @@ -!function(a){"undefined"==typeof a.define&&(a.define=function(b,c){try{delete a.define}catch(d){a.define=void 0}"function"==typeof b?a.when=b():a[b]=c()},a.define.amd={}),function(a){function b(b){return function(e,f){if("string"==typeof f){var g=c.exec(f);if(g)return new Date(f);if(!JSON.parseMsAjaxDate)return f;if(g=d.exec(f)){var h=g[1].split(/[-+,.]/);return new Date(h[0]?+h[0]:0-+h[1])}}return b!==a?b(e,f):f}}if(this.JSON&&!this.JSON.dateParser){var c=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.{0,1}\d*))(?:Z|(\+|-)([\d|:]*))?$/,d=/^\/Date\((d|-|.*)\)[\/|\\]$/;JSON.parseMsAjaxDate=!1,JSON.useDateParser=function(a){"undefined"!=typeof a?JSON._parseSaved&&(JSON.parse=JSON._parseSaved,JSON._parseSaved=null):JSON.parseSaved||(JSON._parseSaved=JSON.parse,JSON.parse=JSON.parseWithDate)},JSON.dateParser=b(),JSON.parseWithDate=function(a,c){var d=JSON._parseSaved?JSON._parseSaved:JSON.parse;try{var e=d(a,b(c));return e}catch(f){throw new Error("JSON content could not be parsed")}},JSON.dateStringToDate=function(a,b){if(b||(b=null),!a)return b;if(a.getTime)return a;('"'===a[0]||"'"===a[0])&&(a=a.substr(1,a.length-2));var e=c.exec(a);if(e)return new Date(a);if(!JSON.parseMsAjaxDate)return b;if(e=d.exec(a)){var f=e[1].split(/[-,.]/);return new Date(+f[0])}return b}}}(),function(a){"use strict";a(function(a){function b(a,b,c,d){return e(a).then(b,c,d)}function c(a){return new d(a,P.PromiseStatus&&P.PromiseStatus())}function d(a,b){function c(){return k?k.inspect():A()}function d(a,b,c,d,e){function f(f){f._when(a,b,c,d,e)}l?l.push(f):B(function(){f(k)})}function e(a){if(l){var c=l;l=T,k=j(h,a),B(function(){b&&o(k,b),i(c,k)})}}function f(a){e(new m(a))}function g(a){if(l){var b=l;B(function(){i(b,new n(a))})}}var h,k,l=[];h=this,this._status=b,this.inspect=c,this._when=d;try{a(e,f,g)}catch(p){f(p)}}function e(a){return a instanceof d?a:f(a)}function f(a){return c(function(b){b(a)})}function g(a){return b(a,function(a){return new m(a)})}function h(){function a(a,c,g){b.resolve=b.resolver.resolve=function(b){return e?f(b):(e=!0,a(b),d)},b.reject=b.resolver.reject=function(a){return e?f(new m(a)):(e=!0,c(a),d)},b.notify=b.resolver.notify=function(a){return g(a),a}}var b,d,e;return b={promise:T,resolve:T,reject:T,notify:T,resolver:{resolve:T,reject:T,notify:T}},b.promise=d=c(a),b}function i(a,b){for(var c=0;c>>0,i=Math.max(0,Math.min(d,o)),k=[],j=o-i+1,l=[],i)for(n=function(a){l.push(a),--j||(m=n=D,e(l))},m=function(a){k.push(a),--i||(m=n=D,c(k))},p=0;o>p;++p)p in a&&b(a[p],h,g,f);else c(k)}return c(h).then(e,f,g)})}function r(a,b,c,d){function e(a){return b?b(a[0]):a[0]}return q(a,1,e,c,d)}function s(a,b,c,d){return w(a,D).then(b,c,d)}function t(){return w(arguments,D)}function u(a){return w(a,y,z)}function v(a,b){return w(a,b)}function w(a,c,e){return b(a,function(a){function f(d,f,g){function h(a,h){b(a,c,e).then(function(a){i[h]=a,--k||d(i)},f,g)}var i,j,k,l;if(k=j=a.length>>>0,i=[],!k)return void d(i);for(l=0;j>l;l++)l in a?h(a[l],l):--k}return new d(f)})}function x(a,c){var d=J(I,arguments,1);return b(a,function(a){var e;return e=a.length,d[0]=function(a,d,f){return b(a,function(a){return b(d,function(b){return c(a,b,f,e)})})},H.apply(a,d)})}function y(a){return{state:"fulfilled",value:a}}function z(a){return{state:"rejected",reason:a}}function A(){return{state:"pending"}}function B(a){1===L.push(a)&&K(C)}function C(){i(L),L=[]}function D(a){return a}function E(a){throw"function"==typeof P.reportUnhandled?P.reportUnhandled():B(function(){throw a}),a}b.promise=c,b.resolve=f,b.reject=g,b.defer=h,b.join=t,b.all=s,b.map=v,b.reduce=x,b.settle=u,b.any=r,b.some=q,b.isPromise=p,b.isPromiseLike=p,F=d.prototype,F.then=function(a,b,c){var e=this;return new d(function(d,f,g){e._when(d,g,a,b,c)},this._status&&this._status.observed())},F["catch"]=F.otherwise=function(a){return this.then(T,a)},F["finally"]=F.ensure=function(a){function b(){return f(a())}return"function"==typeof a?this.then(b,b)["yield"](this):this},F.done=function(a,b){this.then(a,b)["catch"](E)},F["yield"]=function(a){return this.then(function(){return a})},F.tap=function(a){return this.then(a)["yield"](this)},F.spread=function(a){return this.then(function(b){return s(b,function(b){return a.apply(T,b)})})},F.always=function(a,b){return this.then(a,a,b)},G=Object.create||function(a){function b(){}return b.prototype=a,new b},l.prototype=G(F),l.prototype.inspect=function(){return y(this.value)},l.prototype._when=function(a,b,c){try{a("function"==typeof c?c(this.value):this.value)}catch(d){a(new m(d))}},m.prototype=G(F),m.prototype.inspect=function(){return z(this.value)},m.prototype._when=function(a,b,c,d){try{a("function"==typeof d?d(this.value):this)}catch(e){a(new m(e))}},n.prototype=G(F),n.prototype._when=function(a,b,c,d,e){try{b("function"==typeof e?e(this.value):this.value)}catch(f){b(f)}};var F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T;if(R=a,L=[],P="undefined"!=typeof console?console:b,"object"==typeof process&&process.nextTick)K=process.nextTick;else if(S="function"==typeof MutationObserver&&MutationObserver||"function"==typeof WebKitMutationObserver&&WebKitMutationObserver)K=function(a,b,c){var d=a.createElement("div");return new b(c).observe(d,{attributes:!0}),function(){d.setAttribute("x","x")}}(document,S,C);else try{K=R("vertx").runOnLoop||R("vertx").runOnContext}catch(U){Q=setTimeout,K=function(a){Q(a,0)}}return M=Function.prototype,N=M.call,J=M.bind?N.bind(N):function(a,b){return a.apply(b,I.call(arguments,2))},O=[],I=O.slice,H=O.reduce||function(a){var b,c,d,e,f;if(f=0,b=Object(this),e=b.length>>>0,c=arguments,c.length<=1)for(;;){if(f in b){d=b[f++];break}if(++f>=e)throw new TypeError}else d=c[1];for(;e>f;++f)f in b&&(d=a(d,b[f],f,b));return d},b})}("function"==typeof define&&define.amd?define:function(a){module.exports=a(require)}),function(a,b){"object"==typeof exports?module.exports=b():"function"==typeof define&&define.amd?define("uxhr",b):a.uxhr=b()}(this,function(){"use strict";return function(b,c,d){c=c||"",d=d||{};var e=d.complete||function(){},f=d.success||function(){},g=d.error||function(){},h=d.timeout||0,i=d.ontimeout||function(){},j=d.onprogress||function(){},k=d.headers||{},l=d.method||"GET",m=d.sync||!1,n=function(){return 0===b.indexOf("http")&&"undefined"!=typeof XDomainRequest?new XDomainRequest:new XMLHttpRequest}();if(!n)throw new Error("Browser doesn't support XHR");var o="undefined"!=typeof a.FormData;if("string"!=typeof c&&o&&!(c instanceof a.FormData)){var p=[];for(var q in c)p.push(q+"="+c[q]);c=p.join("&")}if("GET"===l&&c&&(b+=b.indexOf("?")>=0?"&"+c:"?"+c),n.open(l,b,!m),m||"ontimeout"in n&&(n.timeout=h,n.ontimeout=i),"onprogress"in n&&(n.onprogress=j),n.onload=function(){e(n.responseText,n.status),f(n.responseText)},n.onerror=function(){e(n.responseText),g(n.responseText,n.status)},"undefined"!=typeof n.setRequestHeader)for(var r in k)n.setRequestHeader(r,k[r]);return n.send("GET"!==l?c:null),n}}),function(){function b(a,b,c){for(var d=(c||0)-1,e=a?a.length:0;++d-1?0:-1:a?0:-1}function e(a){var b=this.cache,c=typeof a;if("boolean"==c||null==a)b[a]=!0;else{"number"!=c&&"string"!=c&&(c="object");var d="number"==c?a:t+a,e=b[c]||(b[c]={});"object"==c?(e[d]||(e[d]=[])).push(a):e[d]=!0}}function f(a){return a.charCodeAt(0)}function g(a,b){for(var c=a.criteria,d=b.criteria,e=-1,f=c.length;++eh||"undefined"==typeof g)return 1;if(h>g||"undefined"==typeof h)return-1}}return a.index-b.index}function h(a){var b=-1,c=a.length,d=a[0],f=a[c/2|0],g=a[c-1];if(d&&"object"==typeof d&&f&&"object"==typeof f&&g&&"object"==typeof g)return!1;var h=k();h["false"]=h["null"]=h["true"]=h.undefined=!1;var i=k();for(i.array=a,i.cache=h,i.push=e;++be?0:e);++d=u&&f===b,j=[];if(i){var k=h(c);k?(f=d,c=k):i=!1}for(;++e-1:void 0});return e.pop(),f.pop(),s&&(l(e),l(f)),g}function cb(a,b,c,d,e){(Zd(b)?Yb:he)(b,function(b,f){var g,h,i=b,j=a[f];if(b&&((h=Zd(b))||ie(b))){for(var k=d.length;k--;)if(g=d[k]==b){j=e[k];break}if(!g){var l;c&&(i=c(j,b),(l="undefined"!=typeof i)&&(j=i)),l||(j=h?Zd(j)?j:[]:ie(j)?j:{}),d.push(b),e.push(j),l||cb(j,b,c,d,e)}}else c&&(i=c(j,b),"undefined"==typeof i&&(i=b)),"undefined"!=typeof i&&(j=i);a[f]=j})}function db(a,b){return a+Ed(Vd()*(b-a+1))}function eb(a,c,e){var f=-1,g=ib(),i=a?a.length:0,k=[],n=!c&&i>=u&&g===b,o=e||n?j():k;if(n){var p=h(o);g=d,o=p}for(;++f3&&"function"==typeof b[c-2])var d=X(b[--c-1],b[c--],2);else c>2&&"function"==typeof b[c-1]&&(d=b[--c]);for(var e=n(arguments,1,c),f=-1,g=j(),h=j();++fc?Sd(0,f+c):c)||0,Zd(a)?g=e(a,b,c)>-1:"number"==typeof f?g=(Jb(a)?a.indexOf(b,c):e(a,b,c))>-1:he(a,function(a){return++d>=c?!(g=a===b):void 0}),g}function Ub(a,b,d){var e=!0;b=c.createCallback(b,d,3);var f=-1,g=a?a.length:0;if("number"==typeof g)for(;++fg&&(g=j)}else b=null==b&&Jb(a)?f:c.createCallback(b,d,3),Yb(a,function(a,c,d){var f=b(a,c,d);f>e&&(e=f,g=a)});return g}function bc(a,b,d){var e=1/0,g=e;if("function"!=typeof b&&d&&d[b]===a&&(b=null),null==b&&Zd(a))for(var h=-1,i=a.length;++hj&&(g=j)}else b=null==b&&Jb(a)?f:c.createCallback(b,d,3),Yb(a,function(a,c,d){var f=b(a,c,d);e>f&&(e=f,g=a)});return g}function cc(a,b,d,e){if(!a)return d;var f=arguments.length<3;b=c.createCallback(b,e,4);var g=-1,h=a.length;if("number"==typeof h)for(f&&(d=a[++g]);++gd?Sd(0,e+d):d||0}else if(d){var f=Ac(a,c);return a[f]===c?f:-1}return b(a,c,d)}function sc(a,b,d){var e=0,f=a?a.length:0;if("number"!=typeof b&&null!=b){var g=f;for(b=c.createCallback(b,d,3);g--&&b(a[g],g,a);)e++}else e=null==b||d?1:b||e;return n(a,0,Td(Sd(0,f-e),f))}function tc(){for(var a=[],c=-1,e=arguments.length,f=j(),g=ib(),i=g===b,k=j();++c=u&&h(c?a[c]:k)))}var o=a[0],p=-1,q=o?o.length:0,r=[];a:for(;++pc?Sd(0,d+c):Td(c,d-1))+1);d--;)if(a[d]===b)return d;return-1}function wc(a){for(var b=arguments,c=0,d=b.length,e=a?a.length:0;++cf;){var h=f+g>>>1;d(a[h])1?arguments:arguments[0],b=-1,c=a?ac(me(a,"length")):0,d=nd(0>c?0:c);++b2?gb(a,17,n(arguments,2),null,b):gb(a,1,null,null,b)}function Jc(a){for(var b=arguments.length>1?_(arguments,!0,!1,1):ub(a),c=-1,d=b.length;++c2?gb(b,19,n(arguments,2),null,a):gb(b,3,null,null,a)}function Lc(){for(var a=arguments,b=a.length;b--;)if(!Db(a[b]))throw new wd;return function(){for(var b=arguments,c=a.length;c--;)b=[a[c].apply(this,b)];return b[0]}}function Mc(a,b){return b="number"==typeof b?b:+b||a.length,gb(a,4,null,null,null,b)}function Nc(a,b,c){var d,e,f,g,h,i,j,k=0,l=!1,m=!0;if(!Db(a))throw new wd;if(b=Sd(0,b)||0,c===!0){var n=!0;m=!1}else Eb(c)&&(n=c.leading,l="maxWait"in c&&(Sd(b,c.maxWait)||0),m="trailing"in c?c.trailing:m);var o=function(){var c=b-(oe()-g);if(0>=c){e&&Dd(e);var l=j;e=i=j=p,l&&(k=oe(),f=a.apply(h,d),i||e||(d=h=null))}else i=Jd(o,c)},q=function(){i&&Dd(i),e=i=j=p,(m||l!==b)&&(k=oe(),f=a.apply(h,d),i||e||(d=h=null))};return function(){if(d=arguments,g=oe(),h=this,j=m&&(i||!n),l===!1)var c=n&&!i;else{e||n||(k=g);var p=l-(g-k),r=0>=p;r?(e&&(e=Dd(e)),k=g,f=a.apply(h,d)):e||(e=Jd(q,p))}return r&&i?i=Dd(i):i||b===l||(i=Jd(o,b)),c&&(r=!0,f=a.apply(h,d)),!r||i||e||(d=h=null),f}}function Oc(a){if(!Db(a))throw new wd;var b=n(arguments,1);return Jd(function(){a.apply(p,b)},1)}function Pc(a,b){if(!Db(a))throw new wd;var c=n(arguments,2);return Jd(function(){a.apply(p,c)},b)}function Qc(a,b){if(!Db(a))throw new wd;var c=function(){var d=c.cache,e=b?b.apply(this,arguments):t+arguments[0];return Hd.call(d,e)?d[e]:d[e]=a.apply(this,arguments)};return c.cache={},c}function Rc(a){var b,c;if(!Db(a))throw new wd;return function(){return b?c:(b=!0,c=a.apply(this,arguments),a=null,c)}}function Sc(a){return gb(a,16,n(arguments,1))}function Tc(a){return gb(a,32,null,n(arguments,1))}function Uc(a,b,c){var d=!0,e=!0;if(!Db(a))throw new wd;return c===!1?d=!1:Eb(c)&&(d="leading"in c?c.leading:d,e="trailing"in c?c.trailing:e),U.leading=d,U.maxWait=b,U.trailing=e,Nc(a,b,U)}function Vc(a,b){return gb(b,16,[a])}function Wc(a){return function(){return a}}function Xc(a,b,c){var d=typeof a;if(null==a||"function"==d)return X(a,b,c);if("object"!=d)return bd(a);var e=_d(a),f=e[0],g=a[f];return 1!=e.length||g!==g||Eb(g)?function(b){for(var c=e.length,d=!1;c--&&(d=ab(b[e[c]],a[e[c]],null,!0)););return d}:function(a){var b=a[f];return g===b&&(0!==g||1/g==1/b)}}function Yc(a){return null==a?"":vd(a).replace(de,hb)}function Zc(a){return a}function $c(a,b,d){var f=!0,g=b&&ub(b);b&&(d||g.length)||(null==d&&(d=b),h=e,b=a,a=c,g=ub(b)),d===!1?f=!1:Eb(d)&&"chain"in d&&(f=d.chain);var h=a,i=Db(h);Yb(g,function(c){var d=a[c]=b[c];i&&(h.prototype[c]=function(){var b=this.__chain__,c=this.__wrapped__,e=[c];Id.apply(e,arguments);var g=d.apply(a,e);if(f||b){if(c===g&&Eb(g))return this;g=new h(g),g.__chain__=b}return g})})}function _c(){return a._=zd,this}function ad(){}function bd(a){return function(b){return b[a]}}function cd(a,b,c){var d=null==a,e=null==b;if(null==c&&("boolean"==typeof a&&e?(c=a,a=1):e||"boolean"!=typeof b||(c=b,e=!0)),d&&e&&(b=1),a=+a||0,e?(b=a,a=0):b=+b||0,c||a%1||b%1){var f=Vd();return Td(a+f*(b-a+parseFloat("1e-"+((f+"").length-1))),b)}return db(a,b)}function dd(a,b){if(a){var c=a[b];return Db(c)?a[b]():c}}function ed(a,b,d){var e=c.templateSettings;a=vd(a||""),d=fe({},d,e);var f,g=fe({},d.imports,e.imports),h=_d(g),j=Rb(g),k=0,l=d.interpolate||F,m="__p += '",n=ud((d.escape||F).source+"|"+l.source+"|"+(l===D?A:F).source+"|"+(d.evaluate||F).source+"|$","g");a.replace(n,function(b,c,d,e,g,h){return d||(d=e),m+=a.slice(k,h).replace(H,i),c&&(m+="' +\n__e("+c+") +\n'"),g&&(f=!0,m+="';\n"+g+";\n__p += '"),d&&(m+="' +\n((__t = ("+d+")) == null ? '' : __t) +\n'"),k=h+b.length,b}),m+="';\n";var o=d.variable,q=o;q||(o="obj",m="with ("+o+") {\n"+m+"\n}\n"),m=(f?m.replace(x,""):m).replace(y,"$1").replace(z,"$1;"),m="function("+o+") {\n"+(q?"":o+" || ("+o+" = {});\n")+"var __t, __p = '', __e = _.escape"+(f?", __j = Array.prototype.join;\nfunction print() { __p += __j.call(arguments, '') }\n":";\n")+m+"return __p\n}";var r="\n/*\n//# sourceURL="+(d.sourceURL||"/lodash/template/source["+J++ +"]")+"\n*/";try{var s=qd(h,"return "+m+r).apply(p,j)}catch(t){throw t.source=m,t}return b?s(b):(s.source=m,s)}function fd(a,b,c){a=(a=+a)>-1?a:0;var d=-1,e=nd(a);for(b=X(b,c,1);++d/g,evaluate:/<%([\s\S]+?)%>/g,interpolate:D,variable:"",imports:{_:c}},Nd||(v=function(){function b(){}return function(c){if(Eb(c)){b.prototype=c;var d=new b;b.prototype=null}return d||a.Object()}}());var Yd=Md?function(a,b){V.value=b,Md(a,"__bindData__",V)}:ad,Zd=Od||function(a){return a&&"object"==typeof a&&"number"==typeof a.length&&Ad.call(a)==L||!1},$d=function(a){var b,c=a,d=[];if(!c)return d;if(!W[typeof a])return d;for(b in c)Hd.call(c,b)&&d.push(b);return d},_d=Rd?function(a){return Eb(a)?Rd(a):[]}:$d,ae={"&":"&","<":"<",">":">",'"':""","'":"'"},be=wb(ae),ce=ud("("+_d(be).join("|")+")","g"),de=ud("["+_d(ae).join("")+"]","g"),ee=function(a,b,c){var d,e=a,f=e;if(!e)return f;var g=arguments,h=0,i="number"==typeof c?2:g.length;if(i>3&&"function"==typeof g[i-2])var j=X(g[--i-1],g[i--],2);else i>2&&"function"==typeof g[i-1]&&(j=g[--i]);for(;++h/g,E=RegExp("^["+w+"]*0+(?=.$)"),F=/($^)/,G=/\bthis\b/,H=/['\n\r\t\u2028\u2029\\]/g,I=["Array","Boolean","Date","Function","Math","Number","Object","RegExp","String","_","attachEvent","clearTimeout","isFinite","isNaN","parseInt","setTimeout"],J=0,K="[object Arguments]",L="[object Array]",M="[object Boolean]",N="[object Date]",O="[object Function]",P="[object Number]",Q="[object Object]",R="[object RegExp]",S="[object String]",T={};T[O]=!1,T[K]=T[L]=T[M]=T[N]=T[P]=T[Q]=T[R]=T[S]=!0;var U={leading:!1,maxWait:0,trailing:!1},V={configurable:!1,enumerable:!1,value:null,writable:!1},W={"boolean":!1,"function":!0,object:!0,number:!1,string:!1,undefined:!1},X={"\\":"\\","'":"'","\n":"n","\r":"r"," ":"t","\u2028":"u2028","\u2029":"u2029"},Y=W[typeof a]&&a||this,Z=W[typeof exports]&&exports&&!exports.nodeType&&exports,$=W[typeof module]&&module&&!module.nodeType&&module,_=$&&$.exports===Z&&Z,ab=W[typeof c]&&c;!ab||ab.global!==ab&&ab.window!==ab||(Y=ab);var bb=o();"function"==typeof define&&"object"==typeof define.amd&&define.amd?(Y._=bb,define(function(){return bb})):Z&&$?_?($.exports=bb)._=bb:Z._=bb:Y._=bb}.call(this),!function(a){"use strict";var b=a.HTMLCanvasElement&&a.HTMLCanvasElement.prototype,c=a.Blob&&function(){try{return Boolean(new Blob)}catch(a){return!1}}(),d=c&&a.Uint8Array&&function(){try{return 100===new Blob([new Uint8Array(100)]).size}catch(a){return!1}}(),e=a.BlobBuilder||a.WebKitBlobBuilder||a.MozBlobBuilder||a.MSBlobBuilder,f=(c||e)&&a.atob&&a.ArrayBuffer&&a.Uint8Array&&function(a){var b,f,g,h,i,j;for(b=a.split(",")[0].indexOf("base64")>=0?atob(a.split(",")[1]):decodeURIComponent(a.split(",")[1]),f=new ArrayBuffer(b.length),g=new Uint8Array(f),h=0;hc?z:c>A?A:c}function h(a,b,c){try{"function"==typeof b&&b.call(a,c)}catch(e){d(e)}}function i(b,d){function i(){L=s,null!==H&&(H.abort(),H=null),0!==I&&(clearTimeout(I),I=0),0!==J&&(clearTimeout(J),J=0),E.readyState=s}function j(a){var b=L===r||L===q?H.responseText||"":"",c=null,d=!1;if(L===q){var i=0,j="",k="";if(n)try{i=Number(H.status||0),j=String(H.statusText||""),k=String(H.getResponseHeader("Content-Type")||"")}catch(l){i=0}else i=200,k=H.contentType;if(200===i&&y.test(k)){if(L=r,G=!0,F=B,E.readyState=r,c=new e("open"),E.dispatchEvent(c),h(E,E.onopen,c),L===s)return}else if(0!==i){var m="";m=200!==i?"EventSource's response has a status "+i+" "+j.replace(/\s+/g," ")+" that is not 200. Aborting the connection.":"EventSource's response has a Content-Type specifying an unsupported type: "+k.replace(/\s+/g," ")+". Aborting the connection.",setTimeout(function(){throw new Error(m)}),d=!0}}if(L===r){b.length>K&&(G=!0);for(var o=K-1,z=b.length,J="\n";++o1048576||0===I&&!G)?0===I&&(G=!1,I=setTimeout(P,C)):(L=p,H.abort(),0!==I&&(clearTimeout(I),I=0),F>16*B&&(F=16*B),F>A&&(F=A),I=setTimeout(P,F),F=2*F+1,E.readyState=q,c=new e("error"),E.dispatchEvent(c),h(E,E.onerror,c))}function k(){j(!1)}function l(){j(!0)}b=String(b);var z=Boolean(m&&d&&d.withCredentials),B=g(d?d.retry:0/0,1e3),C=g(d?d.heartbeatTimeout:0/0,45e3),D=d&&d.lastEventId&&String(d.lastEventId)||"",E=this,F=B,G=!1,H=new o,I=0,J=0,K=0,L=p,M=[],N="",O="",P=null,Q=u,R="",S="";d=null,n&&(J=setTimeout(function T(){3===H.readyState&&k(),J=setTimeout(T,500)},0)),P=function(){if(I=0,L!==p)return void j(!1);if(n&&(void 0!==H.sendAsBinary||void 0===H.onloadend)&&a.document&&a.document.readyState&&"complete"!==a.document.readyState)return void(I=setTimeout(P,4));H.onload=H.onerror=l,n&&(H.onabort=l,H.onreadystatechange=k),H.onprogress=k,G=!1,I=setTimeout(P,C),K=0,L=q,M.length=0,O="",N=D,S="",R="",Q=u;var c=b.slice(0,5);c="data:"!==c&&"blob:"!==c?b+((-1===b.indexOf("?",0)?"?":"&")+"lastEventId="+encodeURIComponent(D)+"&r="+String(Math.random()+1).slice(2)):b,H.open("GET",c,!0),n&&(H.withCredentials=z,H.responseType="text",H.setRequestHeader("Accept","text/event-stream")),H.send(null)},c.call(this),this.close=i,this.url=b,this.readyState=q,this.withCredentials=z,this.onopen=null,this.onmessage=null,this.onerror=null,P()}function j(){this.CONNECTING=q,this.OPEN=r,this.CLOSED=s}b.prototype={get:function(a){return this.data[a+"~"]},set:function(a,b){this.data[a+"~"]=b},"delete":function(a){delete this.data[a+"~"]}},c.prototype={dispatchEvent:function(a){a.target=this;var b=String(a.type),c=this.listeners,e=c.get(b);if(e)for(var f=e.length,g=-1,h=null;++g=0;)if(d[e]===b)return;d.push(b)},removeEventListener:function(a,b){a=String(a);var c=this.listeners,d=c.get(a);if(d){for(var e=d.length,f=[],g=-1;++g>>0;if(0===c)return-1;var d=0;if(arguments.length>0&&(d=Number(arguments[1]),d!==d?d=0:0!==d&&1/0!==d&&d!==-1/0&&(d=(d>0||-1)*Math.floor(Math.abs(d)))),d>=c)return-1;for(var e=d>=0?d:Math.max(c-Math.abs(d),0);c>e;e++)if(e in b&&b[e]===a)return e;return-1}),Array.prototype.forEach||(Array.prototype.forEach=function(a,b){var c,d;if(null===this)throw new TypeError(" this is null or not defined");var e=new Object(this),f=e.length>>>0;if("[object Function]"!=={}.toString.call(a))throw new TypeError(a+" is not a function");for(b&&(c=b),d=0;f>d;){var g;d in e&&(g=e[d],a.call(c,g,d,e)),d++}})}(),d._sliceUserAgent=function(a,b,c){var d=[],e=navigator.userAgent,f=e.indexOf(a),g=e.indexOf(b,f);0>g&&(g=e.length);for(var h=e.slice(f,g).split(c),i=h[1].split("."),j=0;j-1?d._sliceUserAgent("Chrome"," ","/"):a.indexOf("Safari")>-1?d._sliceUserAgent("Safari"," ","/"):a.indexOf("Firefox")>-1?d._sliceUserAgent("Firefox"," ","/"):a.indexOf("MSIE")>-1?d._sliceUserAgent("MSIE",";"," "):null},d.getServerUrl=function(b,c){if("file:"===a.location.protocol)return c?c:"ws://127.0.0.1/ws";var d="https:"===a.location.protocol?"wss://":"ws://",e=""!==a.location.port?":"+a.location.port:"",f=b?b:"ws";return d+a.location.hostname+e+"/"+f},d.browserNotSupportedMessage="Browser does not support WebSockets (RFC6455)",d.deriveKey=function(a,b){if(b&&b.salt){var c=b.salt,d=b.keylen||32,e=b.iterations||1e4,f=CryptoJS.PBKDF2(a,c,{keySize:d/4,iterations:e,hasher:CryptoJS.algo.SHA256});return f.toString(CryptoJS.enc.Base64)}return a},d._idchars="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",d._idlen=16,d._subprotocol="wamp",d._newid=function(){for(var a="",b=0;b1){console.group("Log Item");for(var a=0;a=0){var e=a.substring(0,d);if(c._index[e])return c._index[e]+a.substring(d+1)}return b===!0?a:null},d.PrefixMap.prototype.shrink=function(a,b){for(var c=this,d=a.length;d>0;d-=1){var e=a.substring(0,d),f=c._rindex[e];if(f)return f+":"+a.substring(d)}return b===!0?a:null},d._MESSAGE_TYPEID_WELCOME=0,d._MESSAGE_TYPEID_PREFIX=1,d._MESSAGE_TYPEID_CALL=2,d._MESSAGE_TYPEID_CALL_RESULT=3,d._MESSAGE_TYPEID_CALL_ERROR=4,d._MESSAGE_TYPEID_SUBSCRIBE=5,d._MESSAGE_TYPEID_UNSUBSCRIBE=6,d._MESSAGE_TYPEID_PUBLISH=7,d._MESSAGE_TYPEID_EVENT=8,d.CONNECTION_CLOSED=0,d.CONNECTION_LOST=1,d.CONNECTION_RETRIES_EXCEEDED=2,d.CONNECTION_UNREACHABLE=3,d.CONNECTION_UNSUPPORTED=4,d.CONNECTION_UNREACHABLE_SCHEDULED_RECONNECT=5,d.CONNECTION_LOST_SCHEDULED_RECONNECT=6,d.Deferred=c.defer,d._construct=function(b,c){return"WebSocket"in a?c?new WebSocket(b,c):new WebSocket(b):"MozWebSocket"in a?c?new MozWebSocket(b,c):new MozWebSocket(b):null},d.Session=function(a,b,c,e){var f=this;if(f._wsuri=a,f._options=e,f._websocket_onopen=b,f._websocket_onclose=c,f._websocket=null,f._websocket_connected=!1,f._session_id=null,f._wamp_version=null,f._server=null,f._calls={},f._subscriptions={},f._prefixes=new d.PrefixMap,f._txcnt=0,f._rxcnt=0,f._websocket=f._options&&f._options.skipSubprotocolAnnounce?d._construct(f._wsuri):d._construct(f._wsuri,[d._subprotocol]),!f._websocket){if(void 0!==c)return void c(d.CONNECTION_UNSUPPORTED);throw d.browserNotSupportedMessage}f._websocket.onmessage=function(a){d._debugws&&(f._rxcnt+=1,console.group("WS Receive"),console.info(f._wsuri+" ["+f._session_id+"]"),console.log(f._rxcnt),console.log(a.data),console.groupEnd());var b=JSON.parse(a.data);if(b[1]in f._calls){if(b[0]===d._MESSAGE_TYPEID_CALL_RESULT){var c=f._calls[b[1]],e=b[2];if(d._debugrpc&&void 0!==c._ab_callobj){console.group("WAMP Call",c._ab_callobj[2]),console.timeEnd(c._ab_tid),console.group("Arguments");for(var g=3;g3){if(!(arguments[2]instanceof Array))throw"invalid argument type(s)";if(!(arguments[3]instanceof Array))throw"invalid argument type(s)";f=arguments[2],g=arguments[3],h=[d._MESSAGE_TYPEID_PUBLISH,b,c,f,g]}else if(arguments.length>2)if("boolean"==typeof arguments[2])e=arguments[2],h=[d._MESSAGE_TYPEID_PUBLISH,b,c,e];else{if(!(arguments[2]instanceof Array))throw"invalid argument type(s)";f=arguments[2],h=[d._MESSAGE_TYPEID_PUBLISH,b,c,f]}else h=[d._MESSAGE_TYPEID_PUBLISH,b,c];d._debugpubsub&&(console.group("WAMP Publish"),console.info(a._wsuri+" ["+a._session_id+"]"),console.log(b),console.log(c),null!==e?console.log(e):null!==f&&(console.log(f),null!==g&&console.log(g)),console.groupEnd()),a._send(h)},d.Session.prototype.authreq=function(a,b){return this.call("http://api.wamp.ws/procedure#authreq",a,b)},d.Session.prototype.authsign=function(a,b){return b||(b=""),CryptoJS.HmacSHA256(a,b).toString(CryptoJS.enc.Base64)},d.Session.prototype.auth=function(a){return this.call("http://api.wamp.ws/procedure#auth",a)},d._connect=function(b){var c=new d.Session(b.wsuri,function(){b.connects+=1,b.retryCount=0,b.onConnect(c)},function(c,e){var f=null;switch(c){case d.CONNECTION_CLOSED:b.onHangup(c,"Connection was closed properly ["+e+"]");break;case d.CONNECTION_UNSUPPORTED:b.onHangup(c,"Browser does not support WebSocket.");break;case d.CONNECTION_UNREACHABLE:b.retryCount+=1,0===b.connects?b.onHangup(c,"Connection could not be established."):b.retryCount<=b.options.maxRetries?(f=b.onHangup(d.CONNECTION_UNREACHABLE_SCHEDULED_RECONNECT,"Connection unreachable - scheduled reconnect to occur in "+b.options.retryDelay/1e3+" second(s) - attempt "+b.retryCount+" of "+b.options.maxRetries+".",{delay:b.options.retryDelay,retries:b.retryCount,maxretries:b.options.maxRetries}),f?(d._debugconnect&&console.log("Connection unreachable - retrying stopped by app"),b.onHangup(d.CONNECTION_RETRIES_EXCEEDED,"Number of connection retries exceeded.")):(d._debugconnect&&console.log("Connection unreachable - retrying ("+b.retryCount+") .."),a.setTimeout(function(){d._connect(b)},b.options.retryDelay))):b.onHangup(d.CONNECTION_RETRIES_EXCEEDED,"Number of connection retries exceeded.");break;case d.CONNECTION_LOST:b.retryCount+=1,b.retryCount<=b.options.maxRetries?(f=b.onHangup(d.CONNECTION_LOST_SCHEDULED_RECONNECT,"Connection lost - scheduled "+b.retryCount+"th reconnect to occur in "+b.options.retryDelay/1e3+" second(s).",{delay:b.options.retryDelay,retries:b.retryCount,maxretries:b.options.maxRetries}),f?(d._debugconnect&&console.log("Connection lost - retrying stopped by app"),b.onHangup(d.CONNECTION_RETRIES_EXCEEDED,"Connection lost.")):(d._debugconnect&&console.log("Connection lost - retrying ("+b.retryCount+") .."),a.setTimeout(function(){d._connect(b)},b.options.retryDelay))):b.onHangup(d.CONNECTION_RETRIES_EXCEEDED,"Connection lost.");break;default:throw"unhandled close code in ab._connect"}},b.options)},d.connect=function(a,b,c,e){var f={};if(f.wsuri=a,f.options=e?e:{},void 0===f.options.retryDelay&&(f.options.retryDelay=5e3),void 0===f.options.maxRetries&&(f.options.maxRetries=10),void 0===f.options.skipSubprotocolCheck&&(f.options.skipSubprotocolCheck=!1),void 0===f.options.skipSubprotocolAnnounce&&(f.options.skipSubprotocolAnnounce=!1),!b)throw"onConnect handler required!";f.onConnect=b,f.onHangup=c?c:function(a,b,c){d._debugconnect&&console.log(a,b,c)},f.connects=0,f.retryCount=0,d._connect(f)},d.launch=function(a,b,c){d.connect(a.wsuri,function(c){a.appkey&&""!==a.appkey?c.authreq(a.appkey,a.appextra).then(function(e){var f=null;if("function"==typeof a.appsecret)f=a.appsecret(e);else{var g=d.deriveKey(a.appsecret,JSON.parse(e).authextra);f=c.authsign(e,g)}c.auth(f).then(function(){b?b(c):d._debugconnect&&c.log("Session opened.")},c.log)},c.log):c.authreq().then(function(){c.auth().then(function(){b?b(c):d._debugconnect&&c.log("Session opened.")},c.log)},c.log)},function(a,b,e){c?c(a,b,e):d._debugconnect&&d.log("Session closed.",a,b,e)},a.sessionConfig)},d});var d={VERSION:"0.1.0",defaults:{perPage:50}};a.Hook=d,d.Client=function(b){b||(b={}),this.endpoint=b.endpoint||b.url||a.location.origin,this.app_id=b.app_id||b.appId||"",this.key=b.key||"",this.options="undefined"!=typeof b.options?b.options:{},this.endpoint.lastIndexOf("/")!=this.endpoint.length-1&&(this.endpoint+="/"),this.keys=new d.KeyValues(this),this.auth=new d.Auth(this),this.system=new d.System(this),d.Plugin.Manager.setup(this)},d.Client.prototype.collection=function(a){return new d.Collection(this,a)},d.Client.prototype.channel=function(a,b){"undefined"==typeof b&&(b={});var c=this.collection(a);return c.segments=c.segments.replace("collection/","channels/"),b.transport||(b.transport="sse"),b.transport=b.transport.toUpperCase(),new d.Channel[b.transport](this,c,b)},d.Client.prototype.url=function(a,b){var c="";return b&&(c="&"+this.serialize(b)),this.endpoint+a+this._getCredentialsParams()+c},d.Client.prototype.post=function(a,b){return"undefined"==typeof b&&(b={}),this.request(a,"POST",b)},d.Client.prototype.get=function(a,b){return this.request(a,"GET",b)},d.Client.prototype.put=function(a,b){return this.request(a,"PUT",b)},d.Client.prototype.remove=function(a,b){return this.request(a,"DELETE",b)},d.Client.prototype.request=function(a,b,c){var d,e,f=when.defer(),g=!1;c&&c._sync&&(delete c._sync,g=!0),d=this.getPayload(b,c),e=this.getHeaders(),d instanceof FormData||(e["Content-Type"]="application/json"),"GET"!==b&&"POST"!==b&&this.options.method_override&&(e["X-HTTP-Method-Override"]=b,b="POST"),"undefined"!=typeof XDomainRequest&&(a+=this._getCredentialsParams()+"&r="+Math.floor(1e3*Math.random()));var h=f.promise.xhr=uxhr(this.endpoint+a,d,{method:b,headers:e,sync:g,success:function(a){var b,c=null,d=h.getAllResponseHeaders&&h.getAllResponseHeaders()||"";try{c=JSON.parseWithDate(a)}catch(e){}c===!1||null===c||c.error?(c&&c.error&&console.error(c.error),f.resolver.reject(c)):(b=d.match(/x-total-count: ([^\n]+)/i),b&&(c.total=parseInt(b[1])),f.resolver.resolve(c))},error:function(a){var b=null;try{b=JSON.parseWithDate(a)}catch(c){}console.log("Error: ",b||"Invalid JSON response."),f.resolver.reject(b)}});return f.promise},d.Client.prototype.getHeaders=function(){var a,b={"X-App-Id":this.app_id,"X-App-Key":this.key},a=this.auth.getToken();return a&&(b["X-Auth-Token"]=a),b},d.Client.prototype.getPayload=function(a,b){var c=null;if(b){if(b instanceof FormData)c=b;else if("GET"!==a){var d,e,f,g=new FormData,h=!1;for(d in b)if(e=b[d],f=null,"undefined"!=typeof e&&null!==e&&("boolean"==typeof e||"number"==typeof e||"string"==typeof e?e=e.toString():e instanceof HTMLInputElement&&e.files&&e.files.length>0?(f=e.files[0].name,e=e.files[0],h=!0):e instanceof HTMLInputElement?e=e.value:e instanceof HTMLCanvasElement?(e=dataURLtoBlob(e.toDataURL()),h=!0,f="canvas.png"):"undefined"!=typeof Blob&&e instanceof Blob&&(h=!0,f="blob."+e.type.match(/\/(.*)/)[1]),!(e instanceof Array)))if("string"==typeof e)g.append(d,e);else try{g.append(d,e,f||"file")}catch(i){}h&&(c=g)}if(c=c||JSON.stringify(b,function(a,b){return this[a]instanceof Date?Math.round(this[a].getTime()/1e3):b}),"{}"==c)return null;"GET"===a&&"string"==typeof c&&(c=encodeURIComponent(c))}return c},d.Client.prototype._getCredentialsParams=function(){var a="?X-App-Id="+this.app_id+"&X-App-Key="+this.key,b=this.auth.getToken();return b&&(a+="&X-Auth-Token="+b),a},d.Client.prototype.serialize=function(a,b){var c=[];for(var d in a)if(a.hasOwnProperty(d)){var e=b?b+"["+d+"]":d,f=a[d];c.push("object"==typeof f?this.serialize(f,e):encodeURIComponent(e)+"="+encodeURIComponent(f))}return c.join("&")},d.Events=function(){this._events={}},d.Events.prototype.on=function(a,b,c){this._events[a]||(this._events[a]=[]),this._events[a].push({callback:b,context:c||this})},d.Events.prototype.trigger=function(a){var b,c=Array.prototype.slice.call(arguments,1);if(this._events[a])for(var d=0,e=this._events[a].length;e>d;d++)b=this._events[a][d],b.callback.apply(b.context||this.client,c)},d.Iterable=function(){},d.Iterable.prototype={each:function(a){return this._iterate("each",a)},find:function(a){return this._iterate("find",a)},filter:function(a){return this._iterate("filter",a)},max:function(a){return this._iterate("max",a)},min:function(a){return this._iterate("min",a)},every:function(a){return this._iterate("every",a)},reject:function(a,b){return this._iterate("reject",a,b)},groupBy:function(a,b){return this._iterate("groupBy",a,b)},_iterate:function(a,b,c){var d=when.defer();return this.then(function(e){var f=_[a].call(_,e,b,c);d.resolver.resolve(f)}).otherwise(function(a){d.resolver.reject(a)}),d.promise}},"undefined"==typeof a.FormData&&(a.FormData=function(){this.append=function(){}}),a.location.origin||(a.location.origin=a.location.protocol+"//"+a.location.hostname+(a.location.port?":"+a.location.port:"")),d.Plugin={},d.Plugin.Manager={plugins:[]},d.Plugin.Manager.register=function(a,b){this.plugins.push({path:a,klass:b})},d.Plugin.Manager.setup=function(a){for(var b=0,c=this.plugins.length;c>b;b++)a[this.plugins[b].path]=new this.plugins[b].klass(a)},d.Auth=function(b){this.client=b,this.currentUser=null;var c=new Date,e=new Date(a.localStorage.getItem(this.client.app_id+"-"+d.Auth.AUTH_TOKEN_EXPIRATION)),f=a.localStorage.getItem(this.client.app_id+"-"+d.Auth.AUTH_DATA_KEY);f&&c.getTime()1?b.then.apply(b,Array.prototype.slice.call(arguments,1)):b},d.Collection.prototype.join=function(){return this.options["with"]=arguments,this},d.Collection.prototype.distinct=function(){return this.options.distinct=!0,this},d.Collection.prototype.group=function(){return this._group=arguments,this},d.Collection.prototype.count=function(a){a="undefined"==typeof a?"*":a,this.options.aggregation={method:"count",field:a};var b=this.get();return arguments.length>0&&b.then.apply(b,arguments),b},d.Collection.prototype.max=function(a){this.options.aggregation={method:"max",field:a};var b=this.get();return arguments.length>1&&b.then.apply(b,Array.prototype.slice.call(arguments,1)),b},d.Collection.prototype.min=function(a){this.options.aggregation={method:"min",field:a};var b=this.get();return arguments.length>1&&b.then.apply(b,Array.prototype.slice.call(arguments,1)),b},d.Collection.prototype.avg=function(a){this.options.aggregation={method:"avg",field:a};var b=this.get();return arguments.length>1&&b.then.apply(b,Array.prototype.slice.call(arguments,1)),b},d.Collection.prototype.sum=function(a){this.options.aggregation={method:"sum",field:a};var b=this.get();return arguments.length>1&&b.then.apply(b,Array.prototype.slice.call(arguments,1)),b},d.Collection.prototype.first=function(){this.options.first=1;var a=this.get();return a.then.apply(a,arguments),a},d.Collection.prototype.firstOrCreate=function(a){return this.options.first=1,this.options.data=a,this.client.post(this.segments,this.buildQuery())},d.Collection.prototype.then=function(){var a=this.get();return a.then.apply(a,arguments),a},d.Collection.prototype.debug=function(a){return a="undefined"==typeof a?"log":a,this.then(console[a].bind(console))},d.Collection.prototype.reset=function(){return this.options={},this.wheres=[],this.ordering=[],this._group=[],this._limit=null,this._offset=null,this._remember=null,this},d.Collection.prototype.sort=function(a,b){return b?"number"==typeof b&&(b=-1===parseInt(b,10)?"desc":"asc"):b="asc",this.ordering.push([a,b]),this},d.Collection.prototype.limit=function(a){return this._limit=a,this},d.Collection.prototype.offset=function(a){return this._offset=a,this},d.Collection.prototype.remember=function(a){return this._remember=a,this},d.Collection.prototype.channel=function(){throw new Error("Not implemented.")},d.Collection.prototype.drop=function(){return this.client.remove(this.segments)},d.Collection.prototype.remove=function(a){var b=this.segments;return"undefined"!=typeof a&&(b+="/"+a),this.client.remove(b,this.buildQuery())},d.Collection.prototype.update=function(a,b){return this.client.post(this.segments+"/"+a,b)},d.Collection.prototype.increment=function(a,b){this.options.operation={method:"increment",field:a,value:b||1};var c=this.client.put(this.segments,this.buildQuery());return arguments.length>0&&c.then.apply(c,arguments),c},d.Collection.prototype.decrement=function(a,b){this.options.operation={method:"decrement",field:a,value:b||1};var c=this.client.put(this.segments,this.buildQuery());return arguments.length>0&&c.then.apply(c,arguments),c},d.Collection.prototype.updateAll=function(a){return this.options.data=a,this.client.put(this.segments,this.buildQuery())},d.Collection.prototype.addWhere=function(a,b,c,d){return this.wheres.push([a,b.toLowerCase(),c,d]),this},d.Collection.prototype._validateName=function(a){var b=/^[a-z_\/0-9]+$/;if(!b.test(a))throw new Error("Invalid name: "+a);return a},d.Collection.prototype.buildQuery=function(){var a={};null!==this._limit&&(a.limit=this._limit),null!==this._offset&&(a.offset=this._offset),null!==this._remember&&(a.remember=this._remember),this.wheres.length>0&&(a.q=this.wheres),this.ordering.length>0&&(a.s=this.ordering),this._group.length>0&&(a.g=this._group);var b,c={paginate:"p",first:"f",aggregation:"aggr",operation:"op",data:"data","with":"with",select:"select",distinct:"distinct"};for(b in c)this.options[b]&&(a[c[b]]=this.options[b]);return this.reset(),a},d.Collection.prototype.clone=function(){var a=this.client.collection(this.name);return a.options=_.clone(this.options),a.wheres=_.clone(this.wheres),a.ordering=_.clone(this.ordering),a._group=_.clone(this._group),a._limit=_.clone(this._limit),a._offset=_.clone(this._offset),a._remember=_.clone(this._remember),a},d.CollectionItem=function(){},d.KeyValues=function(a){this.client=a},d.KeyValues.prototype.get=function(a,b){var c=this.client.get("key/"+a);return b&&c.then.apply(c,[b]),c},d.KeyValues.prototype.set=function(a,b){return this.client.post("key/"+a,{value:b})},d.Model=function(){},d.Pagination=function(a){this.fetching=!0,this.collection=a},d.Pagination.prototype._fetchComplete=function(a){this.fetching=!1,this.total=a.total,this.per_page=a.per_page,this.current_page=a.current_page,this.last_page=a.last_page,this.from=a.from,this.to=a.to,this.items=a.data},d.Pagination.prototype.hasNext=function(){return this.current_page0&&a.then.apply(a,arguments),a},d.Channel.SSE=function(a,b,c){this.collection=b,this.client_id=null,this.callbacks={},this.options=c||{},this.readyState=null},d.Channel.SSE.prototype.subscribe=function(a,b){"undefined"==typeof b&&(b=a,a="_default"),this.callbacks[a]=b;var c=this.connect();if(this.readyState===EventSource.CONNECTING){var d=this;c.then(function(){d.event_source.onopen=function(a){d.readyState=a.readyState,d._trigger.apply(d,["state:"+a.type,a])},d.event_source.onerror=function(a){d.readyState=a.readyState,d._trigger.apply(d,["state:"+a.type,a])},d.event_source.onmessage=function(a){var b=JSON.parse(a.data),c=b.event;delete b.event,d._trigger.apply(d,[c,b])}})}return c},d.Channel.SSE.prototype._trigger=function(a,b){console.log("Trigger: ",a,b),-1===a.indexOf("state:")&&this.callbacks._default&&this.callbacks._default.apply(this,[a,b]),this.callbacks[a]&&this.callbacks[a].apply(this,[b])},d.Channel.SSE.prototype.isConnected=function(){return null!==this.readyState&&this.readyState!==EventSource.CLOSED},d.Channel.SSE.prototype.unsubscribe=function(a){this.callbacks[a]&&(this.callbacks[a]=null)},d.Channel.SSE.prototype.publish=function(a,b){return"undefined"==typeof b&&(b={}),b.client_id=this.client_id,b.event=a,this.collection.create(b)},d.Channel.SSE.prototype.connect=function(){if(null!==this.readyState){var b=when.defer();return b.resolver.resolve(),b.promise}this.readyState=EventSource.CONNECTING,this._trigger.apply(this,["state:connecting"]);var c=this;return this.publish("connected").then(function(b){c.collection.where("updated_at",">",b.updated_at);var d="X-App-Id="+c.collection.client.appId+"&X-App-Key="+c.collection.client.key,e=c.collection.client.auth.getToken();e&&(d+="&X-Auth-Token="+e);var f=c.collection.buildQuery();f.stream={refresh:c.options.refresh_timeout||1,retry:c.options.retry_timeout||1},c.client_id=b.client_id,c.event_source=new EventSource(c.collection.client.url+c.collection.segments+"?"+d+"&"+JSON.stringify(f),{withCredentials:!0}),a.addEventListener("unload",function(){c.disconnect(!0)})},function(a){c.readyState=EventSource.CLOSED,c._trigger.apply(c,["state:error",a])})},d.Channel.SSE.prototype.disconnect=function(a){return this.isConnected()&&(this.close(),this.publish("disconnected",{_sync:"undefined"!=typeof a&&a})),this},d.Channel.SSE.prototype.close=function(){return this.event_source&&this.event_source.close(),this.readyState=EventSource.CLOSED,this},d.Channel.WEBSOCKETS=function(b,c,d){var e=this;if(this.client=b,this.collection=c,this.client_id=null,!d.url){var f="https:"===a.location.protocol?"wss://":"ws://",g=b.url.replace(/(?:https?:)?\/\//,f);g.match(/index\.php/)?g=g.replace("index.php","ws/"):g+="ws/",d.url=g}d.url+=this.collection.name+"?X-App-Id="+this.client.app_id+"&X-App-Key="+this.client.key;var h=this.client.auth.getToken();h&&(d.url+="&X-Auth-Token="+h),ab.debug(d.debug===!0,d.verbose===!0,d.debug===!0),this.queued_subscriptions={},this.on("connected",function(){for(var a in e.queued_subscriptions)e.queued_subscriptions.hasOwnProperty(a)&&e.subscribe(a,e.queued_subscriptions[a]);e.queued_subscriptions=null}),ab.connect(d.url,function(a){e.ws=a,e.client_id=a.sessionid(),e.trigger("connected")},function(a){console.error("Can't connect with WebSocket server: "+d.url,a)},{retryDelay:1e3,maxRetries:10})},d.Channel.WEBSOCKETS.prototype=new d.Events,d.Channel.WEBSOCKETS.prototype.constructor=d.Channel.WEBSOCKETS,d.Channel.WEBSOCKETS.prototype.subscribe=function(a,b){return this.ws?this.ws.subscribe(this.collection.name+"."+a,function(a,c){b(c)}):this.queued_subscriptions[a]=b,this},d.Channel.WEBSOCKETS.prototype.isConnected=function(){return this.ws&&this.ws._websocket_connected},d.Channel.WEBSOCKETS.prototype.unsubscribe=function(a){return this.ws&&this.ws._subscriptions[this.collection.name+"."+a]&&this.ws.unsubscribe(this.collection.name+"."+a),this},d.Channel.WEBSOCKETS.prototype.publish=function(a,b,c){var d=[],e=[];return"undefined"==typeof c&&(c={}),c.exclude&&c.exclude instanceof Array&&(d=c.exclude),c.eligible&&c.eligible instanceof Array&&(e=c.eligible),this.ws.publish(this.collection.name+"."+a,b,d,e),this},d.Channel.WEBSOCKETS.prototype.disconnect=function(){return this.ws.close(),this},d.Channel.WEBSOCKETS.prototype.call=function(a,b){return this.ws.call(a,b),this},d.Channel.WEBSOCKETS.prototype.connect=function(){return this.ws.connect(),this}}(this); \ No newline at end of file +!function(a){"undefined"==typeof a.define&&(a.define=function(b,c){try{delete a.define}catch(d){a.define=void 0}"function"==typeof b?a.when=b():a[b]=c()},a.define.amd={}),function(a){function b(b){return function(e,f){if("string"==typeof f){var g=c.exec(f);if(g)return new Date(f);if(!JSON.parseMsAjaxDate)return f;if(g=d.exec(f)){var h=g[1].split(/[-+,.]/);return new Date(h[0]?+h[0]:0-+h[1])}}return b!==a?b(e,f):f}}if(this.JSON&&!this.JSON.dateParser){var c=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.{0,1}\d*))(?:Z|(\+|-)([\d|:]*))?$/,d=/^\/Date\((d|-|.*)\)[\/|\\]$/;JSON.parseMsAjaxDate=!1,JSON.useDateParser=function(a){"undefined"!=typeof a?JSON._parseSaved&&(JSON.parse=JSON._parseSaved,JSON._parseSaved=null):JSON.parseSaved||(JSON._parseSaved=JSON.parse,JSON.parse=JSON.parseWithDate)},JSON.dateParser=b(),JSON.parseWithDate=function(a,c){var d=JSON._parseSaved?JSON._parseSaved:JSON.parse;try{var e=d(a,b(c));return e}catch(f){throw new Error("JSON content could not be parsed")}},JSON.dateStringToDate=function(a,b){if(b||(b=null),!a)return b;if(a.getTime)return a;('"'===a[0]||"'"===a[0])&&(a=a.substr(1,a.length-2));var e=c.exec(a);if(e)return new Date(a);if(!JSON.parseMsAjaxDate)return b;if(e=d.exec(a)){var f=e[1].split(/[-,.]/);return new Date(+f[0])}return b}}}(),function(a){"use strict";a(function(a){function b(a,b,c,d){return e(a).then(b,c,d)}function c(a){return new d(a,P.PromiseStatus&&P.PromiseStatus())}function d(a,b){function c(){return k?k.inspect():A()}function d(a,b,c,d,e){function f(f){f._when(a,b,c,d,e)}l?l.push(f):B(function(){f(k)})}function e(a){if(l){var c=l;l=T,k=j(h,a),B(function(){b&&o(k,b),i(c,k)})}}function f(a){e(new m(a))}function g(a){if(l){var b=l;B(function(){i(b,new n(a))})}}var h,k,l=[];h=this,this._status=b,this.inspect=c,this._when=d;try{a(e,f,g)}catch(p){f(p)}}function e(a){return a instanceof d?a:f(a)}function f(a){return c(function(b){b(a)})}function g(a){return b(a,function(a){return new m(a)})}function h(){function a(a,c,g){b.resolve=b.resolver.resolve=function(b){return e?f(b):(e=!0,a(b),d)},b.reject=b.resolver.reject=function(a){return e?f(new m(a)):(e=!0,c(a),d)},b.notify=b.resolver.notify=function(a){return g(a),a}}var b,d,e;return b={promise:T,resolve:T,reject:T,notify:T,resolver:{resolve:T,reject:T,notify:T}},b.promise=d=c(a),b}function i(a,b){for(var c=0;c>>0,i=Math.max(0,Math.min(d,o)),k=[],j=o-i+1,l=[],i)for(n=function(a){l.push(a),--j||(m=n=D,e(l))},m=function(a){k.push(a),--i||(m=n=D,c(k))},p=0;o>p;++p)p in a&&b(a[p],h,g,f);else c(k)}return c(h).then(e,f,g)})}function r(a,b,c,d){function e(a){return b?b(a[0]):a[0]}return q(a,1,e,c,d)}function s(a,b,c,d){return w(a,D).then(b,c,d)}function t(){return w(arguments,D)}function u(a){return w(a,y,z)}function v(a,b){return w(a,b)}function w(a,c,e){return b(a,function(a){function f(d,f,g){function h(a,h){b(a,c,e).then(function(a){i[h]=a,--k||d(i)},f,g)}var i,j,k,l;if(k=j=a.length>>>0,i=[],!k)return void d(i);for(l=0;j>l;l++)l in a?h(a[l],l):--k}return new d(f)})}function x(a,c){var d=J(I,arguments,1);return b(a,function(a){var e;return e=a.length,d[0]=function(a,d,f){return b(a,function(a){return b(d,function(b){return c(a,b,f,e)})})},H.apply(a,d)})}function y(a){return{state:"fulfilled",value:a}}function z(a){return{state:"rejected",reason:a}}function A(){return{state:"pending"}}function B(a){1===L.push(a)&&K(C)}function C(){i(L),L=[]}function D(a){return a}function E(a){throw"function"==typeof P.reportUnhandled?P.reportUnhandled():B(function(){throw a}),a}b.promise=c,b.resolve=f,b.reject=g,b.defer=h,b.join=t,b.all=s,b.map=v,b.reduce=x,b.settle=u,b.any=r,b.some=q,b.isPromise=p,b.isPromiseLike=p,F=d.prototype,F.then=function(a,b,c){var e=this;return new d(function(d,f,g){e._when(d,g,a,b,c)},this._status&&this._status.observed())},F["catch"]=F.otherwise=function(a){return this.then(T,a)},F["finally"]=F.ensure=function(a){function b(){return f(a())}return"function"==typeof a?this.then(b,b)["yield"](this):this},F.done=function(a,b){this.then(a,b)["catch"](E)},F["yield"]=function(a){return this.then(function(){return a})},F.tap=function(a){return this.then(a)["yield"](this)},F.spread=function(a){return this.then(function(b){return s(b,function(b){return a.apply(T,b)})})},F.always=function(a,b){return this.then(a,a,b)},G=Object.create||function(a){function b(){}return b.prototype=a,new b},l.prototype=G(F),l.prototype.inspect=function(){return y(this.value)},l.prototype._when=function(a,b,c){try{a("function"==typeof c?c(this.value):this.value)}catch(d){a(new m(d))}},m.prototype=G(F),m.prototype.inspect=function(){return z(this.value)},m.prototype._when=function(a,b,c,d){try{a("function"==typeof d?d(this.value):this)}catch(e){a(new m(e))}},n.prototype=G(F),n.prototype._when=function(a,b,c,d,e){try{b("function"==typeof e?e(this.value):this.value)}catch(f){b(f)}};var F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T;if(R=a,L=[],P="undefined"!=typeof console?console:b,"object"==typeof process&&process.nextTick)K=process.nextTick;else if(S="function"==typeof MutationObserver&&MutationObserver||"function"==typeof WebKitMutationObserver&&WebKitMutationObserver)K=function(a,b,c){var d=a.createElement("div");return new b(c).observe(d,{attributes:!0}),function(){d.setAttribute("x","x")}}(document,S,C);else try{K=R("vertx").runOnLoop||R("vertx").runOnContext}catch(U){Q=setTimeout,K=function(a){Q(a,0)}}return M=Function.prototype,N=M.call,J=M.bind?N.bind(N):function(a,b){return a.apply(b,I.call(arguments,2))},O=[],I=O.slice,H=O.reduce||function(a){var b,c,d,e,f;if(f=0,b=Object(this),e=b.length>>>0,c=arguments,c.length<=1)for(;;){if(f in b){d=b[f++];break}if(++f>=e)throw new TypeError}else d=c[1];for(;e>f;++f)f in b&&(d=a(d,b[f],f,b));return d},b})}("function"==typeof define&&define.amd?define:function(a){module.exports=a(require)}),function(a,b){"object"==typeof exports?module.exports=b():"function"==typeof define&&define.amd?define("uxhr",b):a.uxhr=b()}(this,function(){"use strict";return function(b,c,d){c=c||"",d=d||{};var e=d.complete||function(){},f=d.success||function(){},g=d.error||function(){},h=d.timeout||0,i=d.ontimeout||function(){},j=d.onprogress||function(){},k=d.headers||{},l=d.method||"GET",m=d.sync||!1,n=function(){return 0===b.indexOf("http")&&"undefined"!=typeof XDomainRequest?new XDomainRequest:new XMLHttpRequest}();if(!n)throw new Error("Browser doesn't support XHR");var o="undefined"!=typeof a.FormData;if("string"!=typeof c&&o&&!(c instanceof a.FormData)){var p=[];for(var q in c)p.push(q+"="+c[q]);c=p.join("&")}if("GET"===l&&c&&(b+=b.indexOf("?")>=0?"&"+c:"?"+c),n.open(l,b,!m),m||"ontimeout"in n&&(n.timeout=h,n.ontimeout=i),"onprogress"in n&&(n.onprogress=j),n.onload=function(){e(n.responseText,n.status),f(n.responseText)},n.onerror=function(){e(n.responseText),g(n.responseText,n.status)},"undefined"!=typeof n.setRequestHeader)for(var r in k)n.setRequestHeader(r,k[r]);return n.send("GET"!==l?c:null),n}}),function(){function b(a,b,c){for(var d=(c||0)-1,e=a?a.length:0;++d-1?0:-1:a?0:-1}function d(a){var b=this.cache,c=typeof a;if("boolean"==c||null==a)b[a]=!0;else{"number"!=c&&"string"!=c&&(c="object");var d="number"==c?a:s+a,e=b[c]||(b[c]={});"object"==c?(e[d]||(e[d]=[])).push(a):e[d]=!0}}function e(a){return a.charCodeAt(0)}function f(a,b){for(var c=a.criteria,d=b.criteria,e=-1,f=c.length;++eh||"undefined"==typeof g)return 1;if(h>g||"undefined"==typeof h)return-1}}return a.index-b.index}function g(a){var b=-1,c=a.length,e=a[0],f=a[c/2|0],g=a[c-1];if(e&&"object"==typeof e&&f&&"object"==typeof f&&g&&"object"==typeof g)return!1;var h=j();h["false"]=h["null"]=h["true"]=h.undefined=!1;var i=j();for(i.array=a,i.cache=h,i.push=d;++be?0:e);++d=t&&f===b,j=[];if(i){var k=g(d);k?(f=c,d=k):i=!1}for(;++e-1:void 0});return e.pop(),f.pop(),s&&(k(e),k(f)),g}function cb(a,b,c,d,e){(Zd(b)?Yb:he)(b,function(b,f){var g,h,i=b,j=a[f];if(b&&((h=Zd(b))||ie(b))){for(var k=d.length;k--;)if(g=d[k]==b){j=e[k];break}if(!g){var l;c&&(i=c(j,b),(l="undefined"!=typeof i)&&(j=i)),l||(j=h?Zd(j)?j:[]:ie(j)?j:{}),d.push(b),e.push(j),l||cb(j,b,c,d,e)}}else c&&(i=c(j,b),"undefined"==typeof i&&(i=b)),"undefined"!=typeof i&&(j=i);a[f]=j})}function db(a,b){return a+Ed(Vd()*(b-a+1))}function eb(a,d,e){var f=-1,h=ib(),j=a?a.length:0,m=[],n=!d&&j>=t&&h===b,o=e||n?i():m;if(n){var p=g(o);h=c,o=p}for(;++f3&&"function"==typeof b[c-2])var d=Y(b[--c-1],b[c--],2);else c>2&&"function"==typeof b[c-1]&&(d=b[--c]);for(var e=m(arguments,1,c),f=-1,g=i(),h=i();++fc?Sd(0,f+c):c)||0,Zd(a)?g=e(a,b,c)>-1:"number"==typeof f?g=(Jb(a)?a.indexOf(b,c):e(a,b,c))>-1:he(a,function(a){return++d>=c?!(g=a===b):void 0}),g}function Ub(a,b,c){var e=!0;b=d.createCallback(b,c,3);var f=-1,g=a?a.length:0;if("number"==typeof g)for(;++fg&&(g=j)}else b=null==b&&Jb(a)?e:d.createCallback(b,c,3),Yb(a,function(a,c,d){var e=b(a,c,d);e>f&&(f=e,g=a)});return g}function bc(a,b,c){var f=1/0,g=f;if("function"!=typeof b&&c&&c[b]===a&&(b=null),null==b&&Zd(a))for(var h=-1,i=a.length;++hj&&(g=j)}else b=null==b&&Jb(a)?e:d.createCallback(b,c,3),Yb(a,function(a,c,d){var e=b(a,c,d);f>e&&(f=e,g=a)});return g}function cc(a,b,c,e){if(!a)return c;var f=arguments.length<3;b=d.createCallback(b,e,4);var g=-1,h=a.length;if("number"==typeof h)for(f&&(c=a[++g]);++gd?Sd(0,e+d):d||0}else if(d){var f=Ac(a,c);return a[f]===c?f:-1}return b(a,c,d)}function sc(a,b,c){var e=0,f=a?a.length:0;if("number"!=typeof b&&null!=b){var g=f;for(b=d.createCallback(b,c,3);g--&&b(a[g],g,a);)e++}else e=null==b||c?1:b||e;return m(a,0,Td(Sd(0,f-e),f))}function tc(){for(var a=[],d=-1,e=arguments.length,f=i(),h=ib(),j=h===b,m=i();++d=t&&g(d?a[d]:m)))}var o=a[0],p=-1,q=o?o.length:0,r=[];a:for(;++pc?Sd(0,d+c):Td(c,d-1))+1);d--;)if(a[d]===b)return d;return-1}function wc(a){for(var b=arguments,c=0,d=b.length,e=a?a.length:0;++cf;){var h=f+g>>>1;c(a[h])1?arguments:arguments[0],b=-1,c=a?ac(me(a,"length")):0,d=nd(0>c?0:c);++b2?gb(a,17,m(arguments,2),null,b):gb(a,1,null,null,b)}function Jc(a){for(var b=arguments.length>1?_(arguments,!0,!1,1):ub(a),c=-1,d=b.length;++c2?gb(b,19,m(arguments,2),null,a):gb(b,3,null,null,a)}function Lc(){for(var a=arguments,b=a.length;b--;)if(!Db(a[b]))throw new wd;return function(){for(var b=arguments,c=a.length;c--;)b=[a[c].apply(this,b)];return b[0]}}function Mc(a,b){return b="number"==typeof b?b:+b||a.length,gb(a,4,null,null,null,b)}function Nc(a,b,c){var d,e,f,g,h,i,j,k=0,l=!1,m=!0;if(!Db(a))throw new wd;if(b=Sd(0,b)||0,c===!0){var n=!0;m=!1}else Eb(c)&&(n=c.leading,l="maxWait"in c&&(Sd(b,c.maxWait)||0),m="trailing"in c?c.trailing:m);var p=function(){var c=b-(oe()-g);if(0>=c){e&&Dd(e);var l=j;e=i=j=o,l&&(k=oe(),f=a.apply(h,d),i||e||(d=h=null))}else i=Jd(p,c)},q=function(){i&&Dd(i),e=i=j=o,(m||l!==b)&&(k=oe(),f=a.apply(h,d),i||e||(d=h=null))};return function(){if(d=arguments,g=oe(),h=this,j=m&&(i||!n),l===!1)var c=n&&!i;else{e||n||(k=g);var o=l-(g-k),r=0>=o;r?(e&&(e=Dd(e)),k=g,f=a.apply(h,d)):e||(e=Jd(q,o))}return r&&i?i=Dd(i):i||b===l||(i=Jd(p,b)),c&&(r=!0,f=a.apply(h,d)),!r||i||e||(d=h=null),f}}function Oc(a){if(!Db(a))throw new wd;var b=m(arguments,1);return Jd(function(){a.apply(o,b)},1)}function Pc(a,b){if(!Db(a))throw new wd;var c=m(arguments,2);return Jd(function(){a.apply(o,c)},b)}function Qc(a,b){if(!Db(a))throw new wd;var c=function(){var d=c.cache,e=b?b.apply(this,arguments):s+arguments[0];return Hd.call(d,e)?d[e]:d[e]=a.apply(this,arguments)};return c.cache={},c}function Rc(a){var b,c;if(!Db(a))throw new wd;return function(){return b?c:(b=!0,c=a.apply(this,arguments),a=null,c)}}function Sc(a){return gb(a,16,m(arguments,1))}function Tc(a){return gb(a,32,null,m(arguments,1))}function Uc(a,b,c){var d=!0,e=!0;if(!Db(a))throw new wd;return c===!1?d=!1:Eb(c)&&(d="leading"in c?c.leading:d,e="trailing"in c?c.trailing:e),T.leading=d,T.maxWait=b,T.trailing=e,Nc(a,b,T)}function Vc(a,b){return gb(b,16,[a])}function Wc(a){return function(){return a}}function Xc(a,b,c){var d=typeof a;if(null==a||"function"==d)return Y(a,b,c);if("object"!=d)return bd(a);var e=_d(a),f=e[0],g=a[f];return 1!=e.length||g!==g||Eb(g)?function(b){for(var c=e.length,d=!1;c--&&(d=bb(b[e[c]],a[e[c]],null,!0)););return d}:function(a){var b=a[f];return g===b&&(0!==g||1/g==1/b)}}function Yc(a){return null==a?"":vd(a).replace(de,hb)}function Zc(a){return a}function $c(a,b,c){var e=!0,f=b&&ub(b);b&&(c||f.length)||(null==c&&(c=b),g=p,b=a,a=d,f=ub(b)),c===!1?e=!1:Eb(c)&&"chain"in c&&(e=c.chain);var g=a,h=Db(g);Yb(f,function(c){var d=a[c]=b[c];h&&(g.prototype[c]=function(){var b=this.__chain__,c=this.__wrapped__,f=[c];Id.apply(f,arguments);var h=d.apply(a,f);if(e||b){if(c===h&&Eb(h))return this;h=new g(h),h.__chain__=b}return h})})}function _c(){return a._=zd,this}function ad(){}function bd(a){return function(b){return b[a]}}function cd(a,b,c){var d=null==a,e=null==b;if(null==c&&("boolean"==typeof a&&e?(c=a,a=1):e||"boolean"!=typeof b||(c=b,e=!0)),d&&e&&(b=1),a=+a||0,e?(b=a,a=0):b=+b||0,c||a%1||b%1){var f=Vd();return Td(a+f*(b-a+parseFloat("1e-"+((f+"").length-1))),b)}return db(a,b)}function dd(a,b){if(a){var c=a[b];return Db(c)?a[b]():c}}function ed(a,b,c){var e=d.templateSettings;a=vd(a||""),c=fe({},c,e);var f,g=fe({},c.imports,e.imports),i=_d(g),j=Rb(g),k=0,l=c.interpolate||E,m="__p += '",n=ud((c.escape||E).source+"|"+l.source+"|"+(l===C?z:E).source+"|"+(c.evaluate||E).source+"|$","g");a.replace(n,function(b,c,d,e,g,i){return d||(d=e),m+=a.slice(k,i).replace(G,h),c&&(m+="' +\n__e("+c+") +\n'"),g&&(f=!0,m+="';\n"+g+";\n__p += '"),d&&(m+="' +\n((__t = ("+d+")) == null ? '' : __t) +\n'"),k=i+b.length,b}),m+="';\n";var p=c.variable,q=p;q||(p="obj",m="with ("+p+") {\n"+m+"\n}\n"),m=(f?m.replace(w,""):m).replace(x,"$1").replace(y,"$1;"),m="function("+p+") {\n"+(q?"":p+" || ("+p+" = {});\n")+"var __t, __p = '', __e = _.escape"+(f?", __j = Array.prototype.join;\nfunction print() { __p += __j.call(arguments, '') }\n":";\n")+m+"return __p\n}";var r="\n/*\n//# sourceURL="+(c.sourceURL||"/lodash/template/source["+I++ +"]")+"\n*/";try{var s=qd(i,"return "+m+r).apply(o,j)}catch(t){throw t.source=m,t}return b?s(b):(s.source=m,s)}function fd(a,b,c){a=(a=+a)>-1?a:0;var d=-1,e=nd(a);for(b=Y(b,c,1);++d/g,evaluate:/<%([\s\S]+?)%>/g,interpolate:C,variable:"",imports:{_:d}},Nd||(W=function(){function b(){}return function(c){if(Eb(c)){b.prototype=c;var d=new b;b.prototype=null}return d||a.Object()}}());var Yd=Md?function(a,b){U.value=b,Md(a,"__bindData__",U)}:ad,Zd=Od||function(a){return a&&"object"==typeof a&&"number"==typeof a.length&&Ad.call(a)==K||!1},$d=function(a){var b,c=a,d=[];if(!c)return d;if(!V[typeof a])return d;for(b in c)Hd.call(c,b)&&d.push(b);return d},_d=Rd?function(a){return Eb(a)?Rd(a):[]}:$d,ae={"&":"&","<":"<",">":">",'"':""","'":"'"},be=wb(ae),ce=ud("("+_d(be).join("|")+")","g"),de=ud("["+_d(ae).join("")+"]","g"),ee=function(a,b,c){var d,e=a,f=e;if(!e)return f;var g=arguments,h=0,i="number"==typeof c?2:g.length;if(i>3&&"function"==typeof g[i-2])var j=Y(g[--i-1],g[i--],2);else i>2&&"function"==typeof g[i-1]&&(j=g[--i]);for(;++h/g,D=RegExp("^["+v+"]*0+(?=.$)"),E=/($^)/,F=/\bthis\b/,G=/['\n\r\t\u2028\u2029\\]/g,H=["Array","Boolean","Date","Function","Math","Number","Object","RegExp","String","_","attachEvent","clearTimeout","isFinite","isNaN","parseInt","setTimeout"],I=0,J="[object Arguments]",K="[object Array]",L="[object Boolean]",M="[object Date]",N="[object Function]",O="[object Number]",P="[object Object]",Q="[object RegExp]",R="[object String]",S={};S[N]=!1,S[J]=S[K]=S[L]=S[M]=S[O]=S[P]=S[Q]=S[R]=!0;var T={leading:!1,maxWait:0,trailing:!1},U={configurable:!1,enumerable:!1,value:null,writable:!1},V={"boolean":!1,"function":!0,object:!0,number:!1,string:!1,undefined:!1},W={"\\":"\\","'":"'","\n":"n","\r":"r"," ":"t","\u2028":"u2028","\u2029":"u2029"},X=V[typeof a]&&a||this,Y=V[typeof exports]&&exports&&!exports.nodeType&&exports,Z=V[typeof module]&&module&&!module.nodeType&&module,$=Z&&Z.exports===Y&&Y,_=V[typeof global]&&global;!_||_.global!==_&&_.window!==_||(X=_);var ab=n();"function"==typeof define&&"object"==typeof define.amd&&define.amd?(X._=ab,define(function(){return ab})):Y&&Z?$?(Z.exports=ab)._=ab:Y._=ab:X._=ab}.call(this);var b={VERSION:"0.3.4",defaults:{perPage:50}};a.Hook=b,b.Client=function(c){c||(c={}),this.endpoint=c.endpoint||c.url||a.location.origin,this.app_id=c.app_id||c.appId||"",this.key=c.key||"",this.options="undefined"!=typeof c.options?c.options:{},this.endpoint.lastIndexOf("/")!=this.endpoint.length-1&&(this.endpoint+="/"),this.keys=new b.KeyValues(this),this.auth=new b.Auth(this),this.system=new b.System(this),b.Plugin.Manager.setup(this)},b.Client.prototype.collection=function(a){return new b.Collection(this,a)},b.Client.prototype.channel=function(a,c){"undefined"==typeof c&&(c={});var d=this.collection(a);return d.segments=d.segments.replace("collection/","channels/"),c.transport||(c.transport="sse"),c.transport=c.transport.toUpperCase(),new b.Channel[c.transport](this,d,c)},b.Client.prototype.url=function(a,b){var c="";return b&&(c="&"+this.serialize(b)),this.endpoint+a+this._getCredentialsParams()+c},b.Client.prototype.post=function(a,b){return"undefined"==typeof b&&(b={}),this.request(a,"POST",b)},b.Client.prototype.get=function(a,b){return this.request(a,"GET",b)},b.Client.prototype.put=function(a,b){return this.request(a,"PUT",b)},b.Client.prototype.remove=function(a,b){return this.request(a,"DELETE",b)},b.Client.prototype.request=function(a,b,c){var d,e,f=when.defer(),g=!1;c&&c._sync&&(delete c._sync,g=!0),d=this.getPayload(b,c),e=this.getHeaders(),d instanceof FormData||(e["Content-Type"]="application/json"),"GET"!==b&&"POST"!==b&&this.options.method_override&&(e["X-HTTP-Method-Override"]=b,b="POST"),"undefined"!=typeof XDomainRequest&&(a+=this._getCredentialsParams()+"&r="+Math.floor(1e3*Math.random()));var h=f.promise.xhr=uxhr(this.endpoint+a,d,{method:b,headers:e,sync:g,success:function(a){var b,c=null,d=h.getAllResponseHeaders&&h.getAllResponseHeaders()||"";try{c=JSON.parseWithDate(a)}catch(e){}c===!1||null===c||c.error?(c&&c.error&&console.error(c.error),f.resolver.reject(c)):(b=d.match(/x-total-count: ([^\n]+)/i),b&&(c.total=parseInt(b[1])),f.resolver.resolve(c))},error:function(a){var b=null;try{b=JSON.parseWithDate(a)}catch(c){}console.log("Error: ",b||"Invalid JSON response."),f.resolver.reject(b)}});return f.promise},b.Client.prototype.getHeaders=function(){var a,b={"X-App-Id":this.app_id,"X-App-Key":this.key},a=this.auth.getToken();return a&&(b["X-Auth-Token"]=a),b},b.Client.prototype.getPayload=function(a,b){var c=null;if(b){if(b instanceof FormData)c=b;else if("GET"!==a){var d=new FormData,e=!1,f=function(a){var b=a.shift();return a.length>0?b+"["+f(a)+"]":b},g=function(a,b,c){var d,h,i,j=!1;for(d in b)if(h=b[d],i=null,"undefined"!=typeof h&&null!==h){if("boolean"==typeof h||"number"==typeof h||"string"==typeof h)h=h.toString();else if(h instanceof HTMLInputElement&&h.files&&h.files.length>0)i=h.files[0].name,h=h.files[0],e=!0,j=!0;else if(h instanceof HTMLInputElement)h=h.value;else if(h instanceof HTMLCanvasElement)h=dataURLtoBlob(h.toDataURL()),e=!0,i="canvas.png";else if("undefined"!=typeof Blob&&h instanceof Blob)e=!0,i="blob."+h.type.match(/\/(.*)/)[1];else if("object"==typeof h){g(a,h,c.concat(d));continue}if(!(h instanceof Array)){var k=j?d:f(c.concat(d));if("string"==typeof h)a.append(k,h);else try{a.append(k,h,i||"file")}catch(l){}}}};g(d,b,[]),e&&(c=d)}if(c=c||JSON.stringify(b,function(a,b){return this[a]instanceof Date?Math.round(this[a].getTime()/1e3):b}),"{}"==c)return null;"GET"===a&&"string"==typeof c&&(c=encodeURIComponent(c))}return c},b.Client.prototype._getCredentialsParams=function(){var a="?X-App-Id="+this.app_id+"&X-App-Key="+this.key,b=this.auth.getToken();return b&&(a+="&X-Auth-Token="+b),a},b.Client.prototype.serialize=function(a,b){var c=[];for(var d in a)if(a.hasOwnProperty(d)){var e=b?b+"["+d+"]":d,f=a[d];c.push("object"==typeof f?this.serialize(f,e):encodeURIComponent(e)+"="+encodeURIComponent(f))}return c.join("&")},b.Events=function(){this._events={}},b.Events.prototype.on=function(a,b,c){this._events[a]||(this._events[a]=[]),this._events[a].push({callback:b,context:c||this})},b.Events.prototype.trigger=function(a){var b,c=Array.prototype.slice.call(arguments,1);if(this._events[a])for(var d=0,e=this._events[a].length;e>d;d++)b=this._events[a][d],b.callback.apply(b.context||this.client,c)},b.Iterable=function(){},b.Iterable.prototype={each:function(a){return this._iterate("each",a)},find:function(a){return this._iterate("find",a)},filter:function(a){return this._iterate("filter",a)},max:function(a){return this._iterate("max",a)},min:function(a){return this._iterate("min",a)},every:function(a){return this._iterate("every",a)},reject:function(a,b){return this._iterate("reject",a,b)},groupBy:function(a,b){return this._iterate("groupBy",a,b)},_iterate:function(a,b,c){var d=when.defer();return this.then(function(e){var f=_[a].call(_,e,b,c);d.resolver.resolve(f)}).otherwise(function(a){d.resolver.reject(a)}),d.promise}},"undefined"==typeof a.FormData&&(a.FormData=function(){this.append=function(){}}),a.location.origin||(a.location.origin=a.location.protocol+"//"+a.location.hostname+(a.location.port?":"+a.location.port:"")),b.Plugin={},b.Plugin.Manager={plugins:[]},b.Plugin.Manager.register=function(a,b){this.plugins.push({path:a,klass:b})},b.Plugin.Manager.setup=function(a){for(var b=0,c=this.plugins.length;c>b;b++)a[this.plugins[b].path]=new this.plugins[b].klass(a)},b.Auth=function(c){this.client=c,this.currentUser=null;var d=new Date,e=new Date(a.localStorage.getItem(this.client.app_id+"-"+b.Auth.AUTH_TOKEN_EXPIRATION)),f=a.localStorage.getItem(this.client.app_id+"-"+b.Auth.AUTH_DATA_KEY);f&&d.getTime()1?b.then.apply(b,Array.prototype.slice.call(arguments,1)):b},b.Collection.prototype.join=function(){return this.options["with"]=arguments,this},b.Collection.prototype.distinct=function(){return this.options.distinct=!0,this},b.Collection.prototype.group=function(){return this._group=arguments,this},b.Collection.prototype.count=function(a){a="undefined"==typeof a?"*":a,this.options.aggregation={method:"count",field:a};var b=this.get();return arguments.length>0&&b.then.apply(b,arguments),b},b.Collection.prototype.max=function(a){this.options.aggregation={method:"max",field:a};var b=this.get();return arguments.length>1&&b.then.apply(b,Array.prototype.slice.call(arguments,1)),b},b.Collection.prototype.min=function(a){this.options.aggregation={method:"min",field:a};var b=this.get();return arguments.length>1&&b.then.apply(b,Array.prototype.slice.call(arguments,1)),b},b.Collection.prototype.avg=function(a){this.options.aggregation={method:"avg",field:a};var b=this.get();return arguments.length>1&&b.then.apply(b,Array.prototype.slice.call(arguments,1)),b},b.Collection.prototype.sum=function(a){this.options.aggregation={method:"sum",field:a};var b=this.get();return arguments.length>1&&b.then.apply(b,Array.prototype.slice.call(arguments,1)),b},b.Collection.prototype.first=function(){this.options.first=1;var a=this.get();return a.then.apply(a,arguments),a},b.Collection.prototype.firstOrCreate=function(a){return this.options.first=1,this.options.data=a,this.client.post(this.segments,this.buildQuery())},b.Collection.prototype.then=function(){var a=this.get();return a.then.apply(a,arguments),a},b.Collection.prototype.debug=function(a){return a="undefined"==typeof a?"log":a,this.then(console[a].bind(console))},b.Collection.prototype.reset=function(){return this.options={},this.wheres=[],this.ordering=[],this._group=[],this._limit=null,this._offset=null,this._remember=null,this},b.Collection.prototype.sort=function(a,b){return b?"number"==typeof b&&(b=-1===parseInt(b,10)?"desc":"asc"):b="asc",this.ordering.push([a,b]),this},b.Collection.prototype.limit=function(a){return this._limit=a,this},b.Collection.prototype.offset=function(a){return this._offset=a,this},b.Collection.prototype.remember=function(a){return this._remember=a,this},b.Collection.prototype.channel=function(){throw new Error("Not implemented.")},b.Collection.prototype.drop=function(){return this.client.remove(this.segments)},b.Collection.prototype.remove=function(a){var b=this.segments;return"undefined"!=typeof a&&(b+="/"+a),this.client.remove(b,this.buildQuery())},b.Collection.prototype.update=function(a,b){return this.client.post(this.segments+"/"+a,b)},b.Collection.prototype.increment=function(a,b){this.options.operation={method:"increment",field:a,value:b||1};var c=this.client.put(this.segments,this.buildQuery());return arguments.length>0&&c.then.apply(c,arguments),c},b.Collection.prototype.decrement=function(a,b){this.options.operation={method:"decrement",field:a,value:b||1};var c=this.client.put(this.segments,this.buildQuery());return arguments.length>0&&c.then.apply(c,arguments),c},b.Collection.prototype.updateAll=function(a){return this.options.data=a,this.client.put(this.segments,this.buildQuery())},b.Collection.prototype.addWhere=function(a,b,c,d){return this.wheres.push([a,b.toLowerCase(),c,d]),this},b.Collection.prototype._validateName=function(a){var b=/^[a-z_\/0-9]+$/;if(!b.test(a))throw new Error("Invalid name: "+a);return a},b.Collection.prototype.buildQuery=function(){var a={};null!==this._limit&&(a.limit=this._limit),null!==this._offset&&(a.offset=this._offset),null!==this._remember&&(a.remember=this._remember),this.wheres.length>0&&(a.q=this.wheres),this.ordering.length>0&&(a.s=this.ordering),this._group.length>0&&(a.g=this._group);var b,c={paginate:"p",first:"f",aggregation:"aggr",operation:"op",data:"data","with":"with",select:"select",distinct:"distinct"};for(b in c)this.options[b]&&(a[c[b]]=this.options[b]);return this.reset(),a},b.Collection.prototype.clone=function(){var a=this.client.collection(this.name);return a.options=_.clone(this.options),a.wheres=_.clone(this.wheres),a.ordering=_.clone(this.ordering),a._group=_.clone(this._group),a._limit=_.clone(this._limit),a._offset=_.clone(this._offset),a._remember=_.clone(this._remember),a},b.CollectionItem=function(){},b.KeyValues=function(a){this.client=a},b.KeyValues.prototype.get=function(a,b){var c=this.client.get("key/"+a);return b&&c.then.apply(c,[b]),c},b.KeyValues.prototype.set=function(a,b){return this.client.post("key/"+a,{value:b})},b.Model=function(){},b.Pagination=function(a){this.fetching=!0,this.collection=a},b.Pagination.prototype._fetchComplete=function(a){this.fetching=!1,this.total=a.total,this.per_page=a.per_page,this.current_page=a.current_page,this.last_page=a.last_page,this.from=a.from,this.to=a.to,this.items=a.data},b.Pagination.prototype.hasNext=function(){return this.current_page0&&a.then.apply(a,arguments),a},b.Channel.SSE=function(a,b,c){this.collection=b,this.client_id=null,this.callbacks={},this.options=c||{},this.readyState=null},b.Channel.SSE.prototype.subscribe=function(a,b){"undefined"==typeof b&&(b=a,a="_default"),this.callbacks[a]=b;var c=this.connect();if(this.readyState===EventSource.CONNECTING){var d=this;c.then(function(){d.event_source.onopen=function(a){d.readyState=a.readyState,d._trigger.apply(d,["state:"+a.type,a])},d.event_source.onerror=function(a){d.readyState=a.readyState,d._trigger.apply(d,["state:"+a.type,a])},d.event_source.onmessage=function(a){var b=JSON.parse(a.data),c=b.event;delete b.event,d._trigger.apply(d,[c,b])}})}return c},b.Channel.SSE.prototype._trigger=function(a,b){console.log("Trigger: ",a,b),-1===a.indexOf("state:")&&this.callbacks._default&&this.callbacks._default.apply(this,[a,b]),this.callbacks[a]&&this.callbacks[a].apply(this,[b])},b.Channel.SSE.prototype.isConnected=function(){return null!==this.readyState&&this.readyState!==EventSource.CLOSED},b.Channel.SSE.prototype.unsubscribe=function(a){this.callbacks[a]&&(this.callbacks[a]=null)},b.Channel.SSE.prototype.publish=function(a,b){return"undefined"==typeof b&&(b={}),b.client_id=this.client_id,b.event=a,this.collection.create(b)},b.Channel.SSE.prototype.connect=function(){if(null!==this.readyState){var b=when.defer();return b.resolver.resolve(),b.promise}this.readyState=EventSource.CONNECTING,this._trigger.apply(this,["state:connecting"]);var c=this;return this.publish("connected").then(function(b){c.collection.where("updated_at",">",b.updated_at);var d="X-App-Id="+c.collection.client.appId+"&X-App-Key="+c.collection.client.key,e=c.collection.client.auth.getToken();e&&(d+="&X-Auth-Token="+e);var f=c.collection.buildQuery();f.stream={refresh:c.options.refresh_timeout||1,retry:c.options.retry_timeout||1},c.client_id=b.client_id,c.event_source=new EventSource(c.collection.client.url+c.collection.segments+"?"+d+"&"+JSON.stringify(f),{withCredentials:!0}),a.addEventListener("unload",function(){c.disconnect(!0)})},function(a){c.readyState=EventSource.CLOSED,c._trigger.apply(c,["state:error",a])})},b.Channel.SSE.prototype.disconnect=function(a){return this.isConnected()&&(this.close(),this.publish("disconnected",{_sync:"undefined"!=typeof a&&a})),this},b.Channel.SSE.prototype.close=function(){return this.event_source&&this.event_source.close(),this.readyState=EventSource.CLOSED,this},b.Channel.WEBSOCKETS=function(b,c,d){var e=this;if(this.client=b,this.collection=c,this.client_id=null,!d.url){var f="https:"===a.location.protocol?"wss://":"ws://",g=b.url.replace(/(?:https?:)?\/\//,f);g.match(/index\.php/)?g=g.replace("index.php","ws/"):g+="ws/",d.url=g}d.url+=this.collection.name+"?X-App-Id="+this.client.app_id+"&X-App-Key="+this.client.key;var h=this.client.auth.getToken();h&&(d.url+="&X-Auth-Token="+h),ab.debug(d.debug===!0,d.verbose===!0,d.debug===!0),this.queued_subscriptions={},this.on("connected",function(){for(var a in e.queued_subscriptions)e.queued_subscriptions.hasOwnProperty(a)&&e.subscribe(a,e.queued_subscriptions[a]);e.queued_subscriptions=null}),ab.connect(d.url,function(a){e.ws=a,e.client_id=a.sessionid(),e.trigger("connected")},function(a){console.error("Can't connect with WebSocket server: "+d.url,a)},{retryDelay:1e3,maxRetries:10})},b.Channel.WEBSOCKETS.prototype=new b.Events,b.Channel.WEBSOCKETS.prototype.constructor=b.Channel.WEBSOCKETS,b.Channel.WEBSOCKETS.prototype.subscribe=function(a,b){return this.ws?this.ws.subscribe(this.collection.name+"."+a,function(a,c){b(c)}):this.queued_subscriptions[a]=b,this},b.Channel.WEBSOCKETS.prototype.isConnected=function(){return this.ws&&this.ws._websocket_connected},b.Channel.WEBSOCKETS.prototype.unsubscribe=function(a){return this.ws&&this.ws._subscriptions[this.collection.name+"."+a]&&this.ws.unsubscribe(this.collection.name+"."+a),this},b.Channel.WEBSOCKETS.prototype.publish=function(a,b,c){var d=[],e=[];return"undefined"==typeof c&&(c={}),c.exclude&&c.exclude instanceof Array&&(d=c.exclude),c.eligible&&c.eligible instanceof Array&&(e=c.eligible),this.ws.publish(this.collection.name+"."+a,b,d,e),this},b.Channel.WEBSOCKETS.prototype.disconnect=function(){return this.ws.close(),this},b.Channel.WEBSOCKETS.prototype.call=function(a,b){return this.ws.call(a,b),this},b.Channel.WEBSOCKETS.prototype.connect=function(){return this.ws.connect(),this}}(this); \ No newline at end of file diff --git a/grunt/concat.yaml b/grunt/concat.yaml index 90fac44..e95ccff 100644 --- a/grunt/concat.yaml +++ b/grunt/concat.yaml @@ -17,9 +17,9 @@ javascripts: - 'bower_components/uxhr/uxhr.js' - 'bower_components/lodash/dist/lodash.js' - - 'bower_components/blueimp-canvas-to-blob/js/canvas-to-blob.min.js' - - 'bower_components/eventsource/eventsource.js' - - 'bower_components/AutobahnJS/autobahn/autobahn.js' + # - 'bower_components/blueimp-canvas-to-blob/js/canvas-to-blob.min.js' + # - 'bower_components/eventsource/eventsource.js' + # - 'bower_components/AutobahnJS/autobahn/autobahn.js' - 'src/core/*.js' - 'src/*.js' diff --git a/package.json b/package.json index 9681bb8..1c41d00 100644 --- a/package.json +++ b/package.json @@ -2,7 +2,7 @@ "name": "hook-javascript", "title": "hook javascript client", "description": "hook javascript client", - "version": "0.3.3", + "version": "0.3.4", "homepage": "http://github.com/doubleleft/hook-javascript", "main": "dist/hook.js", "authors": [{ diff --git a/src/core/api.js b/src/core/api.js index ddaadab..c9ae280 100644 --- a/src/core/api.js +++ b/src/core/api.js @@ -2,7 +2,7 @@ * @module Hook */ var Hook = { - VERSION: "0.1.0", + VERSION: "0.3.4", defaults: { perPage: 50 } diff --git a/src/core/client.js b/src/core/client.js index 207bf4e..d0eb836 100644 --- a/src/core/client.js +++ b/src/core/client.js @@ -277,55 +277,72 @@ Hook.Client.prototype.getPayload = function(method, data) { if (data instanceof FormData){ payload = data; } else if (method !== "GET") { - var field, value, filename, - formdata = new FormData(), + var formdata = new FormData(), worth = false; - for (field in data) { - value = data[field]; - filename = null; + var getFieldName = function(nested) { + var name = nested.shift(); + return (nested.length > 0) ? name + '[' + getFieldName(nested) + ']' : name; + }; - if (typeof(value)==='undefined' || value === null) { - continue; + var appendFormdataRecursively = function(formdata, data, previous) { + var field, value, filename, isFile = false; - } else if (typeof(value)==='boolean' || typeof(value)==='number' || typeof(value)==="string") { - value = value.toString(); + for (field in data) { + value = data[field]; + filename = null; - // IE8 can't compare instanceof String with HTMLInputElement. - } else if (value instanceof HTMLInputElement && value.files && value.files.length > 0) { - filename = value.files[0].name; - value = value.files[0]; - worth = true; + if (typeof(value)==='undefined' || value === null) { + continue; - } else if (value instanceof HTMLInputElement) { - value = value.value; + } else if (typeof(value)==='boolean' || typeof(value)==='number' || typeof(value)==="string") { + value = value.toString(); - } else if (value instanceof HTMLCanvasElement) { - value = dataURLtoBlob(value.toDataURL()); - worth = true; - filename = 'canvas.png'; + // IE8 can't compare instanceof String with HTMLInputElement. + } else if (value instanceof HTMLInputElement && value.files && value.files.length > 0) { + filename = value.files[0].name; + value = value.files[0]; + worth = true; + isFile = true; - } else if (typeof(Blob) !== "undefined" && value instanceof Blob) { - worth = true; - filename = 'blob.' + value.type.match(/\/(.*)/)[1]; // get extension from blob mime/type - } + } else if (value instanceof HTMLInputElement) { + value = value.value; + + } else if (value instanceof HTMLCanvasElement) { + value = dataURLtoBlob(value.toDataURL()); + worth = true; + filename = 'canvas.png'; - // - // Consider serialization to keep data types here: http://phpjs.org/functions/serialize/ - // - if (!(value instanceof Array)) { // fixme - if (typeof(value)==="string") { - formdata.append(field, value); - } else { - try { - formdata.append(field, value, filename || "file"); - } catch (e) { - // TODO: - // Node.js (CLI console) throws exception here + } else if (typeof(Blob) !== "undefined" && value instanceof Blob) { + worth = true; + filename = 'blob.' + value.type.match(/\/(.*)/)[1]; // get extension from blob mime/type + + } else if (typeof(value)==="object") { + appendFormdataRecursively(formdata, value, previous.concat(field)); + continue; + } + + // + // Consider serialization to keep data types here: http://phpjs.org/functions/serialize/ + // + if (!(value instanceof Array)) { // fixme + var fieldname = (isFile) ? field : getFieldName(previous.concat(field)); + + if (typeof(value)==="string") { + formdata.append(fieldname, value); + } else { + try { + formdata.append(fieldname, value, filename || "file"); + } catch (e) { + // TODO: + // Node.js (CLI console) throws exception here + } } } } - } + }; + + appendFormdataRecursively(formdata, data, []); if (worth) { payload = formdata; diff --git a/tests/api.js b/tests/api.js index a6e084a..313d687 100644 --- a/tests/api.js +++ b/tests/api.js @@ -1,13 +1,4 @@ test("API", function() { - window.ascii_rand = function(length) { - var str = ""; - for (var i=0; i < length; i++) { - var charCode = 97 + Math.floor((Math.random() * 25)); - str += String.fromCharCode(charCode); - } - return str; // + ((new Date()).getTime().toString().substr(8)) - } - ok( client.endpoint == "http://hook.dev/index.php/", "endpoint OK"); ok( client.app_id == appData.keys[1].app_id, "'app_id' OK"); ok( client.key == appData.keys[1].key, "'secret' OK"); diff --git a/tests/app.json b/tests/app.json index 8464643..b08137d 100644 --- a/tests/app.json +++ b/tests/app.json @@ -1 +1 @@ -{"name":"travis","secret":"c7fd74f3e41dc69ea9b4a5b298b8a33c","updated_at":"2014-11-04T00:09:52-02:00","created_at":"2014-11-04T00:09:52-02:00","_id":131,"keys":[{"_id":201,"app_id":131,"key":"77e1dc3b407e34ce53c4d92112a70f00","admin":0,"deleted_at":null,"created_at":"2014-11-04T00:09:52-02:00","updated_at":"2014-11-04T00:09:52-02:00","type":"cli"},{"_id":202,"app_id":131,"key":"8922af1fe7e79a43813078aaa1d362cb","admin":0,"deleted_at":null,"created_at":"2014-11-04T00:09:52-02:00","updated_at":"2014-11-04T00:09:52-02:00","type":"browser"},{"_id":203,"app_id":131,"key":"ad4f042bc8181381bf550139ff6a5637","admin":0,"deleted_at":null,"created_at":"2014-11-04T00:09:52-02:00","updated_at":"2014-11-04T00:09:52-02:00","type":"device"},{"_id":204,"app_id":131,"key":"210dca4580bac2dfb548b5ff65371707","admin":0,"deleted_at":null,"created_at":"2014-11-04T00:09:52-02:00","updated_at":"2014-11-04T00:09:52-02:00","type":"server"}]} +{"name":"hook-javascript-test","secret":"9be410a9a5f2c7ff545ce537d5c299c3","updated_at":"2015-05-22T17:02:01-03:00","created_at":"2015-05-22T17:02:01-03:00","_id":39,"keys":[{"_id":"153","app_id":"39","key":"a62f11923c2f1adc2b9f85dc4f78c57f","type":"cli","deleted_at":null,"created_at":"2015-05-22T17:02:01-03:00","updated_at":"2015-05-22T17:02:01-03:00"},{"_id":"154","app_id":"39","key":"67b6921d8ceb4eb1d7263e9c7df529ca","type":"browser","deleted_at":null,"created_at":"2015-05-22T17:02:01-03:00","updated_at":"2015-05-22T17:02:01-03:00"},{"_id":"155","app_id":"39","key":"90dc29fe7f49785d816ea4fbf829886b","type":"device","deleted_at":null,"created_at":"2015-05-22T17:02:01-03:00","updated_at":"2015-05-22T17:02:01-03:00"},{"_id":"156","app_id":"39","key":"cfee5fb8b7f8301bb3830d54a008c320","type":"server","deleted_at":null,"created_at":"2015-05-22T17:02:01-03:00","updated_at":"2015-05-22T17:02:01-03:00"}]} \ No newline at end of file diff --git a/tests/collections/basic.js b/tests/collections/basic.js index a182094..561ba39 100644 --- a/tests/collections/basic.js +++ b/tests/collections/basic.js @@ -42,3 +42,25 @@ asyncTest("Collections: listing without where", function() { }); }); + +asyncTest("Collections: firstOrCreate", function() { + // + // Get without where + // + client.collection('posts').firstOrCreate({name: "First or create"}).then(function(response) { + ok(response.name === "First or create", "firstOrCreate should create an entry"); + + var previousId = response._id; + + client.collection('posts').firstOrCreate({name: "First or create"}).then(function(response) { + ok(response._id === previousId, "firstOrCreate should find already created item"); + }).otherwise(function(response) { + ok(false, "couldn't find existing item"); + }).done(function() { + start(); + }); + + }).otherwise(function(response) { + ok(false, "couldn't create"); + }); +}); diff --git a/tests/collections/upload.js b/tests/collections/upload_base64.js similarity index 100% rename from tests/collections/upload.js rename to tests/collections/upload_base64.js diff --git a/tests/collections/upload_input.js b/tests/collections/upload_input.js new file mode 100644 index 0000000..ff9b68d --- /dev/null +++ b/tests/collections/upload_input.js @@ -0,0 +1,27 @@ +asyncTest("Files: uploading with input[type=file]", function() { + var attached_files = client.collection('attached_files'); + + $('body').append($('')); + $('body').append($('')); + + $('body').append($('')); + + $('#letstest').click(function() { + attached_files.create({ + file_1: $('#upload_input_file_1').get(0), + file_2: $('#upload_input_file_2').get(0) + }).then(function(data) { + ok(data.file_1.match(/\.pdf/)[0] === ".pdf"); + ok(data.file_1_id >= 0, "file_1_id should be present"); + + ok(data.file_2.match(/\.pdf/)[0] === ".pdf"); + ok(data.file_2_id >= 0, "file_1_id should be present"); + + }).done(function() { + start(); + + }); + }) + +}); + diff --git a/tests/index.html b/tests/index.html index c21340b..e6a8ba7 100644 --- a/tests/index.html +++ b/tests/index.html @@ -9,6 +9,15 @@ - + +