From 00eaf5f60ae99e702e79b1fd1c6e41ba947da257 Mon Sep 17 00:00:00 2001 From: Ian Jennings Date: Wed, 8 Nov 2017 20:06:04 -0800 Subject: [PATCH] build 0.8.4 (#215) --- dist/chat-engine.js | 92 +++++++++++++++++----------------- dist/chat-engine.min.js | 2 +- dist/stats.json | 2 +- package.json | 2 +- setup/lib/chat-engine-setup.js | 2 +- setup/lib/stats.json | 2 +- 6 files changed, 51 insertions(+), 51 deletions(-) diff --git a/dist/chat-engine.js b/dist/chat-engine.js index 5c1c7148..8a2eb6a8 100644 --- a/dist/chat-engine.js +++ b/dist/chat-engine.js @@ -677,55 +677,55 @@ module.exports = defaults; /* 3 */ /***/ (function(module, exports) { -var g; - -// This works in non-strict mode -g = (function() { - return this; -})(); - -try { - // This works if eval is allowed (see CSP) - g = g || Function("return this")() || (1,eval)("this"); -} catch(e) { - // This works if the window reference is available - if(typeof window === "object") - g = window; -} - -// g can still be undefined, but nothing to do about it... -// We return undefined, instead of nothing here, so it's -// easier to handle this case. if(!global) { ...} - -module.exports = g; +var g; + +// This works in non-strict mode +g = (function() { + return this; +})(); + +try { + // This works if eval is allowed (see CSP) + g = g || Function("return this")() || (1,eval)("this"); +} catch(e) { + // This works if the window reference is available + if(typeof window === "object") + g = window; +} + +// g can still be undefined, but nothing to do about it... +// We return undefined, instead of nothing here, so it's +// easier to handle this case. if(!global) { ...} + +module.exports = g; /***/ }), /* 4 */ /***/ (function(module, exports) { -module.exports = function(module) { - if(!module.webpackPolyfill) { - module.deprecate = function() {}; - module.paths = []; - // module.parent = undefined by default - if(!module.children) module.children = []; - Object.defineProperty(module, "loaded", { - enumerable: true, - get: function() { - return module.l; - } - }); - Object.defineProperty(module, "id", { - enumerable: true, - get: function() { - return module.i; - } - }); - module.webpackPolyfill = 1; - } - return module; -}; +module.exports = function(module) { + if(!module.webpackPolyfill) { + module.deprecate = function() {}; + module.paths = []; + // module.parent = undefined by default + if(!module.children) module.children = []; + Object.defineProperty(module, "loaded", { + enumerable: true, + get: function() { + return module.l; + } + }); + Object.defineProperty(module, "id", { + enumerable: true, + get: function() { + return module.i; + } + }); + module.webpackPolyfill = 1; + } + return module; +}; /***/ }), @@ -8321,7 +8321,7 @@ module.exports.default = axios; /*! * Determine if an object is a Buffer * - * @author Feross Aboukhadijeh + * @author Feross Aboukhadijeh * @license MIT */ @@ -9135,7 +9135,7 @@ module.exports = function spread(callback) { /* 52 */ /***/ (function(module, exports) { -module.exports = {"author":"PubNub","name":"chat-engine","version":"0.8.3","description":"ChatEngine","main":"src/index.js","scripts":{"deploy":"gulp; npm publish;","docs":"jsdoc src/index.js -c jsdoc.json"},"repository":{"type":"git","url":"git+https://github.com/pubnub/chat-engine.git"},"keywords":["pubnub","chat","sdk","realtime"],"bugs":{"url":"https://github.com/pubnub/chat-engine/issues"},"homepage":"https://github.com/pubnub/chat-engine#readme","devDependencies":{"body-parser":"^1.17.2","chai":"^3.5.0","chat-engine-typing-indicator":"0.0.x","docdash":"^0.4.0","es6-promise":"^4.1.1","eslint":"^4.7.1","eslint-config-airbnb":"^15.1.0","eslint-plugin-import":"^2.7.0","express":"^4.15.3","gulp":"^3.9.1","gulp-clean":"^0.3.2","gulp-eslint":"^4.0.0","gulp-istanbul":"^1.1.2","gulp-jsdoc3":"^1.0.1","gulp-mocha":"^3.0.1","gulp-rename":"^1.2.2","gulp-uglify":"^2.0.0","gulp-uglify-es":"^0.1.3","http-server":"^0.10.0","isparta":"^4.0.0","jsdoc":"^3.5.5","mocha":"^3.1.2","proxyquire":"^1.8.0","pubnub-functions-mock":"^0.0.6","request":"^2.82.0","run-sequence":"^2.2.0","sinon":"^4.0.0","stats-webpack-plugin":"^0.6.1","uglifyjs-webpack-plugin":"^1.0.1","webpack":"^3.6.0","webpack-stream":"^4.0.0"},"dependencies":{"async":"^2.1.2","axios":"^0.16.2","eventemitter2":"^2.2.1","pubnub":"^4.17.0"}} +module.exports = {"author":"PubNub","name":"chat-engine","version":"0.8.4","description":"ChatEngine","main":"src/index.js","scripts":{"deploy":"gulp; npm publish;","docs":"jsdoc src/index.js -c jsdoc.json"},"repository":{"type":"git","url":"git+https://github.com/pubnub/chat-engine.git"},"keywords":["pubnub","chat","sdk","realtime"],"bugs":{"url":"https://github.com/pubnub/chat-engine/issues"},"homepage":"https://github.com/pubnub/chat-engine#readme","devDependencies":{"body-parser":"^1.17.2","chai":"^3.5.0","chat-engine-typing-indicator":"0.0.x","docdash":"^0.4.0","es6-promise":"^4.1.1","eslint":"^4.7.1","eslint-config-airbnb":"^15.1.0","eslint-plugin-import":"^2.7.0","express":"^4.15.3","gulp":"^3.9.1","gulp-clean":"^0.3.2","gulp-eslint":"^4.0.0","gulp-istanbul":"^1.1.2","gulp-jsdoc3":"^1.0.1","gulp-mocha":"^3.0.1","gulp-rename":"^1.2.2","gulp-surge":"^0.1.0","gulp-uglify":"^2.0.0","gulp-uglify-es":"^0.1.3","http-server":"^0.10.0","isparta":"^4.0.0","jsdoc":"^3.5.5","mocha":"^3.1.2","proxyquire":"^1.8.0","pubnub-functions-mock":"^0.0.6","request":"^2.82.0","run-sequence":"^2.2.0","sinon":"^4.0.0","stats-webpack-plugin":"^0.6.1","surge":"^0.19.0","uglifyjs-webpack-plugin":"^1.0.1","webpack":"^3.6.0","webpack-stream":"^4.0.0"},"dependencies":{"async":"^2.1.2","axios":"^0.16.2","eventemitter2":"^2.2.1","pubnub":"^4.17.0"}} /***/ }), /* 53 */ @@ -9892,7 +9892,7 @@ const Search = __webpack_require__(60); */ class Chat extends Emitter { - constructor(chatEngine, channel = new Date().getTime(), isPrivate = true, autoConnect = true, meta = {}, group = 'custom') { + constructor(chatEngine, channel = new Date().getTime(), isPrivate = false, autoConnect = true, meta = {}, group = 'custom') { super(chatEngine); diff --git a/dist/chat-engine.min.js b/dist/chat-engine.min.js index 87bf3562..de39f63c 100644 --- a/dist/chat-engine.min.js +++ b/dist/chat-engine.min.js @@ -1 +1 @@ -!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.ChatEngineCore=t():e.ChatEngineCore=t()}(this,function(){return function(e){function t(r){if(n[r])return n[r].exports;var i=n[r]={i:r,l:!1,exports:{}};return e[r].call(i.exports,i,i.exports,t),i.l=!0,i.exports}var n={};return t.m=e,t.c=n,t.d=function(e,n,r){t.o(e,n)||Object.defineProperty(e,n,{configurable:!1,enumerable:!0,get:r})},t.n=function(e){var n=e&&e.__esModule?function(){return e.default}:function(){return e};return t.d(n,"a",n),n},t.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},t.p="",t(t.s=30)}([function(e,t,n){"use strict";function r(e){return"[object Array]"===l.call(e)}function i(e){return null!==e&&"object"==typeof e}function o(e){return"[object Function]"===l.call(e)}function s(e,t){if(null!==e&&void 0!==e)if("object"==typeof e||r(e)||(e=[e]),r(e))for(var n=0,i=e.length;n1)for(var n=1;n=200&&e<300}};a.headers={common:{Accept:"application/json, text/plain, */*"}},i.forEach(["delete","get","head"],function(e){a.headers[e]={}}),i.forEach(["post","put","patch"],function(e){a.headers[e]=i.merge(s)}),e.exports=a}).call(t,n(1))},function(e,t){var n;n=function(){return this}();try{n=n||Function("return this")()||(0,eval)("this")}catch(e){"object"==typeof window&&(n=window)}e.exports=n},function(e,t){e.exports=function(e){return e.webpackPolyfill||(e.deprecate=function(){},e.paths=[],e.children||(e.children=[]),Object.defineProperty(e,"loaded",{enumerable:!0,get:function(){return e.l}}),Object.defineProperty(e,"id",{enumerable:!0,get:function(){return e.i}}),e.webpackPolyfill=1),e}},function(e,t,n){const r=n(56),i=n(14),o=n(23);class s extends i{constructor(e){super(),this.chatEngine=e,this.name="Emitter",this.plugins=[],this._dataset={},this._emit=((e,t={})=>(this.chatEngine._emit(e,t,this),this.emitter.emit(e,t),this)),this.on=((e,t)=>(this.events[e]=this.events[e]||new o(this.chatEngine,this,e),this._on(e,t),this))}addChild(e,t){this[e]=t,this._dataset[e]||(this._dataset[e]={}),t.parent=this,t.get=this.get.bind(this._dataset[e]),t.set=this.set.bind(this._dataset[e])}get(e){return this[e]}set(e,t){this[e]&&!t?delete this[e]:this[e]=t}plugin(e){return this.plugins.push(e),e.extends&&e.extends[this.name]&&(this.addChild(e.namespace,new e.extends[this.name]),this[e.namespace].ChatEngine=this.chatEngine,this[e.namespace].construct&&this[e.namespace].construct()),this}bindProtoPlugins(){this.chatEngine.protoPlugins[this.name]&&this.chatEngine.protoPlugins[this.name].forEach(e=>{this.plugin(e)})}trigger(e,t={},n=(()=>{})){let r=()=>{this.runPluginQueue("on",e,e=>{e(null,t)},(t,r)=>{t?n(t):(this._emit(e,r),n(null,e,r))})};"object"==typeof t?(t.chat||(t.chat=this),t.sender?(t.sender=new this.chatEngine.User(t.sender),t.sender._getState(()=>{r()})):r()):r()}runPluginQueue(e,t,n,i){let o=[];o.push(n),this.plugins.forEach(n=>{n.middleware&&n.middleware[e]&&(n.middleware[e][t]&&o.push(n.middleware[e][t]),n.middleware[e]["*"]&&o.push(n.middleware[e]["*"]))}),r(o,i)}onConstructed(){this.bindProtoPlugins(),this.trigger(["$","created",this.name.toLowerCase()].join("."))}}e.exports=s},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e,t){t|=0;for(var n=Math.max(e.length-t,0),r=Array(n),i=0;i(this.emitter.on(e,t),this)),this.off=((e,t)=>(this.emitter.off(e,t),this)),this.onAny=((e,t)=>(this.emitter.onAny(e,t),this)),this.once=((e,t)=>(this.emitter.once(e,t),this))}}e.exports=i},function(e,t,n){(function(e,n,r,i){!function(e,n){n(t)}(0,function(t){"use strict";function o(e,t){t|=0;for(var n=Math.max(e.length-t,0),r=Array(n),i=0;i-1&&e%1==0&&e<=Ve}function y(e){return null!=e&&g(e.length)&&!function(e){if(!s(e))return!1;var t=d(e);return t==ze||t==$e||t==He||t==Xe}(e)}function v(){}function b(e){return function(){if(null!==e){var t=e;e=null,t.apply(this,arguments)}}}function m(e){return null!=e&&"object"==typeof e}function _(e){return m(e)&&d(e)==Ye}function w(e){return y(e)?function(e,t){var n=rt(e),r=!n&&nt(e),i=!n&&!r&&at(e),o=!n&&!r&&!i&&yt(e),s=n||r||i||o,a=s?function(e,t){for(var n=-1,r=Array(e);++n-1&&e%1==0&&e0?r:e);else if(s)n[t]=e;else{if(i=function(e){return e=e.toString().replace(Jt,""),e=e.match(Xt)[2].replace(" ",""),e=e?e.split(Vt):[],e=e.map(function(e){return function(e,t,n){if((e=function(e){return null==e?"":N(e)}(e))&&(n||void 0===t))return e.replace($t,"");if(!e||!(t=N(t)))return e;var r=L(e),i=L(t);return function(e,t,n){var r=e.length;return n=void 0===n?r:n,!t&&n>=r?e:function(e,t,n){var r=-1,i=e.length;t<0&&(t=-t>i?0:i+t),(n=n>i?i:n)<0&&(n+=i),i=t>n?0:n-t>>>0,t>>>=0;for(var o=Array(i);++r-1;);return n}(r,i),function(e,t){for(var n=e.length;n--&&M(t,e[n],0)>-1;);return n}(r,i)+1).join("")}(e.replace(Wt,""))})}(e),0===e.length&&!o&&0===i.length)throw new Error("autoInject task functions require explicit parameters.");o||i.pop(),n[t]=i.concat(r)}}),Ct(n,t)}function D(){this.head=this.tail=null,this.length=0}function U(e,t){e.length=1,e.head=e.tail=t}function I(e,t,n){function r(e,t,n){if(null!=n&&"function"!=typeof n)throw new Error("task callback must be a function");if(u.started=!0,rt(e)||(e=[e]),0===e.length&&u.idle())return Ce(function(){u.drain()});for(var r=0,i=e.length;r=0&&s.splice(a,1),i.callback.apply(i,arguments),null!=t&&u.error(t,i.data)}o<=u.concurrency-u.buffer&&u.unsaturated(),u.idle()&&u.drain(),u.process()}}(e));i(t,l)}a=!1}},length:function(){return u._tasks.length},running:function(){return o},workersList:function(){return s},idle:function(){return u._tasks.length+o===0},pause:function(){u.paused=!0},resume:function(){!1!==u.paused&&(u.paused=!1,Ce(u.process))}};return u}function K(e,t){return I(e,1,t)}function B(e,t,n,r){r=b(r||v);var i=h(n);Yt(e,function(e,n,r){i(t,e,function(e,n){t=n,r(e)})},function(e){r(e,t)})}function F(){var e=A(arguments,h);return function(){var t=o(arguments),n=this,r=t[t.length-1];"function"==typeof r?t.pop():r=v,B(e,t,function(e,t,r){t.apply(n,e.concat(function(e){var t=o(arguments,1);r(e,t)}))},function(e,t){r.apply(n,[e].concat(t))})}}function q(e){return e}function G(e,t){return function(n,r,i,o){o=o||v;var s,a=!1;n(r,function(n,r,o){i(n,function(r,i){r?o(r):e(i)&&!s?(a=!0,s=t(!0,n),o(null,We)):o()})},function(e){e?o(e):o(null,a?s:t(!1))})}}function H(e,t){return t}function z(e){return function(t){var n=o(arguments,1);n.push(function(t){var n=o(arguments,1);"object"==typeof console&&(t?console.error&&console.error(t):console[e]&&j(n,function(t){console[e](t)}))}),h(t).apply(null,n)}}function $(e,t,n){function r(e,t){return e?n(e):t?void i(function(e){if(e)return n(e);var t=o(arguments,1);t.push(r),s.apply(this,t)}):n(null)}n=k(n||v);var i=h(e),s=h(t);r(null,!0)}function X(e,t,n){n=k(n||v);var r=h(e),i=function(e){if(e)return n(e);var s=o(arguments,1);if(t.apply(this,s))return r(i);n.apply(null,[null].concat(s))};r(i)}function V(e,t,n){X(e,function(){return!t.apply(this,arguments)},n)}function W(e,t,n){function r(e,t){return e?n(e):t?void i(function(e){if(e)return n(e);o(r)}):n(null)}n=k(n||v);var i=h(t),o=h(e);o(r)}function J(e){return function(t,n,r){return e(t,r)}}function Q(e,t,n){kt(e,J(h(t)),n)}function Y(e,t,n,r){E(t)(e,J(h(n)),r)}function Z(e){return f(e)?e:xe(function(t,n){var r=!0;t.push(function(){var e=arguments;r?Ce(function(){n.apply(null,e)}):n.apply(null,e)}),e.apply(this,t),r=!1})}function ee(e){return!e}function te(e){return function(t){return null==t?void 0:t[e]}}function ne(e,t,n,r){(y(t)?function(e,t,n,r){var i=new Array(t.length);e(t,function(e,t,r){n(e,function(e,n){i[t]=!!n,r(e)})},function(e){if(e)return r(e);for(var n=[],o=0;o2&&(i=o(arguments,1)),r[t]=i,n(e)})},function(e){n(e,r)})}function ue(e,t){ae(kt,e,t)}function ce(e,t,n){ae(E(t),e,n)}function le(e,t){if(t=b(t||v),!rt(e))return t(new TypeError("First argument to race must be an array of functions"));if(!e.length)return t();for(var n=0,r=e.length;nr?1:0}),te("value")))})}function me(e,t,n){var r=h(e);return xe(function(i,o){var s,a=!1;i.push(function(){a||(o.apply(null,arguments),clearTimeout(s))}),s=setTimeout(function(){var t=e.name||"anonymous",r=new Error('Callback function "'+t+'" timed out.');r.code="ETIMEDOUT",n&&(r.info=n),a=!0,o(r)},t),r.apply(null,i)})}function _e(e,t,n,r){var i=h(n);Pt(function(e,t,n,r){for(var i=-1,o=Ln(Nn((t-e)/(n||1)),0),s=Array(o);o--;)s[r?o:++i]=e,e+=n;return s}(0,e,1),t,i,r)}function we(e,t,n,r){arguments.length<=3&&(r=n,n=t,t=rt(e)?[]:{}),r=b(r||v);var i=h(n);kt(e,function(e,n,r){i(t,e,n,r)},function(e){r(e,t)})}function ke(e,t){var n,r=null;t=t||v,ln(e,function(e,t){h(e)(function(e,i){n=arguments.length>2?o(arguments,1):i,r=e,t(!e)})},function(){t(r,n)})}function Ee(e){return function(){return(e.unmemoized||e).apply(null,arguments)}}function Se(e,t,n){n=k(n||v);var r=h(t);if(!e())return n(null);var i=function(t){if(t)return n(t);if(e())return r(i);var s=o(arguments,1);n.apply(null,[null].concat(s))};r(i)}function Pe(e,t,n){Se(function(){return!e.apply(this,arguments)},t,n)}var Oe,xe=function(e){return function(){var t=o(arguments),n=t.pop();e.call(this,t,n)}},Te="function"==typeof e&&e,je="object"==typeof n&&"function"==typeof n.nextTick,Ce=u(Oe=Te?e:je?n.nextTick:a),Me="function"==typeof Symbol,Ae="object"==typeof r&&r&&r.Object===Object&&r,Ne="object"==typeof self&&self&&self.Object===Object&&self,Le=Ae||Ne||Function("return this")(),Re=Le.Symbol,De=Object.prototype,Ue=De.hasOwnProperty,Ie=De.toString,Ke=Re?Re.toStringTag:void 0,Be=Object.prototype.toString,Fe="[object Null]",qe="[object Undefined]",Ge=Re?Re.toStringTag:void 0,He="[object AsyncFunction]",ze="[object Function]",$e="[object GeneratorFunction]",Xe="[object Proxy]",Ve=9007199254740991,We={},Je="function"==typeof Symbol&&Symbol.iterator,Qe=function(e){return Je&&e[Je]&&e[Je]()},Ye="[object Arguments]",Ze=Object.prototype,et=Ze.hasOwnProperty,tt=Ze.propertyIsEnumerable,nt=_(function(){return arguments}())?_:function(e){return m(e)&&et.call(e,"callee")&&!tt.call(e,"callee")},rt=Array.isArray,it="object"==typeof t&&t&&!t.nodeType&&t,ot=it&&"object"==typeof i&&i&&!i.nodeType&&i,st=ot&&ot.exports===it?Le.Buffer:void 0,at=(st?st.isBuffer:void 0)||function(){return!1},ut=9007199254740991,ct=/^(?:0|[1-9]\d*)$/,lt={};lt["[object Float32Array]"]=lt["[object Float64Array]"]=lt["[object Int8Array]"]=lt["[object Int16Array]"]=lt["[object Int32Array]"]=lt["[object Uint8Array]"]=lt["[object Uint8ClampedArray]"]=lt["[object Uint16Array]"]=lt["[object Uint32Array]"]=!0,lt["[object Arguments]"]=lt["[object Array]"]=lt["[object ArrayBuffer]"]=lt["[object Boolean]"]=lt["[object DataView]"]=lt["[object Date]"]=lt["[object Error]"]=lt["[object Function]"]=lt["[object Map]"]=lt["[object Number]"]=lt["[object Object]"]=lt["[object RegExp]"]=lt["[object Set]"]=lt["[object String]"]=lt["[object WeakMap]"]=!1;var ft="object"==typeof t&&t&&!t.nodeType&&t,ht=ft&&"object"==typeof i&&i&&!i.nodeType&&i,pt=ht&&ht.exports===ft&&Ae.process,dt=function(){try{return pt&&pt.binding("util")}catch(e){}}(),gt=dt&&dt.isTypedArray,yt=gt?function(e){return function(t){return e(t)}}(gt):function(e){return m(e)&&g(e.length)&&!!lt[d(e)]},vt=Object.prototype.hasOwnProperty,bt=Object.prototype,mt=function(e,t){return function(n){return e(t(n))}}(Object.keys,Object),_t=Object.prototype.hasOwnProperty,wt=P(S,1/0),kt=function(e,t,n){(y(e)?function(e,t,n){n=b(n||v);var r=0,i=0,o=e.length;for(0===o&&n(null);r2&&(r=o(arguments,1)),t){var s={};C(a,function(e,t){s[t]=e}),s[e]=r,c=!0,l=Object.create(null),n(t,s)}else a[e]=r,function(e){j(l[e]||[],function(e){e()}),i()}(e)});u++;var s=h(t[t.length-1]);t.length>1?s(a,r):s(r)}(e,t)})}function i(){if(0===f.length&&0===u)return n(null,a);for(;f.length&&u=0&&n.push(r)}),n}(p.pop()),function(e){0==--d[e]&&p.push(e)});if(t!==s)throw new Error("async.auto cannot execute tasks due to a recursive dependency")}(),i()},Mt="[object Symbol]",At=1/0,Nt=Re?Re.prototype:void 0,Lt=Nt?Nt.toString:void 0,Rt=RegExp("[\\u200d\\ud800-\\udfff\\u0300-\\u036f\\ufe20-\\ufe23\\u20d0-\\u20f0\\ufe0e\\ufe0f]"),Dt="[\\ud800-\\udfff]",Ut="[\\u0300-\\u036f\\ufe20-\\ufe23\\u20d0-\\u20f0]",It="\\ud83c[\\udffb-\\udfff]",Kt="[^\\ud800-\\udfff]",Bt="(?:\\ud83c[\\udde6-\\uddff]){2}",Ft="[\\ud800-\\udbff][\\udc00-\\udfff]",qt="(?:"+Ut+"|"+It+")"+"?",Gt="[\\ufe0e\\ufe0f]?"+qt+("(?:\\u200d(?:"+[Kt,Bt,Ft].join("|")+")[\\ufe0e\\ufe0f]?"+qt+")*"),Ht="(?:"+[Kt+Ut+"?",Ut,Bt,Ft,Dt].join("|")+")",zt=RegExp(It+"(?="+It+")|"+Ht+Gt,"g"),$t=/^\s+|\s+$/g,Xt=/^(?:async\s+)?(function)?\s*[^\(]*\(\s*([^\)]*)\)/m,Vt=/,/,Wt=/(=.+)?(\s*)$/,Jt=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/gm;D.prototype.removeLink=function(e){return e.prev?e.prev.next=e.next:this.head=e.next,e.next?e.next.prev=e.prev:this.tail=e.prev,e.prev=e.next=null,this.length-=1,e},D.prototype.empty=function(){for(;this.head;)this.shift();return this},D.prototype.insertAfter=function(e,t){t.prev=e,t.next=e.next,e.next?e.next.prev=t:this.tail=t,e.next=t,this.length+=1},D.prototype.insertBefore=function(e,t){t.prev=e.prev,t.next=e,e.prev?e.prev.next=t:this.head=t,e.prev=t,this.length+=1},D.prototype.unshift=function(e){this.head?this.insertBefore(this.head,e):U(this,e)},D.prototype.push=function(e){this.tail?this.insertAfter(this.tail,e):U(this,e)},D.prototype.shift=function(){return this.head&&this.removeLink(this.head)},D.prototype.pop=function(){return this.tail&&this.removeLink(this.tail)},D.prototype.toArray=function(){for(var e=Array(this.length),t=this.head,n=0;n=i.priority;)i=i.next;for(var o=0,s=e.length;o=0&&(e._idleTimeoutId=setTimeout(function(){e._onTimeout&&e._onTimeout()},t))},n(55),t.setImmediate=setImmediate,t.clearImmediate=clearImmediate},function(e,t){var n=Array.isArray;e.exports=n},function(e,t){e.exports=function(){}},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e){return function(){if(null!==e){var t=e;e=null,t.apply(this,arguments)}}},e.exports=t.default},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e){return function(){if(null===e)throw new Error("Callback was already called.");var t=e;e=null,t.apply(this,arguments)}},e.exports=t.default},function(e,t,n){"use strict";function r(e){return o&&"AsyncFunction"===e[Symbol.toStringTag]}Object.defineProperty(t,"__esModule",{value:!0}),t.isAsync=void 0;var i=function(e){return e&&e.__esModule?e:{default:e}}(n(57)),o="function"==typeof Symbol;t.default=function(e){return r(e)?(0,i.default)(e):e},t.isAsync=r},function(e,t){e.exports=function(e){var t=typeof e;return null!=e&&("object"==t||"function"==t)}},function(e,t){class n{constructor(e,t,n){return this.channel=t.channel,this.chatEngine=e,this.chat=t,this.event=n,this.name="Event",this.chatEngine.pubnub.addListener({message:this.onMessage.bind(this)}),this}onMessage(e){this.channel===e.channel&&e.message.event===this.event&&this.chat.trigger(e.message.event,e.message)}publish(e){e.event=this.event,this.chatEngine.pubnub.publish({message:e,channel:this.channel},t=>{200===t.statusCode?this.chat.trigger("$.publish.success",e):this.chatEngine.throwError(this.chat,"trigger","publish",new Error("There was a problem publishing over the PubNub network."),t)})}}e.exports=n},function(e,t,n){var r=n(65),i=n(28);e.exports=function(e){return null!=e&&i(e.length)&&!r(e)}},function(e,t,n){var r=n(26).Symbol;e.exports=r},function(e,t,n){var r=n(27),i="object"==typeof self&&self&&self.Object===Object&&self,o=r||i||Function("return this")();e.exports=o},function(e,t,n){(function(t){var n="object"==typeof t&&t&&t.Object===Object&&t;e.exports=n}).call(t,n(3))},function(e,t){var n=9007199254740991;e.exports=function(e){return"number"==typeof e&&e>-1&&e%1==0&&e<=n}},function(e,t,n){const r=n(5);class i extends r{constructor(e,t,n={}){return super(),this.chatEngine=e,this.name="User",this.uuid=t,this.state={},this._stateFetched=!1,this.feed=new this.chatEngine.Chat([e.global.channel,"user",t,"read.","feed"].join("#"),!1,"Me"===this.constructor.name,{},"system"),this.direct=new this.chatEngine.Chat([e.global.channel,"user",t,"write.","direct"].join("#"),!1,"Me"===this.constructor.name,{},"system"),e.users[t]||(e.users[t]=this),this.assign(n),this}update(e){let t=this.state||{};this.state=Object.assign(t,e)}assign(e){this.update(e)}_getState(e){this._stateFetched?e(this.state):this.chatEngine.pubnub.getState({uuid:this.uuid,channels:[this.chatEngine.global.channel]},(t,n)=>{if(200===t.statusCode){let t=n.channels[this.chatEngine.global.channel];Object.keys(t).length?(this.assign(n.data),this._stateFetched=!0,e(this.state)):this.chatEngine.request("get","user_state",{user:this.uuid}).then(t=>{this.assign(t.data),this._stateFetched=!0,e(this.state)}).catch(e=>{this.chatEngine.throwError(this,"trigger","getState",e)})}else this.chatEngine.throwError(this,"trigger","getState",new Error("There was a problem getting state from the PubNub network."))})}}e.exports=i},function(e,t,n){const r=n(31);e.exports={plugin:{},create:(e,t={})=>(t.globalChannel?t.globalChannel=t.globalChannel.toString():t.globalChannel="chat-engine",void 0===t.throwErrors&&(t.throwErrors=!0),r(t,e))}},function(e,t,n){const r=n(32),i=n(51),o=n(52),s=n(14),a=n(54),u=n(88),c=n(29),l=n(15);e.exports=((e={},t={})=>{let n=new s;return n.ceConfig=e,n.pnConfig=t,n.pnConfig.heartbeatInterval=n.pnConfig.heartbeatInterval||30,n.pnConfig.presenceTimeout=n.pnConfig.presenceTimeout||60,n.ceConfig.endpoint=n.ceConfig.endpoint||"https://pubsub.pubnub.com/v1/blocks/sub-key/"+n.pnConfig.subscribeKey+"/chat-engine-server",n.ceConfig.globalChannel=n.ceConfig.globalChannel||"chat-engine-global",n.users={},n.chats={},n.global=!1,n.me=!1,n.pubnub=!1,n.ready=!1,n.package=o,n.throwError=((t,n,r,i,o={})=>{if(e.throwErrors)throw console.error(o),i;o.ceError=i.toString(),t[n](["$","error",r].join("."),o)}),e.debug&&n.onAny((e,t)=>{console.info("debug:",e,t)}),n.protoPlugins={},n.proto=((e,t)=>{n.protoPlugins[e]=n.protoPlugins[e]||[],n.protoPlugins[e].push(t)}),n.request=((i,o,s={},a={})=>{let u={uuid:t.uuid,global:e.globalChannel,authData:n.me.authData,authKey:t.authKey},c={route:o};return u=Object.assign(u,s),c=Object.assign(c,a),"get"===i||"delete"===i?(c=Object.assign(c,u),r[i](e.endpoint,{params:c})):r[i](e.endpoint,u,{params:c})}),n.parseChannel=(e=>{let t=e.split("#");return{global:t[0],type:t[1],private:"private."===t[2]}}),n.augmentChannel=((e=(new Date).getTime(),t=!0)=>{let r=e.toString(),i="public.";return t&&(i="private."),-1===r.indexOf(n.ceConfig.globalChannel)&&(r=[n.ceConfig.globalChannel,"chat",i,r].join("#")),r}),n.connect=((r,o={},s=!1,a)=>{t.uuid=r,t.authKey=s||t.uuid;l.parallel([e=>{n.request("post","bootstrap").then(()=>{e(null)}).catch(e)},e=>{n.request("post","user_read").then(()=>{e(null)}).catch(e)},e=>{n.request("post","user_write").then(()=>{e(null)}).catch(e)},r=>{n.request("post","group").then(()=>{n.pubnub=new i(t),n.global=new n.Chat(e.globalChannel,!1,!0,{},"system"),n.me=new u(n,t.uuid,a),n.me.update(o),n.me.onConstructed(),n.global.on("$.connected",()=>{n._emit("$.ready",{me:n.me}),n.global.getUserUpdates();let r=[e.globalChannel+"#"+n.me.uuid+"#rooms",e.globalChannel+"#"+n.me.uuid+"#system",e.globalChannel+"#"+n.me.uuid+"#custom"];n.pubnub.addListener({presence:e=>{n.chats[e.channel]&&n.chats[e.channel].onPresence(e)}}),n.pubnub.subscribe({channelGroups:r,withPresence:!0}),n.ready=!0,["custom","rooms","system"].forEach(r=>{let i=[e.globalChannel,t.uuid,r].join("#");n.pubnub.channelGroups.listChannels({channelGroup:i},(e,t)=>{e.error?console.log("operation failed w/ error:",e):t.channels.forEach(e=>{n.me.addChatToSession({channel:e,private:n.parseChannel(e).private,group:r})})})})}),n.pubnub.addListener({status:e=>{let t=["$","network",{PNNetworkUpCategory:"up.online",PNNetworkDownCategory:"down.offline",PNNetworkIssuesCategory:"down.issue",PNReconnectedCategory:"up.reconnected",PNConnectedCategory:"up.connected",PNAccessDeniedCategory:"down.denied",PNMalformedResponseCategory:"down.malformed",PNBadRequestCategory:"down.badrequest",PNDecryptionErrorCategory:"down.decryption",PNTimeoutCategory:"down.timeout"}[e.category]||"other"].join(".");e.affectedChannels?e.affectedChannels.forEach(r=>{let i=n.chats[r];i?("PNConnectedCategory"===e.category&&i.onConnectionReady(),i.trigger(t,e)):n._emit(t,e)}):n._emit(t,e)}})}).catch(r)}],t=>{t&&n.throwError(n,"_emit","auth",new Error("There was a problem logging into the auth server ("+e.endpoint+")."),{error:t})})}),n.Chat=function(...e){let t=n.augmentChannel(e[0],e[1]);if(n.chats[t])return n.chats[t];{let t=new a(n,...e);return t.onConstructed(),t}},n.User=function(...e){if(n.me.uuid===e[0])return n.me;if(n.users[e[0]])return n.users[e[0]];{let t=new c(n,...e);return t.onConstructed(),t}},n})},function(e,t,n){e.exports=n(33)},function(e,t,n){"use strict";function r(e){var t=new s(e),n=o(s.prototype.request,t);return i.extend(n,s.prototype,t),i.extend(n,t),n}var i=n(0),o=n(9),s=n(35),a=n(2),u=r(a);u.Axios=s,u.create=function(e){return r(i.merge(a,e))},u.Cancel=n(13),u.CancelToken=n(49),u.isCancel=n(12),u.all=function(e){return Promise.all(e)},u.spread=n(50),e.exports=u,e.exports.default=u},function(e,t){function n(e){return!!e.constructor&&"function"==typeof e.constructor.isBuffer&&e.constructor.isBuffer(e)}e.exports=function(e){return null!=e&&(n(e)||function(e){return"function"==typeof e.readFloatLE&&"function"==typeof e.slice&&n(e.slice(0,0))}(e)||!!e._isBuffer)}},function(e,t,n){"use strict";function r(e){this.defaults=e,this.interceptors={request:new s,response:new s}}var i=n(2),o=n(0),s=n(44),a=n(45),u=n(47),c=n(48);r.prototype.request=function(e){"string"==typeof e&&(e=o.merge({url:arguments[0]},arguments[1])),(e=o.merge(i,this.defaults,{method:"get"},e)).method=e.method.toLowerCase(),e.baseURL&&!u(e.url)&&(e.url=c(e.baseURL,e.url));var t=[a,void 0],n=Promise.resolve(e);for(this.interceptors.request.forEach(function(e){t.unshift(e.fulfilled,e.rejected)}),this.interceptors.response.forEach(function(e){t.push(e.fulfilled,e.rejected)});t.length;)n=n.then(t.shift(),t.shift());return n},o.forEach(["delete","get","head","options"],function(e){r.prototype[e]=function(t,n){return this.request(o.merge(n||{},{method:e,url:t}))}}),o.forEach(["post","put","patch"],function(e){r.prototype[e]=function(t,n,r){return this.request(o.merge(r||{},{method:e,url:t,data:n}))}}),e.exports=r},function(e,t,n){"use strict";var r=n(0);e.exports=function(e,t){r.forEach(e,function(n,r){r!==t&&r.toUpperCase()===t.toUpperCase()&&(e[t]=n,delete e[r])})}},function(e,t,n){"use strict";var r=n(11);e.exports=function(e,t,n){var i=n.config.validateStatus;n.status&&i&&!i(n.status)?t(r("Request failed with status code "+n.status,n.config,null,n.request,n)):e(n)}},function(e,t,n){"use strict";e.exports=function(e,t,n,r,i){return e.config=t,n&&(e.code=n),e.request=r,e.response=i,e}},function(e,t,n){"use strict";function r(e){return encodeURIComponent(e).replace(/%40/gi,"@").replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}var i=n(0);e.exports=function(e,t,n){if(!t)return e;var o;if(n)o=n(t);else if(i.isURLSearchParams(t))o=t.toString();else{var s=[];i.forEach(t,function(e,t){null!==e&&void 0!==e&&(i.isArray(e)&&(t+="[]"),i.isArray(e)||(e=[e]),i.forEach(e,function(e){i.isDate(e)?e=e.toISOString():i.isObject(e)&&(e=JSON.stringify(e)),s.push(r(t)+"="+r(e))}))}),o=s.join("&")}return o&&(e+=(-1===e.indexOf("?")?"?":"&")+o),e}},function(e,t,n){"use strict";var r=n(0);e.exports=function(e){var t,n,i,o={};return e?(r.forEach(e.split("\n"),function(e){i=e.indexOf(":"),t=r.trim(e.substr(0,i)).toLowerCase(),n=r.trim(e.substr(i+1)),t&&(o[t]=o[t]?o[t]+", "+n:n)}),o):o}},function(e,t,n){"use strict";var r=n(0);e.exports=r.isStandardBrowserEnv()?function(){function e(e){var t=e;return n&&(i.setAttribute("href",t),t=i.href),i.setAttribute("href",t),{href:i.href,protocol:i.protocol?i.protocol.replace(/:$/,""):"",host:i.host,search:i.search?i.search.replace(/^\?/,""):"",hash:i.hash?i.hash.replace(/^#/,""):"",hostname:i.hostname,port:i.port,pathname:"/"===i.pathname.charAt(0)?i.pathname:"/"+i.pathname}}var t,n=/(msie|trident)/i.test(navigator.userAgent),i=document.createElement("a");return t=e(window.location.href),function(n){var i=r.isString(n)?e(n):n;return i.protocol===t.protocol&&i.host===t.host}}():function(){return!0}},function(e,t,n){"use strict";function r(){this.message="String contains an invalid character"}var i="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";(r.prototype=new Error).code=5,r.prototype.name="InvalidCharacterError",e.exports=function(e){for(var t,n,o=String(e),s="",a=0,u=i;o.charAt(0|a)||(u="=",a%1);s+=u.charAt(63&t>>8-a%1*8)){if((n=o.charCodeAt(a+=.75))>255)throw new r;t=t<<8|n}return s}},function(e,t,n){"use strict";var r=n(0);e.exports=r.isStandardBrowserEnv()?{write:function(e,t,n,i,o,s){var a=[];a.push(e+"="+encodeURIComponent(t)),r.isNumber(n)&&a.push("expires="+new Date(n).toGMTString()),r.isString(i)&&a.push("path="+i),r.isString(o)&&a.push("domain="+o),!0===s&&a.push("secure"),document.cookie=a.join("; ")},read:function(e){var t=document.cookie.match(new RegExp("(^|;\\s*)("+e+")=([^;]*)"));return t?decodeURIComponent(t[3]):null},remove:function(e){this.write(e,"",Date.now()-864e5)}}:{write:function(){},read:function(){return null},remove:function(){}}},function(e,t,n){"use strict";function r(){this.handlers=[]}var i=n(0);r.prototype.use=function(e,t){return this.handlers.push({fulfilled:e,rejected:t}),this.handlers.length-1},r.prototype.eject=function(e){this.handlers[e]&&(this.handlers[e]=null)},r.prototype.forEach=function(e){i.forEach(this.handlers,function(t){null!==t&&e(t)})},e.exports=r},function(e,t,n){"use strict";function r(e){e.cancelToken&&e.cancelToken.throwIfRequested()}var i=n(0),o=n(46),s=n(12),a=n(2);e.exports=function(e){r(e),e.headers=e.headers||{},e.data=o(e.data,e.headers,e.transformRequest),e.headers=i.merge(e.headers.common||{},e.headers[e.method]||{},e.headers||{}),i.forEach(["delete","get","head","post","put","patch","common"],function(t){delete e.headers[t]});return(e.adapter||a.adapter)(e).then(function(t){return r(e),t.data=o(t.data,t.headers,e.transformResponse),t},function(t){return s(t)||(r(e),t&&t.response&&(t.response.data=o(t.response.data,t.response.headers,e.transformResponse))),Promise.reject(t)})}},function(e,t,n){"use strict";var r=n(0);e.exports=function(e,t,n){return r.forEach(n,function(n){e=n(e,t)}),e}},function(e,t,n){"use strict";e.exports=function(e){return/^([a-z][a-z\d\+\-\.]*:)?\/\//i.test(e)}},function(e,t,n){"use strict";e.exports=function(e,t){return t?e.replace(/\/+$/,"")+"/"+t.replace(/^\/+/,""):e}},function(e,t,n){"use strict";function r(e){if("function"!=typeof e)throw new TypeError("executor must be a function.");var t;this.promise=new Promise(function(e){t=e});var n=this;e(function(e){n.reason||(n.reason=new i(e),t(n.reason))})}var i=n(13);r.prototype.throwIfRequested=function(){if(this.reason)throw this.reason},r.source=function(){var e;return{token:new r(function(t){e=t}),cancel:e}},e.exports=r},function(e,t,n){"use strict";e.exports=function(e){return function(t){return e.apply(null,t)}}},function(e,t,n){!function(t,n){e.exports=n()}(0,function(){return function(e){function t(r){if(n[r])return n[r].exports;var i=n[r]={exports:{},id:r,loaded:!1};return e[r].call(i.exports,i,i.exports,t),i.loaded=!0,i.exports}var n={};return t.m=e,t.c=n,t.p="",t(0)}([function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0});var i=r(n(1)),o=r(n(39)),s=r(n(40)),a=n(41),u=(n(5),function(e){function t(e){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,t);var n=e.listenToBrowserNetworkEvents,r=void 0===n||n;e.db=s.default,e.sdkFamily="Web",e.networking=new o.default({del:a.del,get:a.get,post:a.post,sendBeacon:function(e){if(!navigator||!navigator.sendBeacon)return!1;navigator.sendBeacon(e)}});var i=function(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));return r&&(window.addEventListener("offline",function(){i.networkDownDetected()}),window.addEventListener("online",function(){i.networkUpDetected()})),i}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}(t,i.default),t}());t.default=u,e.exports=t.default},function(e,t,n){"use strict";function r(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n]);return t.default=e,t}function i(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0});var o=function(){function e(e,t){for(var n=0;n>>2]|=(n[i>>>2]>>>24-i%4*8&255)<<24-(r+i)%4*8;else if(65535>>2]=n[i>>>2];else t.push.apply(t,n);return this.sigBytes+=e,this},clamp:function(){var t=this.words,n=this.sigBytes;t[n>>>2]&=4294967295<<32-n%4*8,t.length=e.ceil(n/4)},clone:function(){var e=o.clone.call(this);return e.words=this.words.slice(0),e},random:function(t){for(var n=[],r=0;r>>2]>>>24-r%4*8&255;n.push((i>>>4).toString(16)),n.push((15&i).toString(16))}return n.join("")},parse:function(e){for(var t=e.length,n=[],r=0;r>>3]|=parseInt(e.substr(r,2),16)<<24-r%8*4;return new s.init(n,t/2)}},c=a.Latin1={stringify:function(e){var t=e.words;e=e.sigBytes;for(var n=[],r=0;r>>2]>>>24-r%4*8&255));return n.join("")},parse:function(e){for(var t=e.length,n=[],r=0;r>>2]|=(255&e.charCodeAt(r))<<24-r%4*8;return new s.init(n,t)}},l=a.Utf8={stringify:function(e){try{return decodeURIComponent(escape(c.stringify(e)))}catch(e){throw Error("Malformed UTF-8 data")}},parse:function(e){return c.parse(unescape(encodeURIComponent(e)))}},f=r.BufferedBlockAlgorithm=o.extend({reset:function(){this._data=new s.init,this._nDataBytes=0},_append:function(e){"string"==typeof e&&(e=l.parse(e)),this._data.concat(e),this._nDataBytes+=e.sigBytes},_process:function(t){var n=this._data,r=n.words,i=n.sigBytes,o=this.blockSize,a=i/(4*o);if(t=(a=t?e.ceil(a):e.max((0|a)-this._minBufferSize,0))*o,i=e.min(4*t,i),t){for(var u=0;ul;){var f;e:{f=c;for(var h=e.sqrt(f),p=2;p<=h;p++)if(!(f%p)){f=!1;break e}f=!0}f&&(8>l&&(s[l]=u(e.pow(c,.5))),a[l]=u(e.pow(c,1/3)),l++),c++}var d=[],o=o.SHA256=i.extend({_doReset:function(){this._hash=new r.init(s.slice(0))},_doProcessBlock:function(e,t){for(var n=this._hash.words,r=n[0],i=n[1],o=n[2],s=n[3],u=n[4],c=n[5],l=n[6],f=n[7],h=0;64>h;h++){if(16>h)d[h]=0|e[t+h];else{var p=d[h-15],g=d[h-2];d[h]=((p<<25|p>>>7)^(p<<14|p>>>18)^p>>>3)+d[h-7]+((g<<15|g>>>17)^(g<<13|g>>>19)^g>>>10)+d[h-16]}p=f+((u<<26|u>>>6)^(u<<21|u>>>11)^(u<<7|u>>>25))+(u&c^~u&l)+a[h]+d[h],g=((r<<30|r>>>2)^(r<<19|r>>>13)^(r<<10|r>>>22))+(r&i^r&o^i&o),f=l,l=c,c=u,u=s+p|0,s=o,o=i,i=r,r=p+g|0}n[0]=n[0]+r|0,n[1]=n[1]+i|0,n[2]=n[2]+o|0,n[3]=n[3]+s|0,n[4]=n[4]+u|0,n[5]=n[5]+c|0,n[6]=n[6]+l|0,n[7]=n[7]+f|0},_doFinalize:function(){var t=this._data,n=t.words,r=8*this._nDataBytes,i=8*t.sigBytes;return n[i>>>5]|=128<<24-i%32,n[14+(i+64>>>9<<4)]=e.floor(r/4294967296),n[15+(i+64>>>9<<4)]=r,t.sigBytes=4*n.length,this._process(),this._hash},clone:function(){var e=i.clone.call(this);return e._hash=this._hash.clone(),e}});t.SHA256=i._createHelper(o),t.HmacSHA256=i._createHmacHelper(o)}(Math),function(){var e=n,t=e.enc.Utf8;e.algo.HMAC=e.lib.Base.extend({init:function(e,n){e=this._hasher=new e.init,"string"==typeof n&&(n=t.parse(n));var r=e.blockSize,i=4*r;n.sigBytes>i&&(n=e.finalize(n)),n.clamp();for(var o=this._oKey=n.clone(),s=this._iKey=n.clone(),a=o.words,u=s.words,c=0;c>>2]>>>24-i%4*8&255)<<16|(t[i+1>>>2]>>>24-(i+1)%4*8&255)<<8|t[i+2>>>2]>>>24-(i+2)%4*8&255,s=0;4>s&&i+.75*s>>6*(3-s)&63));if(t=r.charAt(64))for(;e.length%4;)e.push(t);return e.join("")},parse:function(e){var n=e.length,r=this._map;(i=r.charAt(64))&&-1!=(i=e.indexOf(i))&&(n=i);for(var i=[],o=0,s=0;s>>6-s%4*2;i[o>>>2]|=(a|u)<<24-o%4*8,o++}return t.create(i,o)},_map:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="}}(),function(e){function t(e,t,n,r,i,o,s){return((e=e+(t&n|~t&r)+i+s)<>>32-o)+t}function r(e,t,n,r,i,o,s){return((e=e+(t&r|n&~r)+i+s)<>>32-o)+t}function i(e,t,n,r,i,o,s){return((e=e+(t^n^r)+i+s)<>>32-o)+t}function o(e,t,n,r,i,o,s){return((e=e+(n^(t|~r))+i+s)<>>32-o)+t}for(var s=n,a=(c=s.lib).WordArray,u=c.Hasher,c=s.algo,l=[],f=0;64>f;f++)l[f]=4294967296*e.abs(e.sin(f+1))|0;c=c.MD5=u.extend({_doReset:function(){this._hash=new a.init([1732584193,4023233417,2562383102,271733878])},_doProcessBlock:function(e,n){for(s=0;16>s;s++){u=e[a=n+s];e[a]=16711935&(u<<8|u>>>24)|4278255360&(u<<24|u>>>8)}var s=this._hash.words,a=e[n+0],u=e[n+1],c=e[n+2],f=e[n+3],h=e[n+4],p=e[n+5],d=e[n+6],g=e[n+7],y=e[n+8],v=e[n+9],b=e[n+10],m=e[n+11],_=e[n+12],w=e[n+13],k=e[n+14],E=e[n+15],S=s[0],P=s[1],O=s[2],x=s[3],P=o(P=o(P=o(P=o(P=i(P=i(P=i(P=i(P=r(P=r(P=r(P=r(P=t(P=t(P=t(P=t(P,O=t(O,x=t(x,S=t(S,P,O,x,a,7,l[0]),P,O,u,12,l[1]),S,P,c,17,l[2]),x,S,f,22,l[3]),O=t(O,x=t(x,S=t(S,P,O,x,h,7,l[4]),P,O,p,12,l[5]),S,P,d,17,l[6]),x,S,g,22,l[7]),O=t(O,x=t(x,S=t(S,P,O,x,y,7,l[8]),P,O,v,12,l[9]),S,P,b,17,l[10]),x,S,m,22,l[11]),O=t(O,x=t(x,S=t(S,P,O,x,_,7,l[12]),P,O,w,12,l[13]),S,P,k,17,l[14]),x,S,E,22,l[15]),O=r(O,x=r(x,S=r(S,P,O,x,u,5,l[16]),P,O,d,9,l[17]),S,P,m,14,l[18]),x,S,a,20,l[19]),O=r(O,x=r(x,S=r(S,P,O,x,p,5,l[20]),P,O,b,9,l[21]),S,P,E,14,l[22]),x,S,h,20,l[23]),O=r(O,x=r(x,S=r(S,P,O,x,v,5,l[24]),P,O,k,9,l[25]),S,P,f,14,l[26]),x,S,y,20,l[27]),O=r(O,x=r(x,S=r(S,P,O,x,w,5,l[28]),P,O,c,9,l[29]),S,P,g,14,l[30]),x,S,_,20,l[31]),O=i(O,x=i(x,S=i(S,P,O,x,p,4,l[32]),P,O,y,11,l[33]),S,P,m,16,l[34]),x,S,k,23,l[35]),O=i(O,x=i(x,S=i(S,P,O,x,u,4,l[36]),P,O,h,11,l[37]),S,P,g,16,l[38]),x,S,b,23,l[39]),O=i(O,x=i(x,S=i(S,P,O,x,w,4,l[40]),P,O,a,11,l[41]),S,P,f,16,l[42]),x,S,d,23,l[43]),O=i(O,x=i(x,S=i(S,P,O,x,v,4,l[44]),P,O,_,11,l[45]),S,P,E,16,l[46]),x,S,c,23,l[47]),O=o(O,x=o(x,S=o(S,P,O,x,a,6,l[48]),P,O,g,10,l[49]),S,P,k,15,l[50]),x,S,p,21,l[51]),O=o(O,x=o(x,S=o(S,P,O,x,_,6,l[52]),P,O,f,10,l[53]),S,P,b,15,l[54]),x,S,u,21,l[55]),O=o(O,x=o(x,S=o(S,P,O,x,y,6,l[56]),P,O,E,10,l[57]),S,P,d,15,l[58]),x,S,w,21,l[59]),O=o(O,x=o(x,S=o(S,P,O,x,h,6,l[60]),P,O,m,10,l[61]),S,P,c,15,l[62]),x,S,v,21,l[63]);s[0]=s[0]+S|0,s[1]=s[1]+P|0,s[2]=s[2]+O|0,s[3]=s[3]+x|0},_doFinalize:function(){var t=this._data,n=t.words,r=8*this._nDataBytes,i=8*t.sigBytes;n[i>>>5]|=128<<24-i%32;var o=e.floor(r/4294967296);for(n[15+(i+64>>>9<<4)]=16711935&(o<<8|o>>>24)|4278255360&(o<<24|o>>>8),n[14+(i+64>>>9<<4)]=16711935&(r<<8|r>>>24)|4278255360&(r<<24|r>>>8),t.sigBytes=4*(n.length+1),this._process(),n=(t=this._hash).words,r=0;4>r;r++)i=n[r],n[r]=16711935&(i<<8|i>>>24)|4278255360&(i<<24|i>>>8);return t},clone:function(){var e=u.clone.call(this);return e._hash=this._hash.clone(),e}}),s.MD5=u._createHelper(c),s.HmacMD5=u._createHmacHelper(c)}(Math),function(){var e=n,t=e.lib,r=t.Base,i=t.WordArray,o=(t=e.algo).EvpKDF=r.extend({cfg:r.extend({keySize:4,hasher:t.MD5,iterations:1}),init:function(e){this.cfg=this.cfg.extend(e)},compute:function(e,t){for(var n=(a=this.cfg).hasher.create(),r=i.create(),o=r.words,s=a.keySize,a=a.iterations;o.length>>2]}},t.BlockCipher=u.extend({cfg:u.cfg.extend({mode:c,padding:f}),reset:function(){u.reset.call(this);var e=(t=this.cfg).iv,t=t.mode;if(this._xformMode==this._ENC_XFORM_MODE)var n=t.createEncryptor;else n=t.createDecryptor,this._minBufferSize=1;this._mode=n.call(t,this,e&&e.words)},_doProcessBlock:function(e,t){this._mode.processBlock(e,t)},_doFinalize:function(){var e=this.cfg.padding;if(this._xformMode==this._ENC_XFORM_MODE){e.pad(this._data,this.blockSize);var t=this._process(!0)}else t=this._process(!0),e.unpad(t);return t},blockSize:4});var h=t.CipherParams=r.extend({init:function(e){this.mixIn(e)},toString:function(e){return(e||this.formatter).stringify(this)}}),c=(d.format={}).OpenSSL={stringify:function(e){var t=e.ciphertext;return((e=e.salt)?i.create([1398893684,1701076831]).concat(e).concat(t):t).toString(s)},parse:function(e){var t=(e=s.parse(e)).words;if(1398893684==t[0]&&1701076831==t[1]){var n=i.create(t.slice(2,4));t.splice(0,4),e.sigBytes-=16}return h.create({ciphertext:e,salt:n})}},p=t.SerializableCipher=r.extend({cfg:r.extend({format:c}),encrypt:function(e,t,n,r){r=this.cfg.extend(r);var i=e.createEncryptor(n,r);return t=i.finalize(t),i=i.cfg,h.create({ciphertext:t,key:n,iv:i.iv,algorithm:e,mode:i.mode,padding:i.padding,blockSize:e.blockSize,formatter:r.format})},decrypt:function(e,t,n,r){return r=this.cfg.extend(r),t=this._parse(t,r.format),e.createDecryptor(n,r).finalize(t.ciphertext)},_parse:function(e,t){return"string"==typeof e?t.parse(e,this):e}}),d=(d.kdf={}).OpenSSL={execute:function(e,t,n,r){return r||(r=i.random(8)),e=a.create({keySize:t+n}).compute(e,r),n=i.create(e.words.slice(t),4*n),e.sigBytes=4*t,h.create({key:e,iv:n,salt:r})}},g=t.PasswordBasedCipher=p.extend({cfg:p.cfg.extend({kdf:d}),encrypt:function(e,t,n,r){return r=this.cfg.extend(r),n=r.kdf.execute(n,e.keySize,e.ivSize),r.iv=n.iv,(e=p.encrypt.call(this,e,t,n.key,r)).mixIn(n),e},decrypt:function(e,t,n,r){return r=this.cfg.extend(r),t=this._parse(t,r.format),n=r.kdf.execute(n,e.keySize,e.ivSize,t.salt),r.iv=n.iv,p.decrypt.call(this,e,t,n.key,r)}})}(),function(){for(var e=n,t=e.lib.BlockCipher,r=e.algo,i=[],o=[],s=[],a=[],u=[],c=[],l=[],f=[],h=[],p=[],d=[],g=0;256>g;g++)d[g]=128>g?g<<1:g<<1^283;for(var y=0,v=0,g=0;256>g;g++){var b=(b=v^v<<1^v<<2^v<<3^v<<4)>>>8^255&b^99;i[y]=b,o[b]=y;var m=d[y],_=d[m],w=d[_],k=257*d[b]^16843008*b;s[y]=k<<24|k>>>8,a[y]=k<<16|k>>>16,u[y]=k<<8|k>>>24,c[y]=k,k=16843009*w^65537*_^257*m^16843008*y,l[b]=k<<24|k>>>8,f[b]=k<<16|k>>>16,h[b]=k<<8|k>>>24,p[b]=k,y?(y=m^d[d[d[w^m]]],v^=d[d[v]]):y=v=1}var E=[0,1,2,4,8,16,32,64,128,27,54],r=r.AES=t.extend({_doReset:function(){for(var e=(n=this._key).words,t=n.sigBytes/4,n=4*((this._nRounds=t+6)+1),r=this._keySchedule=[],o=0;o>>24]<<24|i[s>>>16&255]<<16|i[s>>>8&255]<<8|i[255&s]):(s=s<<8|s>>>24,s=i[s>>>24]<<24|i[s>>>16&255]<<16|i[s>>>8&255]<<8|i[255&s],s^=E[o/t|0]<<24),r[o]=r[o-t]^s}for(e=this._invKeySchedule=[],t=0;tt||4>=o?s:l[i[s>>>24]]^f[i[s>>>16&255]]^h[i[s>>>8&255]]^p[i[255&s]]},encryptBlock:function(e,t){this._doCryptBlock(e,t,this._keySchedule,s,a,u,c,i)},decryptBlock:function(e,t){var n=e[t+1];e[t+1]=e[t+3],e[t+3]=n,this._doCryptBlock(e,t,this._invKeySchedule,l,f,h,p,o),n=e[t+1],e[t+1]=e[t+3],e[t+3]=n},_doCryptBlock:function(e,t,n,r,i,o,s,a){for(var u=this._nRounds,c=e[t]^n[0],l=e[t+1]^n[1],f=e[t+2]^n[2],h=e[t+3]^n[3],p=4,d=1;d>>24]^i[l>>>16&255]^o[f>>>8&255]^s[255&h]^n[p++],y=r[l>>>24]^i[f>>>16&255]^o[h>>>8&255]^s[255&c]^n[p++],v=r[f>>>24]^i[h>>>16&255]^o[c>>>8&255]^s[255&l]^n[p++],h=r[h>>>24]^i[c>>>16&255]^o[l>>>8&255]^s[255&f]^n[p++],c=g,l=y,f=v;g=(a[c>>>24]<<24|a[l>>>16&255]<<16|a[f>>>8&255]<<8|a[255&h])^n[p++],y=(a[l>>>24]<<24|a[f>>>16&255]<<16|a[h>>>8&255]<<8|a[255&c])^n[p++],v=(a[f>>>24]<<24|a[h>>>16&255]<<16|a[c>>>8&255]<<8|a[255&l])^n[p++],h=(a[h>>>24]<<24|a[c>>>16&255]<<16|a[l>>>8&255]<<8|a[255&f])^n[p++],e[t]=g,e[t+1]=y,e[t+2]=v,e[t+3]=h},keySize:8});e.AES=t._createHelper(r)}(),n.mode.ECB=function(){var e=n.lib.BlockCipherMode.extend();return e.Encryptor=e.extend({processBlock:function(e,t){this._cipher.encryptBlock(e,t)}}),e.Decryptor=e.extend({processBlock:function(e,t){this._cipher.decryptBlock(e,t)}}),e}(),e.exports=n},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0});var i=function(){function e(e,t){for(var n=0;n=s){var l={};l.category=u.default.PNRequestMessageCountExceededCategory,l.operation=e.operation,this._listenerManager.announceStatus(l)}i.forEach(function(e){var t=e.channel,r=e.subscriptionMatch,i=e.publishMetaData;if(t===r&&(r=null),c){if(n._dedupingManager.isDuplicate(e))return;n._dedupingManager.addEntry(e)}if(a.default.endsWith(e.channel,"-pnpres")){var o={};o.channel=null,o.subscription=null,o.actualChannel=null!=r?t:null,o.subscribedChannel=null!=r?r:t,t&&(o.channel=t.substring(0,t.lastIndexOf("-pnpres"))),r&&(o.subscription=r.substring(0,r.lastIndexOf("-pnpres"))),o.action=e.payload.action,o.state=e.payload.data,o.timetoken=i.publishTimetoken,o.occupancy=e.payload.occupancy,o.uuid=e.payload.uuid,o.timestamp=e.payload.timestamp,e.payload.join&&(o.join=e.payload.join),e.payload.leave&&(o.leave=e.payload.leave),e.payload.timeout&&(o.timeout=e.payload.timeout),n._listenerManager.announcePresence(o)}else{var s={};s.channel=null,s.subscription=null,s.actualChannel=null!=r?t:null,s.subscribedChannel=null!=r?r:t,s.channel=t,s.subscription=r,s.timetoken=i.publishTimetoken,s.publisher=e.issuingClientId,e.userMetadata&&(s.userMetadata=e.userMetadata),n._config.cipherKey?s.message=n._crypto.decrypt(e.payload):s.message=e.payload,n._listenerManager.announceMessage(s)}}),this._region=t.metadata.region,this._startSubscribeLoop()}}},{key:"_stopSubscribeLoop",value:function(){this._subscribeCall&&(this._subscribeCall.abort(),this._subscribeCall=null)}}]),e}();t.default=c,e.exports=t.default},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=function(){function e(e,t){for(var n=0;n=this._config.maximumCacheSize&&this.hashHistory.shift(),this.hashHistory.push(this.getKey(e))}},{key:"clearHistory",value:function(){this.hashHistory=[]}}]),e}();t.default=o,e.exports=t.default},function(e,t){"use strict";function n(e){return encodeURIComponent(e).replace(/[!~*'()]/g,function(e){return"%"+e.charCodeAt(0).toString(16).toUpperCase()})}e.exports={signPamFromParams:function(e){return function(e){return function(e){var t=[];return Object.keys(e).forEach(function(e){return t.push(e)}),t}(e).sort()}(e).map(function(t){return t+"="+n(e[t])}).join("&")},endsWith:function(e,t){return-1!==e.indexOf(t,this.length-t.length)},createPromise:function(){var e=void 0,t=void 0;return{promise:new Promise(function(n,r){e=n,t=r}),reject:t,fulfill:e}},encodeString:n}},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}function i(e){return function(e,t){return e.type=t,e.error=!0,e}({message:e},"validationError")}Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e,t){var n=e.networking,r=e.config,c=null,l=null,f={};t.getOperation()===a.default.PNTimeOperation||t.getOperation()===a.default.PNChannelGroupsOperation?c=arguments.length<=2?void 0:arguments[2]:(f=arguments.length<=2?void 0:arguments[2],c=arguments.length<=3?void 0:arguments[3]),"undefined"==typeof Promise||c||(l=s.default.createPromise());var h=t.validateParams(e,f);if(!h){var p=t.prepareParams(e,f),d=function(e,t,n){return e.usePost&&e.usePost(t,n)?e.postURL(t,n):e.getURL(t,n)}(t,e,f),g=void 0,y={url:d,operation:t.getOperation(),timeout:t.getRequestTimeout(e)};p.uuid=r.UUID,p.pnsdk=function(e){var t="PubNub-JS-"+e.sdkFamily;return e.partnerId&&(t+="-"+e.partnerId),t+="/"+e.getVersion()}(r),r.useInstanceId&&(p.instanceid=r.instanceId),r.useRequestId&&(p.requestid=o.default.createUUID()),t.isAuthSupported()&&r.getAuthKey()&&(p.auth=r.getAuthKey()),r.secretKey&&function(e,t,n){var r=e.config,i=e.crypto;n.timestamp=Math.floor((new Date).getTime()/1e3);var o=r.subscribeKey+"\n"+r.publishKey+"\n"+t+"\n";o+=s.default.signPamFromParams(n);var a=i.HMACSHA256(o);a=(a=a.replace(/\+/g,"-")).replace(/\//g,"_"),n.signature=a}(e,d,p);var v=function(n,r){if(n.error)c?c(n):l&&l.reject(new u("PubNub call failed, check status for details",n));else{var i=t.handleResponse(e,r,f);c?c(n,i):l&&l.fulfill(i)}};if(t.usePost&&t.usePost(e,f)){var b=t.postPayload(e,f);g=n.POST(p,b,y,v)}else g=t.useDelete&&t.useDelete()?n.DELETE(p,y,v):n.GET(p,y,v);return t.getOperation()===a.default.PNSubscribeOperation?g:l?l.promise:void 0}return c?c(i(h)):l?(l.reject(new u("Validation failed, check status for details",i(h))),l.promise):void 0};var o=r(n(3)),s=r((n(5),n(15))),a=r((r(n(2)),n(13))),u=function(e){function t(e,n){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,t);var r=function(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));return r.name=r.constructor.name,r.status=n,r.message=e,r}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}(t,Error),t}();e.exports=t.default},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0}),t.getOperation=function(){return i.default.PNAddChannelsToGroupOperation},t.validateParams=function(e,t){var n=t.channels,r=t.channelGroup,i=e.config;return r?n&&0!==n.length?i.subscribeKey?void 0:"Missing Subscribe Key":"Missing Channels":"Missing Channel Group"},t.getURL=function(e,t){var n=t.channelGroup;return"/v1/channel-registration/sub-key/"+e.config.subscribeKey+"/channel-group/"+o.default.encodeString(n)},t.getRequestTimeout=function(e){return e.config.getTransactionTimeout()},t.isAuthSupported=function(){return!0},t.prepareParams=function(e,t){var n=t.channels;return{add:(void 0===n?[]:n).join(",")}},t.handleResponse=function(){return{}};var i=r((n(5),n(13))),o=r(n(15))},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0}),t.getOperation=function(){return i.default.PNRemoveChannelsFromGroupOperation},t.validateParams=function(e,t){var n=t.channels,r=t.channelGroup,i=e.config;return r?n&&0!==n.length?i.subscribeKey?void 0:"Missing Subscribe Key":"Missing Channels":"Missing Channel Group"},t.getURL=function(e,t){var n=t.channelGroup;return"/v1/channel-registration/sub-key/"+e.config.subscribeKey+"/channel-group/"+o.default.encodeString(n)},t.getRequestTimeout=function(e){return e.config.getTransactionTimeout()},t.isAuthSupported=function(){return!0},t.prepareParams=function(e,t){var n=t.channels;return{remove:(void 0===n?[]:n).join(",")}},t.handleResponse=function(){return{}};var i=r((n(5),n(13))),o=r(n(15))},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0}),t.getOperation=function(){return i.default.PNRemoveGroupOperation},t.validateParams=function(e,t){var n=t.channelGroup,r=e.config;return n?r.subscribeKey?void 0:"Missing Subscribe Key":"Missing Channel Group"},t.getURL=function(e,t){var n=t.channelGroup;return"/v1/channel-registration/sub-key/"+e.config.subscribeKey+"/channel-group/"+o.default.encodeString(n)+"/remove"},t.isAuthSupported=function(){return!0},t.getRequestTimeout=function(e){return e.config.getTransactionTimeout()},t.prepareParams=function(){return{}},t.handleResponse=function(){return{}};var i=r((n(5),n(13))),o=r(n(15))},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getOperation=function(){return r.default.PNChannelGroupsOperation},t.validateParams=function(e){if(!e.config.subscribeKey)return"Missing Subscribe Key"},t.getURL=function(e){return"/v1/channel-registration/sub-key/"+e.config.subscribeKey+"/channel-group"},t.getRequestTimeout=function(e){return e.config.getTransactionTimeout()},t.isAuthSupported=function(){return!0},t.prepareParams=function(){return{}},t.handleResponse=function(e,t){return{groups:t.payload.groups}};var r=function(e){return e&&e.__esModule?e:{default:e}}((n(5),n(13)))},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0}),t.getOperation=function(){return i.default.PNChannelsForGroupOperation},t.validateParams=function(e,t){var n=t.channelGroup,r=e.config;return n?r.subscribeKey?void 0:"Missing Subscribe Key":"Missing Channel Group"},t.getURL=function(e,t){var n=t.channelGroup;return"/v1/channel-registration/sub-key/"+e.config.subscribeKey+"/channel-group/"+o.default.encodeString(n)},t.getRequestTimeout=function(e){return e.config.getTransactionTimeout()},t.isAuthSupported=function(){return!0},t.prepareParams=function(){return{}},t.handleResponse=function(e,t){return{channels:t.payload.channels}};var i=r((n(5),n(13))),o=r(n(15))},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getOperation=function(){return r.default.PNPushNotificationEnabledChannelsOperation},t.validateParams=function(e,t){var n=t.device,r=t.pushGateway,i=t.channels,o=e.config;return n?r?i&&0!==i.length?o.subscribeKey?void 0:"Missing Subscribe Key":"Missing Channels":"Missing GW Type (pushGateway: gcm or apns)":"Missing Device ID (device)"},t.getURL=function(e,t){var n=t.device;return"/v1/push/sub-key/"+e.config.subscribeKey+"/devices/"+n},t.getRequestTimeout=function(e){return e.config.getTransactionTimeout()},t.isAuthSupported=function(){return!0},t.prepareParams=function(e,t){var n=t.pushGateway,r=t.channels;return{type:n,add:(void 0===r?[]:r).join(",")}},t.handleResponse=function(){return{}};var r=function(e){return e&&e.__esModule?e:{default:e}}((n(5),n(13)))},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getOperation=function(){return r.default.PNPushNotificationEnabledChannelsOperation},t.validateParams=function(e,t){var n=t.device,r=t.pushGateway,i=t.channels,o=e.config;return n?r?i&&0!==i.length?o.subscribeKey?void 0:"Missing Subscribe Key":"Missing Channels":"Missing GW Type (pushGateway: gcm or apns)":"Missing Device ID (device)"},t.getURL=function(e,t){var n=t.device;return"/v1/push/sub-key/"+e.config.subscribeKey+"/devices/"+n},t.getRequestTimeout=function(e){return e.config.getTransactionTimeout()},t.isAuthSupported=function(){return!0},t.prepareParams=function(e,t){var n=t.pushGateway,r=t.channels;return{type:n,remove:(void 0===r?[]:r).join(",")}},t.handleResponse=function(){return{}};var r=function(e){return e&&e.__esModule?e:{default:e}}((n(5),n(13)))},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getOperation=function(){return r.default.PNPushNotificationEnabledChannelsOperation},t.validateParams=function(e,t){var n=t.device,r=t.pushGateway,i=e.config;return n?r?i.subscribeKey?void 0:"Missing Subscribe Key":"Missing GW Type (pushGateway: gcm or apns)":"Missing Device ID (device)"},t.getURL=function(e,t){var n=t.device;return"/v1/push/sub-key/"+e.config.subscribeKey+"/devices/"+n},t.getRequestTimeout=function(e){return e.config.getTransactionTimeout()},t.isAuthSupported=function(){return!0},t.prepareParams=function(e,t){return{type:t.pushGateway}},t.handleResponse=function(e,t){return{channels:t}};var r=function(e){return e&&e.__esModule?e:{default:e}}((n(5),n(13)))},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getOperation=function(){return r.default.PNRemoveAllPushNotificationsOperation},t.validateParams=function(e,t){var n=t.device,r=t.pushGateway,i=e.config;return n?r?i.subscribeKey?void 0:"Missing Subscribe Key":"Missing GW Type (pushGateway: gcm or apns)":"Missing Device ID (device)"},t.getURL=function(e,t){var n=t.device;return"/v1/push/sub-key/"+e.config.subscribeKey+"/devices/"+n+"/remove"},t.getRequestTimeout=function(e){return e.config.getTransactionTimeout()},t.isAuthSupported=function(){return!0},t.prepareParams=function(e,t){return{type:t.pushGateway}},t.handleResponse=function(){return{}};var r=function(e){return e&&e.__esModule?e:{default:e}}((n(5),n(13)))},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0}),t.getOperation=function(){return i.default.PNUnsubscribeOperation},t.validateParams=function(e){if(!e.config.subscribeKey)return"Missing Subscribe Key"},t.getURL=function(e,t){var n=e.config,r=t.channels,i=void 0===r?[]:r,s=i.length>0?i.join(","):",";return"/v2/presence/sub-key/"+n.subscribeKey+"/channel/"+o.default.encodeString(s)+"/leave"},t.getRequestTimeout=function(e){return e.config.getTransactionTimeout()},t.isAuthSupported=function(){return!0},t.prepareParams=function(e,t){var n=t.channelGroups,r=void 0===n?[]:n,i={};return r.length>0&&(i["channel-group"]=r.join(",")),i},t.handleResponse=function(){return{}};var i=r((n(5),n(13))),o=r(n(15))},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getOperation=function(){return r.default.PNWhereNowOperation},t.validateParams=function(e){if(!e.config.subscribeKey)return"Missing Subscribe Key"},t.getURL=function(e,t){var n=e.config,r=t.uuid,i=void 0===r?n.UUID:r;return"/v2/presence/sub-key/"+n.subscribeKey+"/uuid/"+i},t.getRequestTimeout=function(e){return e.config.getTransactionTimeout()},t.isAuthSupported=function(){return!0},t.prepareParams=function(){return{}},t.handleResponse=function(e,t){return t.payload?{channels:t.payload.channels}:{channels:[]}};var r=function(e){return e&&e.__esModule?e:{default:e}}((n(5),n(13)))},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0}),t.getOperation=function(){return i.default.PNHeartbeatOperation},t.validateParams=function(e){if(!e.config.subscribeKey)return"Missing Subscribe Key"},t.getURL=function(e,t){var n=e.config,r=t.channels,i=void 0===r?[]:r,s=i.length>0?i.join(","):",";return"/v2/presence/sub-key/"+n.subscribeKey+"/channel/"+o.default.encodeString(s)+"/heartbeat"},t.isAuthSupported=function(){return!0},t.getRequestTimeout=function(e){return e.config.getTransactionTimeout()},t.prepareParams=function(e,t){var n=t.channelGroups,r=void 0===n?[]:n,i=t.state,o=void 0===i?{}:i,s=e.config,a={};return r.length>0&&(a["channel-group"]=r.join(",")),a.state=JSON.stringify(o),a.heartbeat=s.getPresenceTimeout(),a},t.handleResponse=function(){return{}};var i=r((n(5),n(13))),o=r(n(15))},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0}),t.getOperation=function(){return i.default.PNGetStateOperation},t.validateParams=function(e){if(!e.config.subscribeKey)return"Missing Subscribe Key"},t.getURL=function(e,t){var n=e.config,r=t.uuid,i=void 0===r?n.UUID:r,s=t.channels,a=void 0===s?[]:s,u=a.length>0?a.join(","):",";return"/v2/presence/sub-key/"+n.subscribeKey+"/channel/"+o.default.encodeString(u)+"/uuid/"+i},t.getRequestTimeout=function(e){return e.config.getTransactionTimeout()},t.isAuthSupported=function(){return!0},t.prepareParams=function(e,t){var n=t.channelGroups,r=void 0===n?[]:n,i={};return r.length>0&&(i["channel-group"]=r.join(",")),i},t.handleResponse=function(e,t,n){var r=n.channels,i=void 0===r?[]:r,o=n.channelGroups,s=void 0===o?[]:o,a={};return 1===i.length&&0===s.length?a[i[0]]=t.payload:a=t.payload,{channels:a}};var i=r((n(5),n(13))),o=r(n(15))},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0}),t.getOperation=function(){return i.default.PNSetStateOperation},t.validateParams=function(e,t){var n=e.config,r=t.state,i=t.channels,o=void 0===i?[]:i,s=t.channelGroups,a=void 0===s?[]:s;return r?n.subscribeKey?0===o.length&&0===a.length?"Please provide a list of channels and/or channel-groups":void 0:"Missing Subscribe Key":"Missing State"},t.getURL=function(e,t){var n=e.config,r=t.channels,i=void 0===r?[]:r,s=i.length>0?i.join(","):",";return"/v2/presence/sub-key/"+n.subscribeKey+"/channel/"+o.default.encodeString(s)+"/uuid/"+n.UUID+"/data"},t.getRequestTimeout=function(e){return e.config.getTransactionTimeout()},t.isAuthSupported=function(){return!0},t.prepareParams=function(e,t){var n=t.state,r=t.channelGroups,i=void 0===r?[]:r,o={};return o.state=JSON.stringify(n),i.length>0&&(o["channel-group"]=i.join(",")),o},t.handleResponse=function(e,t){return{state:t.payload}};var i=r((n(5),n(13))),o=r(n(15))},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0}),t.getOperation=function(){return i.default.PNHereNowOperation},t.validateParams=function(e){if(!e.config.subscribeKey)return"Missing Subscribe Key"},t.getURL=function(e,t){var n=e.config,r=t.channels,i=void 0===r?[]:r,s=t.channelGroups,a=void 0===s?[]:s,u="/v2/presence/sub-key/"+n.subscribeKey;if(i.length>0||a.length>0){var c=i.length>0?i.join(","):",";u+="/channel/"+o.default.encodeString(c)}return u},t.getRequestTimeout=function(e){return e.config.getTransactionTimeout()},t.isAuthSupported=function(){return!0},t.prepareParams=function(e,t){var n=t.channelGroups,r=void 0===n?[]:n,i=t.includeUUIDs,o=void 0===i||i,s=t.includeState,a=void 0!==s&&s,u={};return o||(u.disable_uuids=1),a&&(u.state=1),r.length>0&&(u["channel-group"]=r.join(",")),u},t.handleResponse=function(e,t,n){var r=n.channels,i=void 0===r?[]:r,o=n.channelGroups,s=void 0===o?[]:o,a=n.includeUUIDs,u=void 0===a||a,c=n.includeState,l=void 0!==c&&c;return i.length>1||s.length>0||0===s.length&&0===i.length?function(){var e={};return e.totalChannels=t.payload.total_channels,e.totalOccupancy=t.payload.total_occupancy,e.channels={},Object.keys(t.payload.channels).forEach(function(n){var r=t.payload.channels[n],i=[];return e.channels[n]={occupants:i,name:n,occupancy:r.occupancy},u&&r.uuids.forEach(function(e){l?i.push({state:e.state,uuid:e.uuid}):i.push({state:null,uuid:e})}),e}),e}():function(){var e={},n=[];return e.totalChannels=1,e.totalOccupancy=t.occupancy,e.channels={},e.channels[i[0]]={occupants:n,name:i[0],occupancy:t.occupancy},u&&t.uuids&&t.uuids.forEach(function(e){l?n.push({state:e.state,uuid:e.uuid}):n.push({state:null,uuid:e})}),e}()};var i=r((n(5),n(13))),o=r(n(15))},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getOperation=function(){return r.default.PNAccessManagerAudit},t.validateParams=function(e){if(!e.config.subscribeKey)return"Missing Subscribe Key"},t.getURL=function(e){return"/v2/auth/audit/sub-key/"+e.config.subscribeKey},t.getRequestTimeout=function(e){return e.config.getTransactionTimeout()},t.isAuthSupported=function(){return!1},t.prepareParams=function(e,t){var n=t.channel,r=t.channelGroup,i=t.authKeys,o=void 0===i?[]:i,s={};return n&&(s.channel=n),r&&(s["channel-group"]=r),o.length>0&&(s.auth=o.join(",")),s},t.handleResponse=function(e,t){return t.payload};var r=function(e){return e&&e.__esModule?e:{default:e}}((n(5),n(13)))},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getOperation=function(){return r.default.PNAccessManagerGrant},t.validateParams=function(e){var t=e.config;return t.subscribeKey?t.publishKey?t.secretKey?void 0:"Missing Secret Key":"Missing Publish Key":"Missing Subscribe Key"},t.getURL=function(e){return"/v2/auth/grant/sub-key/"+e.config.subscribeKey},t.getRequestTimeout=function(e){return e.config.getTransactionTimeout()},t.isAuthSupported=function(){return!1},t.prepareParams=function(e,t){var n=t.channels,r=void 0===n?[]:n,i=t.channelGroups,o=void 0===i?[]:i,s=t.ttl,a=t.read,u=void 0!==a&&a,c=t.write,l=void 0!==c&&c,f=t.manage,h=void 0!==f&&f,p=t.authKeys,d=void 0===p?[]:p,g={};return g.r=u?"1":"0",g.w=l?"1":"0",g.m=h?"1":"0",r.length>0&&(g.channel=r.join(",")),o.length>0&&(g["channel-group"]=o.join(",")),d.length>0&&(g.auth=d.join(",")),(s||0===s)&&(g.ttl=s),g},t.handleResponse=function(){return{}};var r=function(e){return e&&e.__esModule?e:{default:e}}((n(5),n(13)))},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}function i(e,t){var n=e.crypto,r=e.config,i=JSON.stringify(t);return r.cipherKey&&(i=n.encrypt(i),i=JSON.stringify(i)),i}Object.defineProperty(t,"__esModule",{value:!0});var o="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e};t.getOperation=function(){return s.default.PNPublishOperation},t.validateParams=function(e,t){var n=e.config,r=t.message;return t.channel?r?n.subscribeKey?void 0:"Missing Subscribe Key":"Missing Message":"Missing Channel"},t.usePost=function(e,t){var n=t.sendByPost;return void 0!==n&&n},t.getURL=function(e,t){var n=e.config,r=t.channel,o=i(e,t.message);return"/publish/"+n.publishKey+"/"+n.subscribeKey+"/0/"+a.default.encodeString(r)+"/0/"+a.default.encodeString(o)},t.postURL=function(e,t){var n=e.config,r=t.channel;return"/publish/"+n.publishKey+"/"+n.subscribeKey+"/0/"+a.default.encodeString(r)+"/0"},t.getRequestTimeout=function(e){return e.config.getTransactionTimeout()},t.isAuthSupported=function(){return!0},t.postPayload=function(e,t){return i(e,t.message)},t.prepareParams=function(e,t){var n=t.meta,r=t.replicate,i=void 0===r||r,s=t.storeInHistory,a=t.ttl,u={};return null!=s&&(u.store=s?"1":"0"),a&&(u.ttl=a),!1===i&&(u.norep="true"),n&&"object"===(void 0===n?"undefined":o(n))&&(u.meta=JSON.stringify(n)),u},t.handleResponse=function(e,t){return{timetoken:t[2]}};var s=r((n(5),n(13))),a=r(n(15))},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0}),t.getOperation=function(){return i.default.PNHistoryOperation},t.validateParams=function(e,t){var n=t.channel,r=e.config;return n?r.subscribeKey?void 0:"Missing Subscribe Key":"Missing channel"},t.getURL=function(e,t){var n=t.channel;return"/v2/history/sub-key/"+e.config.subscribeKey+"/channel/"+o.default.encodeString(n)},t.getRequestTimeout=function(e){return e.config.getTransactionTimeout()},t.isAuthSupported=function(){return!0},t.prepareParams=function(e,t){var n=t.start,r=t.end,i=t.reverse,o=t.count,s=void 0===o?100:o,a=t.stringifiedTimeToken,u=void 0!==a&&a,c={include_token:"true"};return c.count=s,n&&(c.start=n),r&&(c.end=r),u&&(c.string_message_token="true"),null!=i&&(c.reverse=i.toString()),c},t.handleResponse=function(e,t){var n={messages:[],startTimeToken:t[1],endTimeToken:t[2]};return t[0].forEach(function(t){var r={timetoken:t.timetoken,entry:function(e,t){var n=e.config,r=e.crypto;if(!n.cipherKey)return t;try{return r.decrypt(t)}catch(e){return t}}(e,t.message)};n.messages.push(r)}),n};var i=r((n(5),n(13))),o=r(n(15))},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0}),t.getOperation=function(){return i.default.PNDeleteMessagesOperation},t.validateParams=function(e,t){var n=t.channel,r=e.config;return n?r.subscribeKey?void 0:"Missing Subscribe Key":"Missing channel"},t.useDelete=function(){return!0},t.getURL=function(e,t){var n=t.channel,r=t.start,i=t.end,s=e.config,a="";return r&&(a="?start="+r),i&&(a+=(""!==a?"&":"?")+"end="+i),"/v3/history/sub-key/"+s.subscribeKey+"/channel/"+o.default.encodeString(n)+a},t.getRequestTimeout=function(e){return e.config.getTransactionTimeout()},t.isAuthSupported=function(){return!0},t.prepareParams=function(e,t){var n=t.start,r=t.end,i={};return n&&(i.start=n),r&&(i.end=r),{}},t.handleResponse=function(e,t){return t.payload};var i=r((n(5),n(13))),o=r(n(15))},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0}),t.getOperation=function(){return i.default.PNFetchMessagesOperation},t.validateParams=function(e,t){var n=t.channels,r=e.config;return n&&0!==n.length?r.subscribeKey?void 0:"Missing Subscribe Key":"Missing channels"},t.getURL=function(e,t){var n=t.channels,r=void 0===n?[]:n,i=e.config,s=r.length>0?r.join(","):",";return"/v3/history/sub-key/"+i.subscribeKey+"/channel/"+o.default.encodeString(s)},t.getRequestTimeout=function(e){return e.config.getTransactionTimeout()},t.isAuthSupported=function(){return!0},t.prepareParams=function(e,t){var n=t.start,r=t.end,i=t.count,o={};return i&&(o.max=i),n&&(o.start=n),r&&(o.end=r),o},t.handleResponse=function(e,t){var n={channels:{}};return Object.keys(t.channels||{}).forEach(function(r){n.channels[r]=[],(t.channels[r]||[]).forEach(function(t){var i={};i.channel=r,i.subscription=null,i.timetoken=t.timetoken,i.message=function(e,t){var n=e.config,r=e.crypto;if(!n.cipherKey)return t;try{return r.decrypt(t)}catch(e){return t}}(e,t.message),n.channels[r].push(i)})}),n};var i=r((n(5),n(13))),o=r(n(15))},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0}),t.getOperation=function(){return i.default.PNSubscribeOperation},t.validateParams=function(e){if(!e.config.subscribeKey)return"Missing Subscribe Key"},t.getURL=function(e,t){var n=e.config,r=t.channels,i=void 0===r?[]:r,s=i.length>0?i.join(","):",";return"/v2/subscribe/"+n.subscribeKey+"/"+o.default.encodeString(s)+"/0"},t.getRequestTimeout=function(e){return e.config.getSubscribeTimeout()},t.isAuthSupported=function(){return!0},t.prepareParams=function(e,t){var n=e.config,r=t.channelGroups,i=void 0===r?[]:r,o=t.timetoken,s=t.filterExpression,a=t.region,u={heartbeat:n.getPresenceTimeout()};return i.length>0&&(u["channel-group"]=i.join(",")),s&&s.length>0&&(u["filter-expr"]=s),o&&(u.tt=o),a&&(u.tr=a),u},t.handleResponse=function(e,t){var n=[];t.m.forEach(function(e){var t={publishTimetoken:e.p.t,region:e.p.r},r={shard:parseInt(e.a,10),subscriptionMatch:e.b,channel:e.c,payload:e.d,flags:e.f,issuingClientId:e.i,subscribeKey:e.k,originationTimetoken:e.o,userMetadata:e.u,publishMetaData:t};n.push(r)});var r={timetoken:t.t.t,region:t.t.r};return{messages:n,metadata:r}};var i=r((n(5),n(13))),o=r(n(15))},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0});var i=function(){function e(e,t){for(var n=0;n=this._maxSubDomain&&(this._currentSubDomain=1),e=this._currentSubDomain.toString(),this._providedFQDN.replace("pubsub","ps"+e)}},{key:"shiftStandardOrigin",value:function(){var e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return this._standardOrigin=this.nextOrigin(e),this._standardOrigin}},{key:"getStandardOrigin",value:function(){return this._standardOrigin}},{key:"POST",value:function(e,t,n,r){return this._modules.post(e,t,n,r)}},{key:"GET",value:function(e,t,n){return this._modules.get(e,t,n)}},{key:"DELETE",value:function(e,t,n){return this._modules.del(e,t,n)}},{key:"_detectErrorCategory",value:function(e){if("ENOTFOUND"===e.code)return o.default.PNNetworkIssuesCategory;if("ECONNREFUSED"===e.code)return o.default.PNNetworkIssuesCategory;if("ECONNRESET"===e.code)return o.default.PNNetworkIssuesCategory;if("EAI_AGAIN"===e.code)return o.default.PNNetworkIssuesCategory;if(0===e.status||e.hasOwnProperty("status")&&void 0===e.status)return o.default.PNNetworkIssuesCategory;if(e.timeout)return o.default.PNTimeoutCategory;if(e.response){if(e.response.badRequest)return o.default.PNBadRequestCategory;if(e.response.forbidden)return o.default.PNAccessDeniedCategory}return o.default.PNUnknownCategory}}]),e}());t.default=s,e.exports=t.default},function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default={get:function(e){try{return localStorage.getItem(e)}catch(e){return null}},set:function(e,t){try{return localStorage.setItem(e,t)}catch(e){return null}}},e.exports=t.default},function(e,t,n){"use strict";function r(e,t,n){var r=this;return this._config.logVerbosity&&(e=e.use(function(e){var t=(new Date).getTime(),n=(new Date).toISOString(),r=console&&console.log?console:window&&window.console&&window.console.log?window.console:console;r.log("<<<<<"),r.log("["+n+"]","\n",e.url,"\n",e.qs),r.log("-----"),e.on("response",function(n){var i=(new Date).getTime()-t,o=(new Date).toISOString();r.log(">>>>>>"),r.log("["+o+" / "+i+"]","\n",e.url,"\n",e.qs,"\n",n.text),r.log("-----")})})),this._config.proxy&&this._modules.proxy&&(e=this._modules.proxy.call(this,e)),this._config.keepAlive&&this._modules.keepAlive&&(e=this._modules.keepAlive(e)),e.timeout(t.timeout).end(function(e,i){var o={};if(o.error=null!==e,o.operation=t.operation,i&&i.status&&(o.statusCode=i.status),e)return o.errorData=e,o.category=r._detectErrorCategory(e),n(o,null);var s=JSON.parse(i.text);return s.error&&1===s.error&&s.status&&s.message&&s.service?(o.errorData=s,o.statusCode=s.status,o.error=!0,o.category=r._detectErrorCategory(o),n(o,null)):n(o,s)})}Object.defineProperty(t,"__esModule",{value:!0}),t.get=function(e,t,n){var o=i.default.get(this.getStandardOrigin()+t.url).query(e);return r.call(this,o,t,n)},t.post=function(e,t,n,o){var s=i.default.post(this.getStandardOrigin()+n.url).query(e).send(t);return r.call(this,s,n,o)},t.del=function(e,t,n){var o=i.default.delete(this.getStandardOrigin()+t.url).query(e);return r.call(this,o,t,n)};var i=function(e){return e&&e.__esModule?e:{default:e}}(n(42));n(5)},function(e,t,n){function r(e){if(!p(e))return e;var t=[];for(var n in e)i(t,n,e[n]);return t.join("&")}function i(e,t,n){if(null!=n)if(Array.isArray(n))n.forEach(function(n){i(e,t,n)});else if(p(n))for(var r in n)i(e,t+"["+r+"]",n[r]);else e.push(encodeURIComponent(t)+"="+encodeURIComponent(n));else null===n&&e.push(encodeURIComponent(t))}function o(e){for(var t,n,r={},i=e.split("&"),o=0,s=i.length;o=300)&&(r=new Error(t.statusText||"Unsuccessful HTTP response"),r.original=e,r.response=t,r.status=t.status)}catch(e){r=e}r?n.callback(r,t):n.callback(null,t)})}function c(e,t){var n=d("DELETE",e);return t&&n.end(t),n}var l;"undefined"!=typeof window?l=window:"undefined"!=typeof self?l=self:(console.warn("Using browser-only version of superagent in non-browser environment"),l=this);var f=n(43),h=n(44),p=n(45),d=e.exports=n(46).bind(null,u);d.getXHR=function(){if(!(!l.XMLHttpRequest||l.location&&"file:"==l.location.protocol&&l.ActiveXObject))return new XMLHttpRequest;try{return new ActiveXObject("Microsoft.XMLHTTP")}catch(e){}try{return new ActiveXObject("Msxml2.XMLHTTP.6.0")}catch(e){}try{return new ActiveXObject("Msxml2.XMLHTTP.3.0")}catch(e){}try{return new ActiveXObject("Msxml2.XMLHTTP")}catch(e){}throw Error("Browser-only verison of superagent could not find XHR")};var g="".trim?function(e){return e.trim()}:function(e){return e.replace(/(^\s*|\s*$)/g,"")};d.serializeObject=r,d.parseString=o,d.types={html:"text/html",json:"application/json",xml:"application/xml",urlencoded:"application/x-www-form-urlencoded",form:"application/x-www-form-urlencoded","form-data":"application/x-www-form-urlencoded"},d.serialize={"application/x-www-form-urlencoded":r,"application/json":JSON.stringify},d.parse={"application/x-www-form-urlencoded":o,"application/json":JSON.parse},a.prototype.get=function(e){return this.header[e.toLowerCase()]},a.prototype._setHeaderProperties=function(e){var t=this.header["content-type"]||"";this.type=function(e){return e.split(/ *; */).shift()}(t);var n=function(e){return e.split(/ *; */).reduce(function(e,t){var n=t.split(/ *= */),r=n.shift(),i=n.shift();return r&&i&&(e[r]=i),e},{})}(t);for(var r in n)this[r]=n[r]},a.prototype._parseBody=function(e){var t=d.parse[this.type];return!t&&s(this.type)&&(t=d.parse["application/json"]),t&&e&&(e.length||e instanceof Object)?t(e):null},a.prototype._setStatusProperties=function(e){1223===e&&(e=204);var t=e/100|0;this.status=this.statusCode=e,this.statusType=t,this.info=1==t,this.ok=2==t,this.clientError=4==t,this.serverError=5==t,this.error=(4==t||5==t)&&this.toError(),this.accepted=202==e,this.noContent=204==e,this.badRequest=400==e,this.unauthorized=401==e,this.notAcceptable=406==e,this.notFound=404==e,this.forbidden=403==e},a.prototype.toError=function(){var e=this.req,t=e.method,n=e.url,r="cannot "+t+" "+n+" ("+this.status+")",i=new Error(r);return i.status=this.status,i.method=t,i.url=n,i},d.Response=a,f(u.prototype);for(var y in h)u.prototype[y]=h[y];u.prototype.type=function(e){return this.set("Content-Type",d.types[e]||e),this},u.prototype.responseType=function(e){return this._responseType=e,this},u.prototype.accept=function(e){return this.set("Accept",d.types[e]||e),this},u.prototype.auth=function(e,t,n){switch(n||(n={type:"basic"}),n.type){case"basic":var r=btoa(e+":"+t);this.set("Authorization","Basic "+r);break;case"auto":this.username=e,this.password=t}return this},u.prototype.query=function(e){return"string"!=typeof e&&(e=r(e)),e&&this._query.push(e),this},u.prototype.attach=function(e,t,n){return this._getFormData().append(e,t,n||t.name),this},u.prototype._getFormData=function(){return this._formData||(this._formData=new l.FormData),this._formData},u.prototype.callback=function(e,t){var n=this._callback;this.clearTimeout(),n(e,t)},u.prototype.crossDomainError=function(){var e=new Error("Request has been terminated\nPossible causes: the network is offline, Origin is not allowed by Access-Control-Allow-Origin, the page is being unloaded, etc.");e.crossDomain=!0,e.status=this.status,e.method=this.method,e.url=this.url,this.callback(e)},u.prototype._timeoutError=function(){var e=this._timeout,t=new Error("timeout of "+e+"ms exceeded");t.timeout=e,this.callback(t)},u.prototype._appendQueryString=function(){var e=this._query.join("&");e&&(this.url+=~this.url.indexOf("?")?"&"+e:"?"+e)},u.prototype.end=function(e){var t=this,n=this.xhr=d.getXHR(),r=this._timeout,i=this._formData||this._data;this._callback=e||function(){},n.onreadystatechange=function(){if(4==n.readyState){var e;try{e=n.status}catch(t){e=0}if(0==e){if(t.timedout)return t._timeoutError();if(t._aborted)return;return t.crossDomainError()}t.emit("end")}};var o=function(e,n){n.total>0&&(n.percent=n.loaded/n.total*100),n.direction=e,t.emit("progress",n)};if(this.hasListeners("progress"))try{n.onprogress=o.bind(null,"download"),n.upload&&(n.upload.onprogress=o.bind(null,"upload"))}catch(e){}if(r&&!this._timer&&(this._timer=setTimeout(function(){t.timedout=!0,t.abort()},r)),this._appendQueryString(),this.username&&this.password?n.open(this.method,this.url,!0,this.username,this.password):n.open(this.method,this.url,!0),this._withCredentials&&(n.withCredentials=!0),"GET"!=this.method&&"HEAD"!=this.method&&"string"!=typeof i&&!this._isHost(i)){var a=this._header["content-type"],u=this._serializer||d.serialize[a?a.split(";")[0]:""];!u&&s(a)&&(u=d.serialize["application/json"]),u&&(i=u(i))}for(var c in this.header)null!=this.header[c]&&n.setRequestHeader(c,this.header[c]);return this._responseType&&(n.responseType=this._responseType),this.emit("request",this),n.send(void 0!==i?i:null),this},d.Request=u,d.get=function(e,t,n){var r=d("GET",e);return"function"==typeof t&&(n=t,t=null),t&&r.query(t),n&&r.end(n),r},d.head=function(e,t,n){var r=d("HEAD",e);return"function"==typeof t&&(n=t,t=null),t&&r.send(t),n&&r.end(n),r},d.options=function(e,t,n){var r=d("OPTIONS",e);return"function"==typeof t&&(n=t,t=null),t&&r.send(t),n&&r.end(n),r},d.del=c,d.delete=c,d.patch=function(e,t,n){var r=d("PATCH",e);return"function"==typeof t&&(n=t,t=null),t&&r.send(t),n&&r.end(n),r},d.post=function(e,t,n){var r=d("POST",e);return"function"==typeof t&&(n=t,t=null),t&&r.send(t),n&&r.end(n),r},d.put=function(e,t,n){var r=d("PUT",e);return"function"==typeof t&&(n=t,t=null),t&&r.send(t),n&&r.end(n),r}},function(e,t,n){function r(e){if(e)return function(e){for(var t in r.prototype)e[t]=r.prototype[t];return e}(e)}e.exports=r,r.prototype.on=r.prototype.addEventListener=function(e,t){return this._callbacks=this._callbacks||{},(this._callbacks["$"+e]=this._callbacks["$"+e]||[]).push(t),this},r.prototype.once=function(e,t){function n(){this.off(e,n),t.apply(this,arguments)}return n.fn=t,this.on(e,n),this},r.prototype.off=r.prototype.removeListener=r.prototype.removeAllListeners=r.prototype.removeEventListener=function(e,t){if(this._callbacks=this._callbacks||{},0==arguments.length)return this._callbacks={},this;var n=this._callbacks["$"+e];if(!n)return this;if(1==arguments.length)return delete this._callbacks["$"+e],this;for(var r,i=0;i3)for(t=new Array(a),i=0;i3)for(t=new Array(a-1),i=1;i3)for(t=new Array(u),i=1;i3)for(t=new Array(u-1),i=1;i0&&o._listeners.length>this._events.maxListeners&&(o._listeners.warned=!0,a.call(this,o._listeners.length,s))):o._listeners=t,!0;s=e.shift()}return!0}.call(this,e,t),this):(this._events[e]?("function"==typeof this._events[e]&&(this._events[e]=[this._events[e]]),this._events[e].push(t),!this._events[e].warned&&this._events.maxListeners>0&&this._events[e].length>this._events.maxListeners&&(this._events[e].warned=!0,a.call(this,this._events[e].length,e))):this._events[e]=t,this)},u.prototype.onAny=function(e){if("function"!=typeof e)throw new Error("onAny only accepts instances of Function");return this._all||(this._all=[]),this._all.push(e),this},u.prototype.addListener=u.prototype.on,u.prototype.off=function(e,t){function n(e){if(e!==i){var t=Object.keys(e);for(var r in t){var o=t[r],s=e[o];s instanceof Function||"object"!=typeof s||null===s||(Object.keys(s).length>0&&n(e[o]),0===Object.keys(s).length&&delete e[o])}}}if("function"!=typeof t)throw new Error("removeListener only takes instances of Function");var r,o=[];if(this.wildcard){var s="string"==typeof e?e.split(this.delimiter):e.slice();o=c.call(this,null,s,this.listenerTree,0)}else{if(!this._events[e])return this;r=this._events[e],o.push({_listeners:r})}for(var a=0;a0){for(n=0,r=(t=this._all).length;n{this.userUpdate(e.uuid,e.state)})}}objectify(){return{channel:this.channel,group:this.group,private:this.isPrivate,meta:this.meta}}invite(e){this.chatEngine.request("post","invite",{to:e.uuid,chat:this.objectify()}).then(()=>{let t=()=>{e.direct.emit("$.invite",{channel:this.channel})};e.direct.connected?t():(e.direct.connect(),e.direct.on("$.connected",t))}).catch(e=>{this.chatEngine.throwError(this,"trigger","auth",new Error("Something went wrong while making a request to authentication server."),{error:e})})}onPresence(e){if("join"===e.action){let t=this.createUser(e.uuid,e.state);this.users[t.uuid]||this.trigger("$.online.join",{user:t})}"leave"===e.action&&this.userLeave(e.uuid),"timeout"===e.action&&this.userDisconnect(e.uuid),"state-change"===e.action&&this.userUpdate(e.uuid,e.state)}update(e){let t=this.meta||{};this.meta=Object.assign(t,e),this.chatEngine.request("post","chat",{chat:this.objectify()}).then(()=>{}).catch(e=>{this.chatEngine.throwError(this,"trigger","auth",new Error("Something went wrong while making a request to authentication server."),{error:e})})}emit(e,t){if("message"===e&&"object"!=typeof t)throw new Error("the payload has to be an object");let n={data:t,sender:this.chatEngine.me.uuid,chat:this,event:e,chatengineSDK:this.chatEngine.package.version};this.runPluginQueue("emit",e,e=>{e(null,n)},(t,n)=>{delete n.chat,this.events[e]=this.events[e]||new o(this.chatEngine,this,e),this.events[e].publish(n)})}createUser(e,t){return this.chatEngine.users[e]=this.chatEngine.users[e]||new this.chatEngine.User(e),this.chatEngine.users[e].assign(t),this.users[e]||this.trigger("$.online.here",{user:this.chatEngine.users[e]}),this.users[e]=this.chatEngine.users[e],this.chatEngine.users[e]}userUpdate(e,t){this.chatEngine.users[e]=this.chatEngine.users[e]||new this.chatEngine.User(e),this.users[e]||this.createUser(e,t),this.users[e].assign(t),this.chatEngine._emit("$.state",{user:this.users[e],state:this.users[e].state})}leave(){this.chatEngine.pubnub.unsubscribe({channels:[this.channel]}),this.chatEngine.request("post","leave",{chat:this.objectify()}).then(()=>{this.connected=!1,this.trigger("$.disconnected"),this.chatEngine.me.sync.emit("$.session.chat.leave",{subject:this.objectify()})}).catch(e=>{this.chatEngine.throwError(this,"trigger","auth",new Error("Something went wrong while making a request to chat server."),{error:e})})}userLeave(e){this.users[e]&&(this.trigger("$.offline.leave",{user:this.users[e]}),delete this.users[e])}userDisconnect(e){this.users[e]&&this.trigger("$.offline.disconnect",{user:this.users[e]})}setState(e){this.chatEngine.pubnub.setState({state:e,channels:[this.chatEngine.global.channel]},()=>{})}search(e){return new s(this.chatEngine,this,e)}onConnectionReady(){this.trigger("$.connected"),this.chatEngine.me.sync.emit("$.session.chat.join",{subject:this.objectify()}),this.connected=!0,this.users[this.chatEngine.me.uuid]=this.chatEngine.me,this.trigger("$.online.join",{user:this.chatEngine.me}),this.channel!==this.chatEngine.global.channel&&"custom"===this.group&&(this.getUserUpdates(),setTimeout(()=>{this.getUserUpdates()},5e3))}getUserUpdates(){this.chatEngine.pubnub.hereNow({channels:[this.channel],includeUUIDs:!0,includeState:!0},this.onHereNow.bind(this))}connect(){r.waterfall([e=>{this.chatEngine.pubnub?e():e("You must call ChatEngine.connect() and wait for the $.ready event before creating new Chats.")},e=>{this.chatEngine.request("post","grant",{chat:this.objectify()}).then(()=>{e()}).catch(e)},e=>{this.chatEngine.request("post","join",{chat:this.objectify()}).then(()=>{e()}).catch(e)},e=>{this.chatEngine.request("get","chat",{},{channel:this.channel}).then(e=>{e.data.found?this.meta=e.data.chat.meta:this.update(this.meta),this.onConnectionReady()}).catch(e)}],e=>{this.chatEngine.throwError(this,"trigger","auth",new Error("Something went wrong while making a request to authentication server."),{error:e})})}}e.exports=a},function(e,t,n){(function(e,t){!function(e,n){"use strict";function r(e){delete a[e]}function i(e){if(u)setTimeout(i,0,e);else{var t=a[e];if(t){u=!0;try{!function(e){var t=e.callback,r=e.args;switch(r.length){case 0:t();break;case 1:t(r[0]);break;case 2:t(r[0],r[1]);break;case 3:t(r[0],r[1],r[2]);break;default:t.apply(n,r)}}(t)}finally{r(e),u=!1}}}}if(!e.setImmediate){var o,s=1,a={},u=!1,c=e.document,l=Object.getPrototypeOf&&Object.getPrototypeOf(e);l=l&&l.setTimeout?l:e,"[object process]"==={}.toString.call(e.process)?o=function(e){t.nextTick(function(){i(e)})}:function(){if(e.postMessage&&!e.importScripts){var t=!0,n=e.onmessage;return e.onmessage=function(){t=!1},e.postMessage("","*"),e.onmessage=n,t}}()?function(){var t="setImmediate$"+Math.random()+"$",n=function(n){n.source===e&&"string"==typeof n.data&&0===n.data.indexOf(t)&&i(+n.data.slice(t.length))};e.addEventListener?e.addEventListener("message",n,!1):e.attachEvent("onmessage",n),o=function(n){e.postMessage(t+n,"*")}}():e.MessageChannel?function(){var e=new MessageChannel;e.port1.onmessage=function(e){i(e.data)},o=function(t){e.port2.postMessage(t)}}():c&&"onreadystatechange"in c.createElement("script")?function(){var e=c.documentElement;o=function(t){var n=c.createElement("script");n.onreadystatechange=function(){i(t),n.onreadystatechange=null,e.removeChild(n),n=null},e.appendChild(n)}}():o=function(e){setTimeout(i,0,e)},l.setImmediate=function(e){"function"!=typeof e&&(e=new Function(""+e));for(var t=new Array(arguments.length-1),n=0;n(e.sort((e,n)=>{let r=t?n:e,i=t?e:n;return parseInt(r.timetoken,10)-parseInt(i.timetoken,10)}),e)),this.page=(e=>{this._emit("$.search.page.request"),this.config.start=this.config.reverse?this.lastTT:this.firstTT,this.firstPage=!1,this.chatEngine.pubnub.history(this.config,(t,n)=>{this._emit("$.search.page.response"),t.error?this.chatEngine.throwError(this,"trigger","search",new Error("There was a problem searching history. Make sure your request parameters are valid and history is enabled for this PubNub key."),t):(this.firstTT=n.startTimeToken,this.lastTT=n.endTimeToken,n.messages=this.sortHistory(n.messages),e(n))})});this.needleCount=0,this.triggerHistory=((e,t)=>{this.needleCount{e||(this.needleCount+=1),t()}):t()}),this.maxPage=10,this.numPage=0,this.next=(()=>{this.maxPage=this.maxPage+this.config.pages,this.find()}),this.find=(()=>(this.page(e=>{this.config.reverse||e.messages.reverse(),i(e.messages,this.triggerHistory,()=>{this.numPage===this.maxPage?this._emit("$.search.pause"):e.messages&&e.messages.length===this.config.count&&this.needleCount({middleware:{on:{"*":(t,n)=>{n(!(t&&t.event&&t.event===e),t)}}}}))(this.config.event)),this.config.sender&&this.plugin((e=>({middleware:{on:{"*":(t,n)=>{n(!(t&&t.sender&&t.sender.uuid===e.uuid),t)}}}}))(this.config.sender)),this._emit("$.search.start"),this.find()}}e.exports=o},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0});var i=r(n(62)),o=r(n(87));t.default=(0,o.default)(i.default,1),e.exports=t.default},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e,t,n,r){(0,i.default)(t)(e,(0,o.default)((0,s.default)(n)),r)};var i=r(n(63)),o=r(n(86)),s=r(n(21));e.exports=t.default},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e){return function(t,n,r){function c(){for(;h-1&&e%1==0&&e{this.addChatToSession(e.data.subject)}),this.sync.on("$.session.chat.leave",e=>{this.removeChatFromSession(e.data.subject)}),this}assign(e){super.update(e)}update(e){super.update(e),this.chatEngine.global.setState(e)}addChatToSession(e){this.session[e.group]=this.session[e.group]||{};let t=this.chatEngine.chats[e.channel];t?this.session[e.group][e.channel]=t:(this.session[e.group][e.channel]=new this.chatEngine.Chat(e.channel,e.private,!1,e.meta,e.group),this.trigger("$.session.chat.join",{chat:this.session[e.group][e.channel]}))}removeChatFromSession(e){this.session[e.group]&&this.session[e.group][e.channel]&&(e=this.session[e.group][e.channel]||e,delete this.chatEngine.chats[e.channel],delete this.session[e.group][e.channel],this.trigger("$.session.chat.leave",{chat:e}))}}e.exports=i}])}); \ No newline at end of file +!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.ChatEngineCore=t():e.ChatEngineCore=t()}(this,function(){return function(e){function t(r){if(n[r])return n[r].exports;var i=n[r]={i:r,l:!1,exports:{}};return e[r].call(i.exports,i,i.exports,t),i.l=!0,i.exports}var n={};return t.m=e,t.c=n,t.d=function(e,n,r){t.o(e,n)||Object.defineProperty(e,n,{configurable:!1,enumerable:!0,get:r})},t.n=function(e){var n=e&&e.__esModule?function(){return e.default}:function(){return e};return t.d(n,"a",n),n},t.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},t.p="",t(t.s=30)}([function(e,t,n){"use strict";function r(e){return"[object Array]"===l.call(e)}function i(e){return null!==e&&"object"==typeof e}function o(e){return"[object Function]"===l.call(e)}function s(e,t){if(null!==e&&void 0!==e)if("object"==typeof e||r(e)||(e=[e]),r(e))for(var n=0,i=e.length;n1)for(var n=1;n=200&&e<300}};a.headers={common:{Accept:"application/json, text/plain, */*"}},i.forEach(["delete","get","head"],function(e){a.headers[e]={}}),i.forEach(["post","put","patch"],function(e){a.headers[e]=i.merge(s)}),e.exports=a}).call(t,n(1))},function(e,t){var n;n=function(){return this}();try{n=n||Function("return this")()||(0,eval)("this")}catch(e){"object"==typeof window&&(n=window)}e.exports=n},function(e,t){e.exports=function(e){return e.webpackPolyfill||(e.deprecate=function(){},e.paths=[],e.children||(e.children=[]),Object.defineProperty(e,"loaded",{enumerable:!0,get:function(){return e.l}}),Object.defineProperty(e,"id",{enumerable:!0,get:function(){return e.i}}),e.webpackPolyfill=1),e}},function(e,t,n){const r=n(56),i=n(14),o=n(23);class s extends i{constructor(e){super(),this.chatEngine=e,this.name="Emitter",this.plugins=[],this._dataset={},this._emit=((e,t={})=>(this.chatEngine._emit(e,t,this),this.emitter.emit(e,t),this)),this.on=((e,t)=>(this.events[e]=this.events[e]||new o(this.chatEngine,this,e),this._on(e,t),this))}addChild(e,t){this[e]=t,this._dataset[e]||(this._dataset[e]={}),t.parent=this,t.get=this.get.bind(this._dataset[e]),t.set=this.set.bind(this._dataset[e])}get(e){return this[e]}set(e,t){this[e]&&!t?delete this[e]:this[e]=t}plugin(e){return this.plugins.push(e),e.extends&&e.extends[this.name]&&(this.addChild(e.namespace,new e.extends[this.name]),this[e.namespace].ChatEngine=this.chatEngine,this[e.namespace].construct&&this[e.namespace].construct()),this}bindProtoPlugins(){this.chatEngine.protoPlugins[this.name]&&this.chatEngine.protoPlugins[this.name].forEach(e=>{this.plugin(e)})}trigger(e,t={},n=(()=>{})){let r=()=>{this.runPluginQueue("on",e,e=>{e(null,t)},(t,r)=>{t?n(t):(this._emit(e,r),n(null,e,r))})};"object"==typeof t?(t.chat||(t.chat=this),t.sender?(t.sender=new this.chatEngine.User(t.sender),t.sender._getState(()=>{r()})):r()):r()}runPluginQueue(e,t,n,i){let o=[];o.push(n),this.plugins.forEach(n=>{n.middleware&&n.middleware[e]&&(n.middleware[e][t]&&o.push(n.middleware[e][t]),n.middleware[e]["*"]&&o.push(n.middleware[e]["*"]))}),r(o,i)}onConstructed(){this.bindProtoPlugins(),this.trigger(["$","created",this.name.toLowerCase()].join("."))}}e.exports=s},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e,t){t|=0;for(var n=Math.max(e.length-t,0),r=Array(n),i=0;i(this.emitter.on(e,t),this)),this.off=((e,t)=>(this.emitter.off(e,t),this)),this.onAny=((e,t)=>(this.emitter.onAny(e,t),this)),this.once=((e,t)=>(this.emitter.once(e,t),this))}}e.exports=i},function(e,t,n){(function(e,n,r,i){!function(e,n){n(t)}(0,function(t){"use strict";function o(e,t){t|=0;for(var n=Math.max(e.length-t,0),r=Array(n),i=0;i-1&&e%1==0&&e<=Ve}function y(e){return null!=e&&g(e.length)&&!function(e){if(!s(e))return!1;var t=d(e);return t==ze||t==$e||t==He||t==Xe}(e)}function v(){}function b(e){return function(){if(null!==e){var t=e;e=null,t.apply(this,arguments)}}}function m(e){return null!=e&&"object"==typeof e}function _(e){return m(e)&&d(e)==Ye}function w(e){return y(e)?function(e,t){var n=rt(e),r=!n&&nt(e),i=!n&&!r&&at(e),o=!n&&!r&&!i&&yt(e),s=n||r||i||o,a=s?function(e,t){for(var n=-1,r=Array(e);++n-1&&e%1==0&&e0?r:e);else if(s)n[t]=e;else{if(i=function(e){return e=e.toString().replace(Jt,""),e=e.match(Xt)[2].replace(" ",""),e=e?e.split(Vt):[],e=e.map(function(e){return function(e,t,n){if((e=function(e){return null==e?"":N(e)}(e))&&(n||void 0===t))return e.replace($t,"");if(!e||!(t=N(t)))return e;var r=L(e),i=L(t);return function(e,t,n){var r=e.length;return n=void 0===n?r:n,!t&&n>=r?e:function(e,t,n){var r=-1,i=e.length;t<0&&(t=-t>i?0:i+t),(n=n>i?i:n)<0&&(n+=i),i=t>n?0:n-t>>>0,t>>>=0;for(var o=Array(i);++r-1;);return n}(r,i),function(e,t){for(var n=e.length;n--&&M(t,e[n],0)>-1;);return n}(r,i)+1).join("")}(e.replace(Wt,""))})}(e),0===e.length&&!o&&0===i.length)throw new Error("autoInject task functions require explicit parameters.");o||i.pop(),n[t]=i.concat(r)}}),Ct(n,t)}function D(){this.head=this.tail=null,this.length=0}function U(e,t){e.length=1,e.head=e.tail=t}function I(e,t,n){function r(e,t,n){if(null!=n&&"function"!=typeof n)throw new Error("task callback must be a function");if(u.started=!0,rt(e)||(e=[e]),0===e.length&&u.idle())return Ce(function(){u.drain()});for(var r=0,i=e.length;r=0&&s.splice(a,1),i.callback.apply(i,arguments),null!=t&&u.error(t,i.data)}o<=u.concurrency-u.buffer&&u.unsaturated(),u.idle()&&u.drain(),u.process()}}(e));i(t,l)}a=!1}},length:function(){return u._tasks.length},running:function(){return o},workersList:function(){return s},idle:function(){return u._tasks.length+o===0},pause:function(){u.paused=!0},resume:function(){!1!==u.paused&&(u.paused=!1,Ce(u.process))}};return u}function K(e,t){return I(e,1,t)}function B(e,t,n,r){r=b(r||v);var i=h(n);Yt(e,function(e,n,r){i(t,e,function(e,n){t=n,r(e)})},function(e){r(e,t)})}function F(){var e=A(arguments,h);return function(){var t=o(arguments),n=this,r=t[t.length-1];"function"==typeof r?t.pop():r=v,B(e,t,function(e,t,r){t.apply(n,e.concat(function(e){var t=o(arguments,1);r(e,t)}))},function(e,t){r.apply(n,[e].concat(t))})}}function q(e){return e}function G(e,t){return function(n,r,i,o){o=o||v;var s,a=!1;n(r,function(n,r,o){i(n,function(r,i){r?o(r):e(i)&&!s?(a=!0,s=t(!0,n),o(null,We)):o()})},function(e){e?o(e):o(null,a?s:t(!1))})}}function H(e,t){return t}function z(e){return function(t){var n=o(arguments,1);n.push(function(t){var n=o(arguments,1);"object"==typeof console&&(t?console.error&&console.error(t):console[e]&&j(n,function(t){console[e](t)}))}),h(t).apply(null,n)}}function $(e,t,n){function r(e,t){return e?n(e):t?void i(function(e){if(e)return n(e);var t=o(arguments,1);t.push(r),s.apply(this,t)}):n(null)}n=k(n||v);var i=h(e),s=h(t);r(null,!0)}function X(e,t,n){n=k(n||v);var r=h(e),i=function(e){if(e)return n(e);var s=o(arguments,1);if(t.apply(this,s))return r(i);n.apply(null,[null].concat(s))};r(i)}function V(e,t,n){X(e,function(){return!t.apply(this,arguments)},n)}function W(e,t,n){function r(e,t){return e?n(e):t?void i(function(e){if(e)return n(e);o(r)}):n(null)}n=k(n||v);var i=h(t),o=h(e);o(r)}function J(e){return function(t,n,r){return e(t,r)}}function Q(e,t,n){kt(e,J(h(t)),n)}function Y(e,t,n,r){E(t)(e,J(h(n)),r)}function Z(e){return f(e)?e:xe(function(t,n){var r=!0;t.push(function(){var e=arguments;r?Ce(function(){n.apply(null,e)}):n.apply(null,e)}),e.apply(this,t),r=!1})}function ee(e){return!e}function te(e){return function(t){return null==t?void 0:t[e]}}function ne(e,t,n,r){(y(t)?function(e,t,n,r){var i=new Array(t.length);e(t,function(e,t,r){n(e,function(e,n){i[t]=!!n,r(e)})},function(e){if(e)return r(e);for(var n=[],o=0;o2&&(i=o(arguments,1)),r[t]=i,n(e)})},function(e){n(e,r)})}function ue(e,t){ae(kt,e,t)}function ce(e,t,n){ae(E(t),e,n)}function le(e,t){if(t=b(t||v),!rt(e))return t(new TypeError("First argument to race must be an array of functions"));if(!e.length)return t();for(var n=0,r=e.length;nr?1:0}),te("value")))})}function me(e,t,n){var r=h(e);return xe(function(i,o){var s,a=!1;i.push(function(){a||(o.apply(null,arguments),clearTimeout(s))}),s=setTimeout(function(){var t=e.name||"anonymous",r=new Error('Callback function "'+t+'" timed out.');r.code="ETIMEDOUT",n&&(r.info=n),a=!0,o(r)},t),r.apply(null,i)})}function _e(e,t,n,r){var i=h(n);Pt(function(e,t,n,r){for(var i=-1,o=Ln(Nn((t-e)/(n||1)),0),s=Array(o);o--;)s[r?o:++i]=e,e+=n;return s}(0,e,1),t,i,r)}function we(e,t,n,r){arguments.length<=3&&(r=n,n=t,t=rt(e)?[]:{}),r=b(r||v);var i=h(n);kt(e,function(e,n,r){i(t,e,n,r)},function(e){r(e,t)})}function ke(e,t){var n,r=null;t=t||v,ln(e,function(e,t){h(e)(function(e,i){n=arguments.length>2?o(arguments,1):i,r=e,t(!e)})},function(){t(r,n)})}function Ee(e){return function(){return(e.unmemoized||e).apply(null,arguments)}}function Se(e,t,n){n=k(n||v);var r=h(t);if(!e())return n(null);var i=function(t){if(t)return n(t);if(e())return r(i);var s=o(arguments,1);n.apply(null,[null].concat(s))};r(i)}function Pe(e,t,n){Se(function(){return!e.apply(this,arguments)},t,n)}var Oe,xe=function(e){return function(){var t=o(arguments),n=t.pop();e.call(this,t,n)}},Te="function"==typeof e&&e,je="object"==typeof n&&"function"==typeof n.nextTick,Ce=u(Oe=Te?e:je?n.nextTick:a),Me="function"==typeof Symbol,Ae="object"==typeof r&&r&&r.Object===Object&&r,Ne="object"==typeof self&&self&&self.Object===Object&&self,Le=Ae||Ne||Function("return this")(),Re=Le.Symbol,De=Object.prototype,Ue=De.hasOwnProperty,Ie=De.toString,Ke=Re?Re.toStringTag:void 0,Be=Object.prototype.toString,Fe="[object Null]",qe="[object Undefined]",Ge=Re?Re.toStringTag:void 0,He="[object AsyncFunction]",ze="[object Function]",$e="[object GeneratorFunction]",Xe="[object Proxy]",Ve=9007199254740991,We={},Je="function"==typeof Symbol&&Symbol.iterator,Qe=function(e){return Je&&e[Je]&&e[Je]()},Ye="[object Arguments]",Ze=Object.prototype,et=Ze.hasOwnProperty,tt=Ze.propertyIsEnumerable,nt=_(function(){return arguments}())?_:function(e){return m(e)&&et.call(e,"callee")&&!tt.call(e,"callee")},rt=Array.isArray,it="object"==typeof t&&t&&!t.nodeType&&t,ot=it&&"object"==typeof i&&i&&!i.nodeType&&i,st=ot&&ot.exports===it?Le.Buffer:void 0,at=(st?st.isBuffer:void 0)||function(){return!1},ut=9007199254740991,ct=/^(?:0|[1-9]\d*)$/,lt={};lt["[object Float32Array]"]=lt["[object Float64Array]"]=lt["[object Int8Array]"]=lt["[object Int16Array]"]=lt["[object Int32Array]"]=lt["[object Uint8Array]"]=lt["[object Uint8ClampedArray]"]=lt["[object Uint16Array]"]=lt["[object Uint32Array]"]=!0,lt["[object Arguments]"]=lt["[object Array]"]=lt["[object ArrayBuffer]"]=lt["[object Boolean]"]=lt["[object DataView]"]=lt["[object Date]"]=lt["[object Error]"]=lt["[object Function]"]=lt["[object Map]"]=lt["[object Number]"]=lt["[object Object]"]=lt["[object RegExp]"]=lt["[object Set]"]=lt["[object String]"]=lt["[object WeakMap]"]=!1;var ft="object"==typeof t&&t&&!t.nodeType&&t,ht=ft&&"object"==typeof i&&i&&!i.nodeType&&i,pt=ht&&ht.exports===ft&&Ae.process,dt=function(){try{return pt&&pt.binding("util")}catch(e){}}(),gt=dt&&dt.isTypedArray,yt=gt?function(e){return function(t){return e(t)}}(gt):function(e){return m(e)&&g(e.length)&&!!lt[d(e)]},vt=Object.prototype.hasOwnProperty,bt=Object.prototype,mt=function(e,t){return function(n){return e(t(n))}}(Object.keys,Object),_t=Object.prototype.hasOwnProperty,wt=P(S,1/0),kt=function(e,t,n){(y(e)?function(e,t,n){n=b(n||v);var r=0,i=0,o=e.length;for(0===o&&n(null);r2&&(r=o(arguments,1)),t){var s={};C(a,function(e,t){s[t]=e}),s[e]=r,c=!0,l=Object.create(null),n(t,s)}else a[e]=r,function(e){j(l[e]||[],function(e){e()}),i()}(e)});u++;var s=h(t[t.length-1]);t.length>1?s(a,r):s(r)}(e,t)})}function i(){if(0===f.length&&0===u)return n(null,a);for(;f.length&&u=0&&n.push(r)}),n}(p.pop()),function(e){0==--d[e]&&p.push(e)});if(t!==s)throw new Error("async.auto cannot execute tasks due to a recursive dependency")}(),i()},Mt="[object Symbol]",At=1/0,Nt=Re?Re.prototype:void 0,Lt=Nt?Nt.toString:void 0,Rt=RegExp("[\\u200d\\ud800-\\udfff\\u0300-\\u036f\\ufe20-\\ufe23\\u20d0-\\u20f0\\ufe0e\\ufe0f]"),Dt="[\\ud800-\\udfff]",Ut="[\\u0300-\\u036f\\ufe20-\\ufe23\\u20d0-\\u20f0]",It="\\ud83c[\\udffb-\\udfff]",Kt="[^\\ud800-\\udfff]",Bt="(?:\\ud83c[\\udde6-\\uddff]){2}",Ft="[\\ud800-\\udbff][\\udc00-\\udfff]",qt="(?:"+Ut+"|"+It+")"+"?",Gt="[\\ufe0e\\ufe0f]?"+qt+("(?:\\u200d(?:"+[Kt,Bt,Ft].join("|")+")[\\ufe0e\\ufe0f]?"+qt+")*"),Ht="(?:"+[Kt+Ut+"?",Ut,Bt,Ft,Dt].join("|")+")",zt=RegExp(It+"(?="+It+")|"+Ht+Gt,"g"),$t=/^\s+|\s+$/g,Xt=/^(?:async\s+)?(function)?\s*[^\(]*\(\s*([^\)]*)\)/m,Vt=/,/,Wt=/(=.+)?(\s*)$/,Jt=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/gm;D.prototype.removeLink=function(e){return e.prev?e.prev.next=e.next:this.head=e.next,e.next?e.next.prev=e.prev:this.tail=e.prev,e.prev=e.next=null,this.length-=1,e},D.prototype.empty=function(){for(;this.head;)this.shift();return this},D.prototype.insertAfter=function(e,t){t.prev=e,t.next=e.next,e.next?e.next.prev=t:this.tail=t,e.next=t,this.length+=1},D.prototype.insertBefore=function(e,t){t.prev=e.prev,t.next=e,e.prev?e.prev.next=t:this.head=t,e.prev=t,this.length+=1},D.prototype.unshift=function(e){this.head?this.insertBefore(this.head,e):U(this,e)},D.prototype.push=function(e){this.tail?this.insertAfter(this.tail,e):U(this,e)},D.prototype.shift=function(){return this.head&&this.removeLink(this.head)},D.prototype.pop=function(){return this.tail&&this.removeLink(this.tail)},D.prototype.toArray=function(){for(var e=Array(this.length),t=this.head,n=0;n=i.priority;)i=i.next;for(var o=0,s=e.length;o=0&&(e._idleTimeoutId=setTimeout(function(){e._onTimeout&&e._onTimeout()},t))},n(55),t.setImmediate=setImmediate,t.clearImmediate=clearImmediate},function(e,t){var n=Array.isArray;e.exports=n},function(e,t){e.exports=function(){}},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e){return function(){if(null!==e){var t=e;e=null,t.apply(this,arguments)}}},e.exports=t.default},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e){return function(){if(null===e)throw new Error("Callback was already called.");var t=e;e=null,t.apply(this,arguments)}},e.exports=t.default},function(e,t,n){"use strict";function r(e){return o&&"AsyncFunction"===e[Symbol.toStringTag]}Object.defineProperty(t,"__esModule",{value:!0}),t.isAsync=void 0;var i=function(e){return e&&e.__esModule?e:{default:e}}(n(57)),o="function"==typeof Symbol;t.default=function(e){return r(e)?(0,i.default)(e):e},t.isAsync=r},function(e,t){e.exports=function(e){var t=typeof e;return null!=e&&("object"==t||"function"==t)}},function(e,t){class n{constructor(e,t,n){return this.channel=t.channel,this.chatEngine=e,this.chat=t,this.event=n,this.name="Event",this.chatEngine.pubnub.addListener({message:this.onMessage.bind(this)}),this}onMessage(e){this.channel===e.channel&&e.message.event===this.event&&this.chat.trigger(e.message.event,e.message)}publish(e){e.event=this.event,this.chatEngine.pubnub.publish({message:e,channel:this.channel},t=>{200===t.statusCode?this.chat.trigger("$.publish.success",e):this.chatEngine.throwError(this.chat,"trigger","publish",new Error("There was a problem publishing over the PubNub network."),t)})}}e.exports=n},function(e,t,n){var r=n(65),i=n(28);e.exports=function(e){return null!=e&&i(e.length)&&!r(e)}},function(e,t,n){var r=n(26).Symbol;e.exports=r},function(e,t,n){var r=n(27),i="object"==typeof self&&self&&self.Object===Object&&self,o=r||i||Function("return this")();e.exports=o},function(e,t,n){(function(t){var n="object"==typeof t&&t&&t.Object===Object&&t;e.exports=n}).call(t,n(3))},function(e,t){var n=9007199254740991;e.exports=function(e){return"number"==typeof e&&e>-1&&e%1==0&&e<=n}},function(e,t,n){const r=n(5);class i extends r{constructor(e,t,n={}){return super(),this.chatEngine=e,this.name="User",this.uuid=t,this.state={},this._stateFetched=!1,this.feed=new this.chatEngine.Chat([e.global.channel,"user",t,"read.","feed"].join("#"),!1,"Me"===this.constructor.name,{},"system"),this.direct=new this.chatEngine.Chat([e.global.channel,"user",t,"write.","direct"].join("#"),!1,"Me"===this.constructor.name,{},"system"),e.users[t]||(e.users[t]=this),this.assign(n),this}update(e){let t=this.state||{};this.state=Object.assign(t,e)}assign(e){this.update(e)}_getState(e){this._stateFetched?e(this.state):this.chatEngine.pubnub.getState({uuid:this.uuid,channels:[this.chatEngine.global.channel]},(t,n)=>{if(200===t.statusCode){let t=n.channels[this.chatEngine.global.channel];Object.keys(t).length?(this.assign(n.data),this._stateFetched=!0,e(this.state)):this.chatEngine.request("get","user_state",{user:this.uuid}).then(t=>{this.assign(t.data),this._stateFetched=!0,e(this.state)}).catch(e=>{this.chatEngine.throwError(this,"trigger","getState",e)})}else this.chatEngine.throwError(this,"trigger","getState",new Error("There was a problem getting state from the PubNub network."))})}}e.exports=i},function(e,t,n){const r=n(31);e.exports={plugin:{},create:(e,t={})=>(t.globalChannel?t.globalChannel=t.globalChannel.toString():t.globalChannel="chat-engine",void 0===t.throwErrors&&(t.throwErrors=!0),r(t,e))}},function(e,t,n){const r=n(32),i=n(51),o=n(52),s=n(14),a=n(54),u=n(88),c=n(29),l=n(15);e.exports=((e={},t={})=>{let n=new s;return n.ceConfig=e,n.pnConfig=t,n.pnConfig.heartbeatInterval=n.pnConfig.heartbeatInterval||30,n.pnConfig.presenceTimeout=n.pnConfig.presenceTimeout||60,n.ceConfig.endpoint=n.ceConfig.endpoint||"https://pubsub.pubnub.com/v1/blocks/sub-key/"+n.pnConfig.subscribeKey+"/chat-engine-server",n.ceConfig.globalChannel=n.ceConfig.globalChannel||"chat-engine-global",n.users={},n.chats={},n.global=!1,n.me=!1,n.pubnub=!1,n.ready=!1,n.package=o,n.throwError=((t,n,r,i,o={})=>{if(e.throwErrors)throw console.error(o),i;o.ceError=i.toString(),t[n](["$","error",r].join("."),o)}),e.debug&&n.onAny((e,t)=>{console.info("debug:",e,t)}),n.protoPlugins={},n.proto=((e,t)=>{n.protoPlugins[e]=n.protoPlugins[e]||[],n.protoPlugins[e].push(t)}),n.request=((i,o,s={},a={})=>{let u={uuid:t.uuid,global:e.globalChannel,authData:n.me.authData,authKey:t.authKey},c={route:o};return u=Object.assign(u,s),c=Object.assign(c,a),"get"===i||"delete"===i?(c=Object.assign(c,u),r[i](e.endpoint,{params:c})):r[i](e.endpoint,u,{params:c})}),n.parseChannel=(e=>{let t=e.split("#");return{global:t[0],type:t[1],private:"private."===t[2]}}),n.augmentChannel=((e=(new Date).getTime(),t=!0)=>{let r=e.toString(),i="public.";return t&&(i="private."),-1===r.indexOf(n.ceConfig.globalChannel)&&(r=[n.ceConfig.globalChannel,"chat",i,r].join("#")),r}),n.connect=((r,o={},s=!1,a)=>{t.uuid=r,t.authKey=s||t.uuid;l.parallel([e=>{n.request("post","bootstrap").then(()=>{e(null)}).catch(e)},e=>{n.request("post","user_read").then(()=>{e(null)}).catch(e)},e=>{n.request("post","user_write").then(()=>{e(null)}).catch(e)},r=>{n.request("post","group").then(()=>{n.pubnub=new i(t),n.global=new n.Chat(e.globalChannel,!1,!0,{},"system"),n.me=new u(n,t.uuid,a),n.me.update(o),n.me.onConstructed(),n.global.on("$.connected",()=>{n._emit("$.ready",{me:n.me}),n.global.getUserUpdates();let r=[e.globalChannel+"#"+n.me.uuid+"#rooms",e.globalChannel+"#"+n.me.uuid+"#system",e.globalChannel+"#"+n.me.uuid+"#custom"];n.pubnub.addListener({presence:e=>{n.chats[e.channel]&&n.chats[e.channel].onPresence(e)}}),n.pubnub.subscribe({channelGroups:r,withPresence:!0}),n.ready=!0,["custom","rooms","system"].forEach(r=>{let i=[e.globalChannel,t.uuid,r].join("#");n.pubnub.channelGroups.listChannels({channelGroup:i},(e,t)=>{e.error?console.log("operation failed w/ error:",e):t.channels.forEach(e=>{n.me.addChatToSession({channel:e,private:n.parseChannel(e).private,group:r})})})})}),n.pubnub.addListener({status:e=>{let t=["$","network",{PNNetworkUpCategory:"up.online",PNNetworkDownCategory:"down.offline",PNNetworkIssuesCategory:"down.issue",PNReconnectedCategory:"up.reconnected",PNConnectedCategory:"up.connected",PNAccessDeniedCategory:"down.denied",PNMalformedResponseCategory:"down.malformed",PNBadRequestCategory:"down.badrequest",PNDecryptionErrorCategory:"down.decryption",PNTimeoutCategory:"down.timeout"}[e.category]||"other"].join(".");e.affectedChannels?e.affectedChannels.forEach(r=>{let i=n.chats[r];i?("PNConnectedCategory"===e.category&&i.onConnectionReady(),i.trigger(t,e)):n._emit(t,e)}):n._emit(t,e)}})}).catch(r)}],t=>{t&&n.throwError(n,"_emit","auth",new Error("There was a problem logging into the auth server ("+e.endpoint+")."),{error:t})})}),n.Chat=function(...e){let t=n.augmentChannel(e[0],e[1]);if(n.chats[t])return n.chats[t];{let t=new a(n,...e);return t.onConstructed(),t}},n.User=function(...e){if(n.me.uuid===e[0])return n.me;if(n.users[e[0]])return n.users[e[0]];{let t=new c(n,...e);return t.onConstructed(),t}},n})},function(e,t,n){e.exports=n(33)},function(e,t,n){"use strict";function r(e){var t=new s(e),n=o(s.prototype.request,t);return i.extend(n,s.prototype,t),i.extend(n,t),n}var i=n(0),o=n(9),s=n(35),a=n(2),u=r(a);u.Axios=s,u.create=function(e){return r(i.merge(a,e))},u.Cancel=n(13),u.CancelToken=n(49),u.isCancel=n(12),u.all=function(e){return Promise.all(e)},u.spread=n(50),e.exports=u,e.exports.default=u},function(e,t){function n(e){return!!e.constructor&&"function"==typeof e.constructor.isBuffer&&e.constructor.isBuffer(e)}e.exports=function(e){return null!=e&&(n(e)||function(e){return"function"==typeof e.readFloatLE&&"function"==typeof e.slice&&n(e.slice(0,0))}(e)||!!e._isBuffer)}},function(e,t,n){"use strict";function r(e){this.defaults=e,this.interceptors={request:new s,response:new s}}var i=n(2),o=n(0),s=n(44),a=n(45),u=n(47),c=n(48);r.prototype.request=function(e){"string"==typeof e&&(e=o.merge({url:arguments[0]},arguments[1])),(e=o.merge(i,this.defaults,{method:"get"},e)).method=e.method.toLowerCase(),e.baseURL&&!u(e.url)&&(e.url=c(e.baseURL,e.url));var t=[a,void 0],n=Promise.resolve(e);for(this.interceptors.request.forEach(function(e){t.unshift(e.fulfilled,e.rejected)}),this.interceptors.response.forEach(function(e){t.push(e.fulfilled,e.rejected)});t.length;)n=n.then(t.shift(),t.shift());return n},o.forEach(["delete","get","head","options"],function(e){r.prototype[e]=function(t,n){return this.request(o.merge(n||{},{method:e,url:t}))}}),o.forEach(["post","put","patch"],function(e){r.prototype[e]=function(t,n,r){return this.request(o.merge(r||{},{method:e,url:t,data:n}))}}),e.exports=r},function(e,t,n){"use strict";var r=n(0);e.exports=function(e,t){r.forEach(e,function(n,r){r!==t&&r.toUpperCase()===t.toUpperCase()&&(e[t]=n,delete e[r])})}},function(e,t,n){"use strict";var r=n(11);e.exports=function(e,t,n){var i=n.config.validateStatus;n.status&&i&&!i(n.status)?t(r("Request failed with status code "+n.status,n.config,null,n.request,n)):e(n)}},function(e,t,n){"use strict";e.exports=function(e,t,n,r,i){return e.config=t,n&&(e.code=n),e.request=r,e.response=i,e}},function(e,t,n){"use strict";function r(e){return encodeURIComponent(e).replace(/%40/gi,"@").replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}var i=n(0);e.exports=function(e,t,n){if(!t)return e;var o;if(n)o=n(t);else if(i.isURLSearchParams(t))o=t.toString();else{var s=[];i.forEach(t,function(e,t){null!==e&&void 0!==e&&(i.isArray(e)&&(t+="[]"),i.isArray(e)||(e=[e]),i.forEach(e,function(e){i.isDate(e)?e=e.toISOString():i.isObject(e)&&(e=JSON.stringify(e)),s.push(r(t)+"="+r(e))}))}),o=s.join("&")}return o&&(e+=(-1===e.indexOf("?")?"?":"&")+o),e}},function(e,t,n){"use strict";var r=n(0);e.exports=function(e){var t,n,i,o={};return e?(r.forEach(e.split("\n"),function(e){i=e.indexOf(":"),t=r.trim(e.substr(0,i)).toLowerCase(),n=r.trim(e.substr(i+1)),t&&(o[t]=o[t]?o[t]+", "+n:n)}),o):o}},function(e,t,n){"use strict";var r=n(0);e.exports=r.isStandardBrowserEnv()?function(){function e(e){var t=e;return n&&(i.setAttribute("href",t),t=i.href),i.setAttribute("href",t),{href:i.href,protocol:i.protocol?i.protocol.replace(/:$/,""):"",host:i.host,search:i.search?i.search.replace(/^\?/,""):"",hash:i.hash?i.hash.replace(/^#/,""):"",hostname:i.hostname,port:i.port,pathname:"/"===i.pathname.charAt(0)?i.pathname:"/"+i.pathname}}var t,n=/(msie|trident)/i.test(navigator.userAgent),i=document.createElement("a");return t=e(window.location.href),function(n){var i=r.isString(n)?e(n):n;return i.protocol===t.protocol&&i.host===t.host}}():function(){return!0}},function(e,t,n){"use strict";function r(){this.message="String contains an invalid character"}var i="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";(r.prototype=new Error).code=5,r.prototype.name="InvalidCharacterError",e.exports=function(e){for(var t,n,o=String(e),s="",a=0,u=i;o.charAt(0|a)||(u="=",a%1);s+=u.charAt(63&t>>8-a%1*8)){if((n=o.charCodeAt(a+=.75))>255)throw new r;t=t<<8|n}return s}},function(e,t,n){"use strict";var r=n(0);e.exports=r.isStandardBrowserEnv()?{write:function(e,t,n,i,o,s){var a=[];a.push(e+"="+encodeURIComponent(t)),r.isNumber(n)&&a.push("expires="+new Date(n).toGMTString()),r.isString(i)&&a.push("path="+i),r.isString(o)&&a.push("domain="+o),!0===s&&a.push("secure"),document.cookie=a.join("; ")},read:function(e){var t=document.cookie.match(new RegExp("(^|;\\s*)("+e+")=([^;]*)"));return t?decodeURIComponent(t[3]):null},remove:function(e){this.write(e,"",Date.now()-864e5)}}:{write:function(){},read:function(){return null},remove:function(){}}},function(e,t,n){"use strict";function r(){this.handlers=[]}var i=n(0);r.prototype.use=function(e,t){return this.handlers.push({fulfilled:e,rejected:t}),this.handlers.length-1},r.prototype.eject=function(e){this.handlers[e]&&(this.handlers[e]=null)},r.prototype.forEach=function(e){i.forEach(this.handlers,function(t){null!==t&&e(t)})},e.exports=r},function(e,t,n){"use strict";function r(e){e.cancelToken&&e.cancelToken.throwIfRequested()}var i=n(0),o=n(46),s=n(12),a=n(2);e.exports=function(e){r(e),e.headers=e.headers||{},e.data=o(e.data,e.headers,e.transformRequest),e.headers=i.merge(e.headers.common||{},e.headers[e.method]||{},e.headers||{}),i.forEach(["delete","get","head","post","put","patch","common"],function(t){delete e.headers[t]});return(e.adapter||a.adapter)(e).then(function(t){return r(e),t.data=o(t.data,t.headers,e.transformResponse),t},function(t){return s(t)||(r(e),t&&t.response&&(t.response.data=o(t.response.data,t.response.headers,e.transformResponse))),Promise.reject(t)})}},function(e,t,n){"use strict";var r=n(0);e.exports=function(e,t,n){return r.forEach(n,function(n){e=n(e,t)}),e}},function(e,t,n){"use strict";e.exports=function(e){return/^([a-z][a-z\d\+\-\.]*:)?\/\//i.test(e)}},function(e,t,n){"use strict";e.exports=function(e,t){return t?e.replace(/\/+$/,"")+"/"+t.replace(/^\/+/,""):e}},function(e,t,n){"use strict";function r(e){if("function"!=typeof e)throw new TypeError("executor must be a function.");var t;this.promise=new Promise(function(e){t=e});var n=this;e(function(e){n.reason||(n.reason=new i(e),t(n.reason))})}var i=n(13);r.prototype.throwIfRequested=function(){if(this.reason)throw this.reason},r.source=function(){var e;return{token:new r(function(t){e=t}),cancel:e}},e.exports=r},function(e,t,n){"use strict";e.exports=function(e){return function(t){return e.apply(null,t)}}},function(e,t,n){!function(t,n){e.exports=n()}(0,function(){return function(e){function t(r){if(n[r])return n[r].exports;var i=n[r]={exports:{},id:r,loaded:!1};return e[r].call(i.exports,i,i.exports,t),i.loaded=!0,i.exports}var n={};return t.m=e,t.c=n,t.p="",t(0)}([function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0});var i=r(n(1)),o=r(n(39)),s=r(n(40)),a=n(41),u=(n(5),function(e){function t(e){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,t);var n=e.listenToBrowserNetworkEvents,r=void 0===n||n;e.db=s.default,e.sdkFamily="Web",e.networking=new o.default({del:a.del,get:a.get,post:a.post,sendBeacon:function(e){if(!navigator||!navigator.sendBeacon)return!1;navigator.sendBeacon(e)}});var i=function(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));return r&&(window.addEventListener("offline",function(){i.networkDownDetected()}),window.addEventListener("online",function(){i.networkUpDetected()})),i}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}(t,i.default),t}());t.default=u,e.exports=t.default},function(e,t,n){"use strict";function r(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n]);return t.default=e,t}function i(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0});var o=function(){function e(e,t){for(var n=0;n>>2]|=(n[i>>>2]>>>24-i%4*8&255)<<24-(r+i)%4*8;else if(65535>>2]=n[i>>>2];else t.push.apply(t,n);return this.sigBytes+=e,this},clamp:function(){var t=this.words,n=this.sigBytes;t[n>>>2]&=4294967295<<32-n%4*8,t.length=e.ceil(n/4)},clone:function(){var e=o.clone.call(this);return e.words=this.words.slice(0),e},random:function(t){for(var n=[],r=0;r>>2]>>>24-r%4*8&255;n.push((i>>>4).toString(16)),n.push((15&i).toString(16))}return n.join("")},parse:function(e){for(var t=e.length,n=[],r=0;r>>3]|=parseInt(e.substr(r,2),16)<<24-r%8*4;return new s.init(n,t/2)}},c=a.Latin1={stringify:function(e){var t=e.words;e=e.sigBytes;for(var n=[],r=0;r>>2]>>>24-r%4*8&255));return n.join("")},parse:function(e){for(var t=e.length,n=[],r=0;r>>2]|=(255&e.charCodeAt(r))<<24-r%4*8;return new s.init(n,t)}},l=a.Utf8={stringify:function(e){try{return decodeURIComponent(escape(c.stringify(e)))}catch(e){throw Error("Malformed UTF-8 data")}},parse:function(e){return c.parse(unescape(encodeURIComponent(e)))}},f=r.BufferedBlockAlgorithm=o.extend({reset:function(){this._data=new s.init,this._nDataBytes=0},_append:function(e){"string"==typeof e&&(e=l.parse(e)),this._data.concat(e),this._nDataBytes+=e.sigBytes},_process:function(t){var n=this._data,r=n.words,i=n.sigBytes,o=this.blockSize,a=i/(4*o);if(t=(a=t?e.ceil(a):e.max((0|a)-this._minBufferSize,0))*o,i=e.min(4*t,i),t){for(var u=0;ul;){var f;e:{f=c;for(var h=e.sqrt(f),p=2;p<=h;p++)if(!(f%p)){f=!1;break e}f=!0}f&&(8>l&&(s[l]=u(e.pow(c,.5))),a[l]=u(e.pow(c,1/3)),l++),c++}var d=[],o=o.SHA256=i.extend({_doReset:function(){this._hash=new r.init(s.slice(0))},_doProcessBlock:function(e,t){for(var n=this._hash.words,r=n[0],i=n[1],o=n[2],s=n[3],u=n[4],c=n[5],l=n[6],f=n[7],h=0;64>h;h++){if(16>h)d[h]=0|e[t+h];else{var p=d[h-15],g=d[h-2];d[h]=((p<<25|p>>>7)^(p<<14|p>>>18)^p>>>3)+d[h-7]+((g<<15|g>>>17)^(g<<13|g>>>19)^g>>>10)+d[h-16]}p=f+((u<<26|u>>>6)^(u<<21|u>>>11)^(u<<7|u>>>25))+(u&c^~u&l)+a[h]+d[h],g=((r<<30|r>>>2)^(r<<19|r>>>13)^(r<<10|r>>>22))+(r&i^r&o^i&o),f=l,l=c,c=u,u=s+p|0,s=o,o=i,i=r,r=p+g|0}n[0]=n[0]+r|0,n[1]=n[1]+i|0,n[2]=n[2]+o|0,n[3]=n[3]+s|0,n[4]=n[4]+u|0,n[5]=n[5]+c|0,n[6]=n[6]+l|0,n[7]=n[7]+f|0},_doFinalize:function(){var t=this._data,n=t.words,r=8*this._nDataBytes,i=8*t.sigBytes;return n[i>>>5]|=128<<24-i%32,n[14+(i+64>>>9<<4)]=e.floor(r/4294967296),n[15+(i+64>>>9<<4)]=r,t.sigBytes=4*n.length,this._process(),this._hash},clone:function(){var e=i.clone.call(this);return e._hash=this._hash.clone(),e}});t.SHA256=i._createHelper(o),t.HmacSHA256=i._createHmacHelper(o)}(Math),function(){var e=n,t=e.enc.Utf8;e.algo.HMAC=e.lib.Base.extend({init:function(e,n){e=this._hasher=new e.init,"string"==typeof n&&(n=t.parse(n));var r=e.blockSize,i=4*r;n.sigBytes>i&&(n=e.finalize(n)),n.clamp();for(var o=this._oKey=n.clone(),s=this._iKey=n.clone(),a=o.words,u=s.words,c=0;c>>2]>>>24-i%4*8&255)<<16|(t[i+1>>>2]>>>24-(i+1)%4*8&255)<<8|t[i+2>>>2]>>>24-(i+2)%4*8&255,s=0;4>s&&i+.75*s>>6*(3-s)&63));if(t=r.charAt(64))for(;e.length%4;)e.push(t);return e.join("")},parse:function(e){var n=e.length,r=this._map;(i=r.charAt(64))&&-1!=(i=e.indexOf(i))&&(n=i);for(var i=[],o=0,s=0;s>>6-s%4*2;i[o>>>2]|=(a|u)<<24-o%4*8,o++}return t.create(i,o)},_map:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="}}(),function(e){function t(e,t,n,r,i,o,s){return((e=e+(t&n|~t&r)+i+s)<>>32-o)+t}function r(e,t,n,r,i,o,s){return((e=e+(t&r|n&~r)+i+s)<>>32-o)+t}function i(e,t,n,r,i,o,s){return((e=e+(t^n^r)+i+s)<>>32-o)+t}function o(e,t,n,r,i,o,s){return((e=e+(n^(t|~r))+i+s)<>>32-o)+t}for(var s=n,a=(c=s.lib).WordArray,u=c.Hasher,c=s.algo,l=[],f=0;64>f;f++)l[f]=4294967296*e.abs(e.sin(f+1))|0;c=c.MD5=u.extend({_doReset:function(){this._hash=new a.init([1732584193,4023233417,2562383102,271733878])},_doProcessBlock:function(e,n){for(s=0;16>s;s++){u=e[a=n+s];e[a]=16711935&(u<<8|u>>>24)|4278255360&(u<<24|u>>>8)}var s=this._hash.words,a=e[n+0],u=e[n+1],c=e[n+2],f=e[n+3],h=e[n+4],p=e[n+5],d=e[n+6],g=e[n+7],y=e[n+8],v=e[n+9],b=e[n+10],m=e[n+11],_=e[n+12],w=e[n+13],k=e[n+14],E=e[n+15],S=s[0],P=s[1],O=s[2],x=s[3],P=o(P=o(P=o(P=o(P=i(P=i(P=i(P=i(P=r(P=r(P=r(P=r(P=t(P=t(P=t(P=t(P,O=t(O,x=t(x,S=t(S,P,O,x,a,7,l[0]),P,O,u,12,l[1]),S,P,c,17,l[2]),x,S,f,22,l[3]),O=t(O,x=t(x,S=t(S,P,O,x,h,7,l[4]),P,O,p,12,l[5]),S,P,d,17,l[6]),x,S,g,22,l[7]),O=t(O,x=t(x,S=t(S,P,O,x,y,7,l[8]),P,O,v,12,l[9]),S,P,b,17,l[10]),x,S,m,22,l[11]),O=t(O,x=t(x,S=t(S,P,O,x,_,7,l[12]),P,O,w,12,l[13]),S,P,k,17,l[14]),x,S,E,22,l[15]),O=r(O,x=r(x,S=r(S,P,O,x,u,5,l[16]),P,O,d,9,l[17]),S,P,m,14,l[18]),x,S,a,20,l[19]),O=r(O,x=r(x,S=r(S,P,O,x,p,5,l[20]),P,O,b,9,l[21]),S,P,E,14,l[22]),x,S,h,20,l[23]),O=r(O,x=r(x,S=r(S,P,O,x,v,5,l[24]),P,O,k,9,l[25]),S,P,f,14,l[26]),x,S,y,20,l[27]),O=r(O,x=r(x,S=r(S,P,O,x,w,5,l[28]),P,O,c,9,l[29]),S,P,g,14,l[30]),x,S,_,20,l[31]),O=i(O,x=i(x,S=i(S,P,O,x,p,4,l[32]),P,O,y,11,l[33]),S,P,m,16,l[34]),x,S,k,23,l[35]),O=i(O,x=i(x,S=i(S,P,O,x,u,4,l[36]),P,O,h,11,l[37]),S,P,g,16,l[38]),x,S,b,23,l[39]),O=i(O,x=i(x,S=i(S,P,O,x,w,4,l[40]),P,O,a,11,l[41]),S,P,f,16,l[42]),x,S,d,23,l[43]),O=i(O,x=i(x,S=i(S,P,O,x,v,4,l[44]),P,O,_,11,l[45]),S,P,E,16,l[46]),x,S,c,23,l[47]),O=o(O,x=o(x,S=o(S,P,O,x,a,6,l[48]),P,O,g,10,l[49]),S,P,k,15,l[50]),x,S,p,21,l[51]),O=o(O,x=o(x,S=o(S,P,O,x,_,6,l[52]),P,O,f,10,l[53]),S,P,b,15,l[54]),x,S,u,21,l[55]),O=o(O,x=o(x,S=o(S,P,O,x,y,6,l[56]),P,O,E,10,l[57]),S,P,d,15,l[58]),x,S,w,21,l[59]),O=o(O,x=o(x,S=o(S,P,O,x,h,6,l[60]),P,O,m,10,l[61]),S,P,c,15,l[62]),x,S,v,21,l[63]);s[0]=s[0]+S|0,s[1]=s[1]+P|0,s[2]=s[2]+O|0,s[3]=s[3]+x|0},_doFinalize:function(){var t=this._data,n=t.words,r=8*this._nDataBytes,i=8*t.sigBytes;n[i>>>5]|=128<<24-i%32;var o=e.floor(r/4294967296);for(n[15+(i+64>>>9<<4)]=16711935&(o<<8|o>>>24)|4278255360&(o<<24|o>>>8),n[14+(i+64>>>9<<4)]=16711935&(r<<8|r>>>24)|4278255360&(r<<24|r>>>8),t.sigBytes=4*(n.length+1),this._process(),n=(t=this._hash).words,r=0;4>r;r++)i=n[r],n[r]=16711935&(i<<8|i>>>24)|4278255360&(i<<24|i>>>8);return t},clone:function(){var e=u.clone.call(this);return e._hash=this._hash.clone(),e}}),s.MD5=u._createHelper(c),s.HmacMD5=u._createHmacHelper(c)}(Math),function(){var e=n,t=e.lib,r=t.Base,i=t.WordArray,o=(t=e.algo).EvpKDF=r.extend({cfg:r.extend({keySize:4,hasher:t.MD5,iterations:1}),init:function(e){this.cfg=this.cfg.extend(e)},compute:function(e,t){for(var n=(a=this.cfg).hasher.create(),r=i.create(),o=r.words,s=a.keySize,a=a.iterations;o.length>>2]}},t.BlockCipher=u.extend({cfg:u.cfg.extend({mode:c,padding:f}),reset:function(){u.reset.call(this);var e=(t=this.cfg).iv,t=t.mode;if(this._xformMode==this._ENC_XFORM_MODE)var n=t.createEncryptor;else n=t.createDecryptor,this._minBufferSize=1;this._mode=n.call(t,this,e&&e.words)},_doProcessBlock:function(e,t){this._mode.processBlock(e,t)},_doFinalize:function(){var e=this.cfg.padding;if(this._xformMode==this._ENC_XFORM_MODE){e.pad(this._data,this.blockSize);var t=this._process(!0)}else t=this._process(!0),e.unpad(t);return t},blockSize:4});var h=t.CipherParams=r.extend({init:function(e){this.mixIn(e)},toString:function(e){return(e||this.formatter).stringify(this)}}),c=(d.format={}).OpenSSL={stringify:function(e){var t=e.ciphertext;return((e=e.salt)?i.create([1398893684,1701076831]).concat(e).concat(t):t).toString(s)},parse:function(e){var t=(e=s.parse(e)).words;if(1398893684==t[0]&&1701076831==t[1]){var n=i.create(t.slice(2,4));t.splice(0,4),e.sigBytes-=16}return h.create({ciphertext:e,salt:n})}},p=t.SerializableCipher=r.extend({cfg:r.extend({format:c}),encrypt:function(e,t,n,r){r=this.cfg.extend(r);var i=e.createEncryptor(n,r);return t=i.finalize(t),i=i.cfg,h.create({ciphertext:t,key:n,iv:i.iv,algorithm:e,mode:i.mode,padding:i.padding,blockSize:e.blockSize,formatter:r.format})},decrypt:function(e,t,n,r){return r=this.cfg.extend(r),t=this._parse(t,r.format),e.createDecryptor(n,r).finalize(t.ciphertext)},_parse:function(e,t){return"string"==typeof e?t.parse(e,this):e}}),d=(d.kdf={}).OpenSSL={execute:function(e,t,n,r){return r||(r=i.random(8)),e=a.create({keySize:t+n}).compute(e,r),n=i.create(e.words.slice(t),4*n),e.sigBytes=4*t,h.create({key:e,iv:n,salt:r})}},g=t.PasswordBasedCipher=p.extend({cfg:p.cfg.extend({kdf:d}),encrypt:function(e,t,n,r){return r=this.cfg.extend(r),n=r.kdf.execute(n,e.keySize,e.ivSize),r.iv=n.iv,(e=p.encrypt.call(this,e,t,n.key,r)).mixIn(n),e},decrypt:function(e,t,n,r){return r=this.cfg.extend(r),t=this._parse(t,r.format),n=r.kdf.execute(n,e.keySize,e.ivSize,t.salt),r.iv=n.iv,p.decrypt.call(this,e,t,n.key,r)}})}(),function(){for(var e=n,t=e.lib.BlockCipher,r=e.algo,i=[],o=[],s=[],a=[],u=[],c=[],l=[],f=[],h=[],p=[],d=[],g=0;256>g;g++)d[g]=128>g?g<<1:g<<1^283;for(var y=0,v=0,g=0;256>g;g++){var b=(b=v^v<<1^v<<2^v<<3^v<<4)>>>8^255&b^99;i[y]=b,o[b]=y;var m=d[y],_=d[m],w=d[_],k=257*d[b]^16843008*b;s[y]=k<<24|k>>>8,a[y]=k<<16|k>>>16,u[y]=k<<8|k>>>24,c[y]=k,k=16843009*w^65537*_^257*m^16843008*y,l[b]=k<<24|k>>>8,f[b]=k<<16|k>>>16,h[b]=k<<8|k>>>24,p[b]=k,y?(y=m^d[d[d[w^m]]],v^=d[d[v]]):y=v=1}var E=[0,1,2,4,8,16,32,64,128,27,54],r=r.AES=t.extend({_doReset:function(){for(var e=(n=this._key).words,t=n.sigBytes/4,n=4*((this._nRounds=t+6)+1),r=this._keySchedule=[],o=0;o>>24]<<24|i[s>>>16&255]<<16|i[s>>>8&255]<<8|i[255&s]):(s=s<<8|s>>>24,s=i[s>>>24]<<24|i[s>>>16&255]<<16|i[s>>>8&255]<<8|i[255&s],s^=E[o/t|0]<<24),r[o]=r[o-t]^s}for(e=this._invKeySchedule=[],t=0;tt||4>=o?s:l[i[s>>>24]]^f[i[s>>>16&255]]^h[i[s>>>8&255]]^p[i[255&s]]},encryptBlock:function(e,t){this._doCryptBlock(e,t,this._keySchedule,s,a,u,c,i)},decryptBlock:function(e,t){var n=e[t+1];e[t+1]=e[t+3],e[t+3]=n,this._doCryptBlock(e,t,this._invKeySchedule,l,f,h,p,o),n=e[t+1],e[t+1]=e[t+3],e[t+3]=n},_doCryptBlock:function(e,t,n,r,i,o,s,a){for(var u=this._nRounds,c=e[t]^n[0],l=e[t+1]^n[1],f=e[t+2]^n[2],h=e[t+3]^n[3],p=4,d=1;d>>24]^i[l>>>16&255]^o[f>>>8&255]^s[255&h]^n[p++],y=r[l>>>24]^i[f>>>16&255]^o[h>>>8&255]^s[255&c]^n[p++],v=r[f>>>24]^i[h>>>16&255]^o[c>>>8&255]^s[255&l]^n[p++],h=r[h>>>24]^i[c>>>16&255]^o[l>>>8&255]^s[255&f]^n[p++],c=g,l=y,f=v;g=(a[c>>>24]<<24|a[l>>>16&255]<<16|a[f>>>8&255]<<8|a[255&h])^n[p++],y=(a[l>>>24]<<24|a[f>>>16&255]<<16|a[h>>>8&255]<<8|a[255&c])^n[p++],v=(a[f>>>24]<<24|a[h>>>16&255]<<16|a[c>>>8&255]<<8|a[255&l])^n[p++],h=(a[h>>>24]<<24|a[c>>>16&255]<<16|a[l>>>8&255]<<8|a[255&f])^n[p++],e[t]=g,e[t+1]=y,e[t+2]=v,e[t+3]=h},keySize:8});e.AES=t._createHelper(r)}(),n.mode.ECB=function(){var e=n.lib.BlockCipherMode.extend();return e.Encryptor=e.extend({processBlock:function(e,t){this._cipher.encryptBlock(e,t)}}),e.Decryptor=e.extend({processBlock:function(e,t){this._cipher.decryptBlock(e,t)}}),e}(),e.exports=n},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0});var i=function(){function e(e,t){for(var n=0;n=s){var l={};l.category=u.default.PNRequestMessageCountExceededCategory,l.operation=e.operation,this._listenerManager.announceStatus(l)}i.forEach(function(e){var t=e.channel,r=e.subscriptionMatch,i=e.publishMetaData;if(t===r&&(r=null),c){if(n._dedupingManager.isDuplicate(e))return;n._dedupingManager.addEntry(e)}if(a.default.endsWith(e.channel,"-pnpres")){var o={};o.channel=null,o.subscription=null,o.actualChannel=null!=r?t:null,o.subscribedChannel=null!=r?r:t,t&&(o.channel=t.substring(0,t.lastIndexOf("-pnpres"))),r&&(o.subscription=r.substring(0,r.lastIndexOf("-pnpres"))),o.action=e.payload.action,o.state=e.payload.data,o.timetoken=i.publishTimetoken,o.occupancy=e.payload.occupancy,o.uuid=e.payload.uuid,o.timestamp=e.payload.timestamp,e.payload.join&&(o.join=e.payload.join),e.payload.leave&&(o.leave=e.payload.leave),e.payload.timeout&&(o.timeout=e.payload.timeout),n._listenerManager.announcePresence(o)}else{var s={};s.channel=null,s.subscription=null,s.actualChannel=null!=r?t:null,s.subscribedChannel=null!=r?r:t,s.channel=t,s.subscription=r,s.timetoken=i.publishTimetoken,s.publisher=e.issuingClientId,e.userMetadata&&(s.userMetadata=e.userMetadata),n._config.cipherKey?s.message=n._crypto.decrypt(e.payload):s.message=e.payload,n._listenerManager.announceMessage(s)}}),this._region=t.metadata.region,this._startSubscribeLoop()}}},{key:"_stopSubscribeLoop",value:function(){this._subscribeCall&&(this._subscribeCall.abort(),this._subscribeCall=null)}}]),e}();t.default=c,e.exports=t.default},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=function(){function e(e,t){for(var n=0;n=this._config.maximumCacheSize&&this.hashHistory.shift(),this.hashHistory.push(this.getKey(e))}},{key:"clearHistory",value:function(){this.hashHistory=[]}}]),e}();t.default=o,e.exports=t.default},function(e,t){"use strict";function n(e){return encodeURIComponent(e).replace(/[!~*'()]/g,function(e){return"%"+e.charCodeAt(0).toString(16).toUpperCase()})}e.exports={signPamFromParams:function(e){return function(e){return function(e){var t=[];return Object.keys(e).forEach(function(e){return t.push(e)}),t}(e).sort()}(e).map(function(t){return t+"="+n(e[t])}).join("&")},endsWith:function(e,t){return-1!==e.indexOf(t,this.length-t.length)},createPromise:function(){var e=void 0,t=void 0;return{promise:new Promise(function(n,r){e=n,t=r}),reject:t,fulfill:e}},encodeString:n}},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}function i(e){return function(e,t){return e.type=t,e.error=!0,e}({message:e},"validationError")}Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e,t){var n=e.networking,r=e.config,c=null,l=null,f={};t.getOperation()===a.default.PNTimeOperation||t.getOperation()===a.default.PNChannelGroupsOperation?c=arguments.length<=2?void 0:arguments[2]:(f=arguments.length<=2?void 0:arguments[2],c=arguments.length<=3?void 0:arguments[3]),"undefined"==typeof Promise||c||(l=s.default.createPromise());var h=t.validateParams(e,f);if(!h){var p=t.prepareParams(e,f),d=function(e,t,n){return e.usePost&&e.usePost(t,n)?e.postURL(t,n):e.getURL(t,n)}(t,e,f),g=void 0,y={url:d,operation:t.getOperation(),timeout:t.getRequestTimeout(e)};p.uuid=r.UUID,p.pnsdk=function(e){var t="PubNub-JS-"+e.sdkFamily;return e.partnerId&&(t+="-"+e.partnerId),t+="/"+e.getVersion()}(r),r.useInstanceId&&(p.instanceid=r.instanceId),r.useRequestId&&(p.requestid=o.default.createUUID()),t.isAuthSupported()&&r.getAuthKey()&&(p.auth=r.getAuthKey()),r.secretKey&&function(e,t,n){var r=e.config,i=e.crypto;n.timestamp=Math.floor((new Date).getTime()/1e3);var o=r.subscribeKey+"\n"+r.publishKey+"\n"+t+"\n";o+=s.default.signPamFromParams(n);var a=i.HMACSHA256(o);a=(a=a.replace(/\+/g,"-")).replace(/\//g,"_"),n.signature=a}(e,d,p);var v=function(n,r){if(n.error)c?c(n):l&&l.reject(new u("PubNub call failed, check status for details",n));else{var i=t.handleResponse(e,r,f);c?c(n,i):l&&l.fulfill(i)}};if(t.usePost&&t.usePost(e,f)){var b=t.postPayload(e,f);g=n.POST(p,b,y,v)}else g=t.useDelete&&t.useDelete()?n.DELETE(p,y,v):n.GET(p,y,v);return t.getOperation()===a.default.PNSubscribeOperation?g:l?l.promise:void 0}return c?c(i(h)):l?(l.reject(new u("Validation failed, check status for details",i(h))),l.promise):void 0};var o=r(n(3)),s=r((n(5),n(15))),a=r((r(n(2)),n(13))),u=function(e){function t(e,n){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,t);var r=function(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));return r.name=r.constructor.name,r.status=n,r.message=e,r}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}(t,Error),t}();e.exports=t.default},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0}),t.getOperation=function(){return i.default.PNAddChannelsToGroupOperation},t.validateParams=function(e,t){var n=t.channels,r=t.channelGroup,i=e.config;return r?n&&0!==n.length?i.subscribeKey?void 0:"Missing Subscribe Key":"Missing Channels":"Missing Channel Group"},t.getURL=function(e,t){var n=t.channelGroup;return"/v1/channel-registration/sub-key/"+e.config.subscribeKey+"/channel-group/"+o.default.encodeString(n)},t.getRequestTimeout=function(e){return e.config.getTransactionTimeout()},t.isAuthSupported=function(){return!0},t.prepareParams=function(e,t){var n=t.channels;return{add:(void 0===n?[]:n).join(",")}},t.handleResponse=function(){return{}};var i=r((n(5),n(13))),o=r(n(15))},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0}),t.getOperation=function(){return i.default.PNRemoveChannelsFromGroupOperation},t.validateParams=function(e,t){var n=t.channels,r=t.channelGroup,i=e.config;return r?n&&0!==n.length?i.subscribeKey?void 0:"Missing Subscribe Key":"Missing Channels":"Missing Channel Group"},t.getURL=function(e,t){var n=t.channelGroup;return"/v1/channel-registration/sub-key/"+e.config.subscribeKey+"/channel-group/"+o.default.encodeString(n)},t.getRequestTimeout=function(e){return e.config.getTransactionTimeout()},t.isAuthSupported=function(){return!0},t.prepareParams=function(e,t){var n=t.channels;return{remove:(void 0===n?[]:n).join(",")}},t.handleResponse=function(){return{}};var i=r((n(5),n(13))),o=r(n(15))},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0}),t.getOperation=function(){return i.default.PNRemoveGroupOperation},t.validateParams=function(e,t){var n=t.channelGroup,r=e.config;return n?r.subscribeKey?void 0:"Missing Subscribe Key":"Missing Channel Group"},t.getURL=function(e,t){var n=t.channelGroup;return"/v1/channel-registration/sub-key/"+e.config.subscribeKey+"/channel-group/"+o.default.encodeString(n)+"/remove"},t.isAuthSupported=function(){return!0},t.getRequestTimeout=function(e){return e.config.getTransactionTimeout()},t.prepareParams=function(){return{}},t.handleResponse=function(){return{}};var i=r((n(5),n(13))),o=r(n(15))},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getOperation=function(){return r.default.PNChannelGroupsOperation},t.validateParams=function(e){if(!e.config.subscribeKey)return"Missing Subscribe Key"},t.getURL=function(e){return"/v1/channel-registration/sub-key/"+e.config.subscribeKey+"/channel-group"},t.getRequestTimeout=function(e){return e.config.getTransactionTimeout()},t.isAuthSupported=function(){return!0},t.prepareParams=function(){return{}},t.handleResponse=function(e,t){return{groups:t.payload.groups}};var r=function(e){return e&&e.__esModule?e:{default:e}}((n(5),n(13)))},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0}),t.getOperation=function(){return i.default.PNChannelsForGroupOperation},t.validateParams=function(e,t){var n=t.channelGroup,r=e.config;return n?r.subscribeKey?void 0:"Missing Subscribe Key":"Missing Channel Group"},t.getURL=function(e,t){var n=t.channelGroup;return"/v1/channel-registration/sub-key/"+e.config.subscribeKey+"/channel-group/"+o.default.encodeString(n)},t.getRequestTimeout=function(e){return e.config.getTransactionTimeout()},t.isAuthSupported=function(){return!0},t.prepareParams=function(){return{}},t.handleResponse=function(e,t){return{channels:t.payload.channels}};var i=r((n(5),n(13))),o=r(n(15))},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getOperation=function(){return r.default.PNPushNotificationEnabledChannelsOperation},t.validateParams=function(e,t){var n=t.device,r=t.pushGateway,i=t.channels,o=e.config;return n?r?i&&0!==i.length?o.subscribeKey?void 0:"Missing Subscribe Key":"Missing Channels":"Missing GW Type (pushGateway: gcm or apns)":"Missing Device ID (device)"},t.getURL=function(e,t){var n=t.device;return"/v1/push/sub-key/"+e.config.subscribeKey+"/devices/"+n},t.getRequestTimeout=function(e){return e.config.getTransactionTimeout()},t.isAuthSupported=function(){return!0},t.prepareParams=function(e,t){var n=t.pushGateway,r=t.channels;return{type:n,add:(void 0===r?[]:r).join(",")}},t.handleResponse=function(){return{}};var r=function(e){return e&&e.__esModule?e:{default:e}}((n(5),n(13)))},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getOperation=function(){return r.default.PNPushNotificationEnabledChannelsOperation},t.validateParams=function(e,t){var n=t.device,r=t.pushGateway,i=t.channels,o=e.config;return n?r?i&&0!==i.length?o.subscribeKey?void 0:"Missing Subscribe Key":"Missing Channels":"Missing GW Type (pushGateway: gcm or apns)":"Missing Device ID (device)"},t.getURL=function(e,t){var n=t.device;return"/v1/push/sub-key/"+e.config.subscribeKey+"/devices/"+n},t.getRequestTimeout=function(e){return e.config.getTransactionTimeout()},t.isAuthSupported=function(){return!0},t.prepareParams=function(e,t){var n=t.pushGateway,r=t.channels;return{type:n,remove:(void 0===r?[]:r).join(",")}},t.handleResponse=function(){return{}};var r=function(e){return e&&e.__esModule?e:{default:e}}((n(5),n(13)))},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getOperation=function(){return r.default.PNPushNotificationEnabledChannelsOperation},t.validateParams=function(e,t){var n=t.device,r=t.pushGateway,i=e.config;return n?r?i.subscribeKey?void 0:"Missing Subscribe Key":"Missing GW Type (pushGateway: gcm or apns)":"Missing Device ID (device)"},t.getURL=function(e,t){var n=t.device;return"/v1/push/sub-key/"+e.config.subscribeKey+"/devices/"+n},t.getRequestTimeout=function(e){return e.config.getTransactionTimeout()},t.isAuthSupported=function(){return!0},t.prepareParams=function(e,t){return{type:t.pushGateway}},t.handleResponse=function(e,t){return{channels:t}};var r=function(e){return e&&e.__esModule?e:{default:e}}((n(5),n(13)))},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getOperation=function(){return r.default.PNRemoveAllPushNotificationsOperation},t.validateParams=function(e,t){var n=t.device,r=t.pushGateway,i=e.config;return n?r?i.subscribeKey?void 0:"Missing Subscribe Key":"Missing GW Type (pushGateway: gcm or apns)":"Missing Device ID (device)"},t.getURL=function(e,t){var n=t.device;return"/v1/push/sub-key/"+e.config.subscribeKey+"/devices/"+n+"/remove"},t.getRequestTimeout=function(e){return e.config.getTransactionTimeout()},t.isAuthSupported=function(){return!0},t.prepareParams=function(e,t){return{type:t.pushGateway}},t.handleResponse=function(){return{}};var r=function(e){return e&&e.__esModule?e:{default:e}}((n(5),n(13)))},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0}),t.getOperation=function(){return i.default.PNUnsubscribeOperation},t.validateParams=function(e){if(!e.config.subscribeKey)return"Missing Subscribe Key"},t.getURL=function(e,t){var n=e.config,r=t.channels,i=void 0===r?[]:r,s=i.length>0?i.join(","):",";return"/v2/presence/sub-key/"+n.subscribeKey+"/channel/"+o.default.encodeString(s)+"/leave"},t.getRequestTimeout=function(e){return e.config.getTransactionTimeout()},t.isAuthSupported=function(){return!0},t.prepareParams=function(e,t){var n=t.channelGroups,r=void 0===n?[]:n,i={};return r.length>0&&(i["channel-group"]=r.join(",")),i},t.handleResponse=function(){return{}};var i=r((n(5),n(13))),o=r(n(15))},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getOperation=function(){return r.default.PNWhereNowOperation},t.validateParams=function(e){if(!e.config.subscribeKey)return"Missing Subscribe Key"},t.getURL=function(e,t){var n=e.config,r=t.uuid,i=void 0===r?n.UUID:r;return"/v2/presence/sub-key/"+n.subscribeKey+"/uuid/"+i},t.getRequestTimeout=function(e){return e.config.getTransactionTimeout()},t.isAuthSupported=function(){return!0},t.prepareParams=function(){return{}},t.handleResponse=function(e,t){return t.payload?{channels:t.payload.channels}:{channels:[]}};var r=function(e){return e&&e.__esModule?e:{default:e}}((n(5),n(13)))},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0}),t.getOperation=function(){return i.default.PNHeartbeatOperation},t.validateParams=function(e){if(!e.config.subscribeKey)return"Missing Subscribe Key"},t.getURL=function(e,t){var n=e.config,r=t.channels,i=void 0===r?[]:r,s=i.length>0?i.join(","):",";return"/v2/presence/sub-key/"+n.subscribeKey+"/channel/"+o.default.encodeString(s)+"/heartbeat"},t.isAuthSupported=function(){return!0},t.getRequestTimeout=function(e){return e.config.getTransactionTimeout()},t.prepareParams=function(e,t){var n=t.channelGroups,r=void 0===n?[]:n,i=t.state,o=void 0===i?{}:i,s=e.config,a={};return r.length>0&&(a["channel-group"]=r.join(",")),a.state=JSON.stringify(o),a.heartbeat=s.getPresenceTimeout(),a},t.handleResponse=function(){return{}};var i=r((n(5),n(13))),o=r(n(15))},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0}),t.getOperation=function(){return i.default.PNGetStateOperation},t.validateParams=function(e){if(!e.config.subscribeKey)return"Missing Subscribe Key"},t.getURL=function(e,t){var n=e.config,r=t.uuid,i=void 0===r?n.UUID:r,s=t.channels,a=void 0===s?[]:s,u=a.length>0?a.join(","):",";return"/v2/presence/sub-key/"+n.subscribeKey+"/channel/"+o.default.encodeString(u)+"/uuid/"+i},t.getRequestTimeout=function(e){return e.config.getTransactionTimeout()},t.isAuthSupported=function(){return!0},t.prepareParams=function(e,t){var n=t.channelGroups,r=void 0===n?[]:n,i={};return r.length>0&&(i["channel-group"]=r.join(",")),i},t.handleResponse=function(e,t,n){var r=n.channels,i=void 0===r?[]:r,o=n.channelGroups,s=void 0===o?[]:o,a={};return 1===i.length&&0===s.length?a[i[0]]=t.payload:a=t.payload,{channels:a}};var i=r((n(5),n(13))),o=r(n(15))},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0}),t.getOperation=function(){return i.default.PNSetStateOperation},t.validateParams=function(e,t){var n=e.config,r=t.state,i=t.channels,o=void 0===i?[]:i,s=t.channelGroups,a=void 0===s?[]:s;return r?n.subscribeKey?0===o.length&&0===a.length?"Please provide a list of channels and/or channel-groups":void 0:"Missing Subscribe Key":"Missing State"},t.getURL=function(e,t){var n=e.config,r=t.channels,i=void 0===r?[]:r,s=i.length>0?i.join(","):",";return"/v2/presence/sub-key/"+n.subscribeKey+"/channel/"+o.default.encodeString(s)+"/uuid/"+n.UUID+"/data"},t.getRequestTimeout=function(e){return e.config.getTransactionTimeout()},t.isAuthSupported=function(){return!0},t.prepareParams=function(e,t){var n=t.state,r=t.channelGroups,i=void 0===r?[]:r,o={};return o.state=JSON.stringify(n),i.length>0&&(o["channel-group"]=i.join(",")),o},t.handleResponse=function(e,t){return{state:t.payload}};var i=r((n(5),n(13))),o=r(n(15))},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0}),t.getOperation=function(){return i.default.PNHereNowOperation},t.validateParams=function(e){if(!e.config.subscribeKey)return"Missing Subscribe Key"},t.getURL=function(e,t){var n=e.config,r=t.channels,i=void 0===r?[]:r,s=t.channelGroups,a=void 0===s?[]:s,u="/v2/presence/sub-key/"+n.subscribeKey;if(i.length>0||a.length>0){var c=i.length>0?i.join(","):",";u+="/channel/"+o.default.encodeString(c)}return u},t.getRequestTimeout=function(e){return e.config.getTransactionTimeout()},t.isAuthSupported=function(){return!0},t.prepareParams=function(e,t){var n=t.channelGroups,r=void 0===n?[]:n,i=t.includeUUIDs,o=void 0===i||i,s=t.includeState,a=void 0!==s&&s,u={};return o||(u.disable_uuids=1),a&&(u.state=1),r.length>0&&(u["channel-group"]=r.join(",")),u},t.handleResponse=function(e,t,n){var r=n.channels,i=void 0===r?[]:r,o=n.channelGroups,s=void 0===o?[]:o,a=n.includeUUIDs,u=void 0===a||a,c=n.includeState,l=void 0!==c&&c;return i.length>1||s.length>0||0===s.length&&0===i.length?function(){var e={};return e.totalChannels=t.payload.total_channels,e.totalOccupancy=t.payload.total_occupancy,e.channels={},Object.keys(t.payload.channels).forEach(function(n){var r=t.payload.channels[n],i=[];return e.channels[n]={occupants:i,name:n,occupancy:r.occupancy},u&&r.uuids.forEach(function(e){l?i.push({state:e.state,uuid:e.uuid}):i.push({state:null,uuid:e})}),e}),e}():function(){var e={},n=[];return e.totalChannels=1,e.totalOccupancy=t.occupancy,e.channels={},e.channels[i[0]]={occupants:n,name:i[0],occupancy:t.occupancy},u&&t.uuids&&t.uuids.forEach(function(e){l?n.push({state:e.state,uuid:e.uuid}):n.push({state:null,uuid:e})}),e}()};var i=r((n(5),n(13))),o=r(n(15))},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getOperation=function(){return r.default.PNAccessManagerAudit},t.validateParams=function(e){if(!e.config.subscribeKey)return"Missing Subscribe Key"},t.getURL=function(e){return"/v2/auth/audit/sub-key/"+e.config.subscribeKey},t.getRequestTimeout=function(e){return e.config.getTransactionTimeout()},t.isAuthSupported=function(){return!1},t.prepareParams=function(e,t){var n=t.channel,r=t.channelGroup,i=t.authKeys,o=void 0===i?[]:i,s={};return n&&(s.channel=n),r&&(s["channel-group"]=r),o.length>0&&(s.auth=o.join(",")),s},t.handleResponse=function(e,t){return t.payload};var r=function(e){return e&&e.__esModule?e:{default:e}}((n(5),n(13)))},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getOperation=function(){return r.default.PNAccessManagerGrant},t.validateParams=function(e){var t=e.config;return t.subscribeKey?t.publishKey?t.secretKey?void 0:"Missing Secret Key":"Missing Publish Key":"Missing Subscribe Key"},t.getURL=function(e){return"/v2/auth/grant/sub-key/"+e.config.subscribeKey},t.getRequestTimeout=function(e){return e.config.getTransactionTimeout()},t.isAuthSupported=function(){return!1},t.prepareParams=function(e,t){var n=t.channels,r=void 0===n?[]:n,i=t.channelGroups,o=void 0===i?[]:i,s=t.ttl,a=t.read,u=void 0!==a&&a,c=t.write,l=void 0!==c&&c,f=t.manage,h=void 0!==f&&f,p=t.authKeys,d=void 0===p?[]:p,g={};return g.r=u?"1":"0",g.w=l?"1":"0",g.m=h?"1":"0",r.length>0&&(g.channel=r.join(",")),o.length>0&&(g["channel-group"]=o.join(",")),d.length>0&&(g.auth=d.join(",")),(s||0===s)&&(g.ttl=s),g},t.handleResponse=function(){return{}};var r=function(e){return e&&e.__esModule?e:{default:e}}((n(5),n(13)))},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}function i(e,t){var n=e.crypto,r=e.config,i=JSON.stringify(t);return r.cipherKey&&(i=n.encrypt(i),i=JSON.stringify(i)),i}Object.defineProperty(t,"__esModule",{value:!0});var o="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e};t.getOperation=function(){return s.default.PNPublishOperation},t.validateParams=function(e,t){var n=e.config,r=t.message;return t.channel?r?n.subscribeKey?void 0:"Missing Subscribe Key":"Missing Message":"Missing Channel"},t.usePost=function(e,t){var n=t.sendByPost;return void 0!==n&&n},t.getURL=function(e,t){var n=e.config,r=t.channel,o=i(e,t.message);return"/publish/"+n.publishKey+"/"+n.subscribeKey+"/0/"+a.default.encodeString(r)+"/0/"+a.default.encodeString(o)},t.postURL=function(e,t){var n=e.config,r=t.channel;return"/publish/"+n.publishKey+"/"+n.subscribeKey+"/0/"+a.default.encodeString(r)+"/0"},t.getRequestTimeout=function(e){return e.config.getTransactionTimeout()},t.isAuthSupported=function(){return!0},t.postPayload=function(e,t){return i(e,t.message)},t.prepareParams=function(e,t){var n=t.meta,r=t.replicate,i=void 0===r||r,s=t.storeInHistory,a=t.ttl,u={};return null!=s&&(u.store=s?"1":"0"),a&&(u.ttl=a),!1===i&&(u.norep="true"),n&&"object"===(void 0===n?"undefined":o(n))&&(u.meta=JSON.stringify(n)),u},t.handleResponse=function(e,t){return{timetoken:t[2]}};var s=r((n(5),n(13))),a=r(n(15))},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0}),t.getOperation=function(){return i.default.PNHistoryOperation},t.validateParams=function(e,t){var n=t.channel,r=e.config;return n?r.subscribeKey?void 0:"Missing Subscribe Key":"Missing channel"},t.getURL=function(e,t){var n=t.channel;return"/v2/history/sub-key/"+e.config.subscribeKey+"/channel/"+o.default.encodeString(n)},t.getRequestTimeout=function(e){return e.config.getTransactionTimeout()},t.isAuthSupported=function(){return!0},t.prepareParams=function(e,t){var n=t.start,r=t.end,i=t.reverse,o=t.count,s=void 0===o?100:o,a=t.stringifiedTimeToken,u=void 0!==a&&a,c={include_token:"true"};return c.count=s,n&&(c.start=n),r&&(c.end=r),u&&(c.string_message_token="true"),null!=i&&(c.reverse=i.toString()),c},t.handleResponse=function(e,t){var n={messages:[],startTimeToken:t[1],endTimeToken:t[2]};return t[0].forEach(function(t){var r={timetoken:t.timetoken,entry:function(e,t){var n=e.config,r=e.crypto;if(!n.cipherKey)return t;try{return r.decrypt(t)}catch(e){return t}}(e,t.message)};n.messages.push(r)}),n};var i=r((n(5),n(13))),o=r(n(15))},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0}),t.getOperation=function(){return i.default.PNDeleteMessagesOperation},t.validateParams=function(e,t){var n=t.channel,r=e.config;return n?r.subscribeKey?void 0:"Missing Subscribe Key":"Missing channel"},t.useDelete=function(){return!0},t.getURL=function(e,t){var n=t.channel,r=t.start,i=t.end,s=e.config,a="";return r&&(a="?start="+r),i&&(a+=(""!==a?"&":"?")+"end="+i),"/v3/history/sub-key/"+s.subscribeKey+"/channel/"+o.default.encodeString(n)+a},t.getRequestTimeout=function(e){return e.config.getTransactionTimeout()},t.isAuthSupported=function(){return!0},t.prepareParams=function(e,t){var n=t.start,r=t.end,i={};return n&&(i.start=n),r&&(i.end=r),{}},t.handleResponse=function(e,t){return t.payload};var i=r((n(5),n(13))),o=r(n(15))},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0}),t.getOperation=function(){return i.default.PNFetchMessagesOperation},t.validateParams=function(e,t){var n=t.channels,r=e.config;return n&&0!==n.length?r.subscribeKey?void 0:"Missing Subscribe Key":"Missing channels"},t.getURL=function(e,t){var n=t.channels,r=void 0===n?[]:n,i=e.config,s=r.length>0?r.join(","):",";return"/v3/history/sub-key/"+i.subscribeKey+"/channel/"+o.default.encodeString(s)},t.getRequestTimeout=function(e){return e.config.getTransactionTimeout()},t.isAuthSupported=function(){return!0},t.prepareParams=function(e,t){var n=t.start,r=t.end,i=t.count,o={};return i&&(o.max=i),n&&(o.start=n),r&&(o.end=r),o},t.handleResponse=function(e,t){var n={channels:{}};return Object.keys(t.channels||{}).forEach(function(r){n.channels[r]=[],(t.channels[r]||[]).forEach(function(t){var i={};i.channel=r,i.subscription=null,i.timetoken=t.timetoken,i.message=function(e,t){var n=e.config,r=e.crypto;if(!n.cipherKey)return t;try{return r.decrypt(t)}catch(e){return t}}(e,t.message),n.channels[r].push(i)})}),n};var i=r((n(5),n(13))),o=r(n(15))},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0}),t.getOperation=function(){return i.default.PNSubscribeOperation},t.validateParams=function(e){if(!e.config.subscribeKey)return"Missing Subscribe Key"},t.getURL=function(e,t){var n=e.config,r=t.channels,i=void 0===r?[]:r,s=i.length>0?i.join(","):",";return"/v2/subscribe/"+n.subscribeKey+"/"+o.default.encodeString(s)+"/0"},t.getRequestTimeout=function(e){return e.config.getSubscribeTimeout()},t.isAuthSupported=function(){return!0},t.prepareParams=function(e,t){var n=e.config,r=t.channelGroups,i=void 0===r?[]:r,o=t.timetoken,s=t.filterExpression,a=t.region,u={heartbeat:n.getPresenceTimeout()};return i.length>0&&(u["channel-group"]=i.join(",")),s&&s.length>0&&(u["filter-expr"]=s),o&&(u.tt=o),a&&(u.tr=a),u},t.handleResponse=function(e,t){var n=[];t.m.forEach(function(e){var t={publishTimetoken:e.p.t,region:e.p.r},r={shard:parseInt(e.a,10),subscriptionMatch:e.b,channel:e.c,payload:e.d,flags:e.f,issuingClientId:e.i,subscribeKey:e.k,originationTimetoken:e.o,userMetadata:e.u,publishMetaData:t};n.push(r)});var r={timetoken:t.t.t,region:t.t.r};return{messages:n,metadata:r}};var i=r((n(5),n(13))),o=r(n(15))},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0});var i=function(){function e(e,t){for(var n=0;n=this._maxSubDomain&&(this._currentSubDomain=1),e=this._currentSubDomain.toString(),this._providedFQDN.replace("pubsub","ps"+e)}},{key:"shiftStandardOrigin",value:function(){var e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return this._standardOrigin=this.nextOrigin(e),this._standardOrigin}},{key:"getStandardOrigin",value:function(){return this._standardOrigin}},{key:"POST",value:function(e,t,n,r){return this._modules.post(e,t,n,r)}},{key:"GET",value:function(e,t,n){return this._modules.get(e,t,n)}},{key:"DELETE",value:function(e,t,n){return this._modules.del(e,t,n)}},{key:"_detectErrorCategory",value:function(e){if("ENOTFOUND"===e.code)return o.default.PNNetworkIssuesCategory;if("ECONNREFUSED"===e.code)return o.default.PNNetworkIssuesCategory;if("ECONNRESET"===e.code)return o.default.PNNetworkIssuesCategory;if("EAI_AGAIN"===e.code)return o.default.PNNetworkIssuesCategory;if(0===e.status||e.hasOwnProperty("status")&&void 0===e.status)return o.default.PNNetworkIssuesCategory;if(e.timeout)return o.default.PNTimeoutCategory;if(e.response){if(e.response.badRequest)return o.default.PNBadRequestCategory;if(e.response.forbidden)return o.default.PNAccessDeniedCategory}return o.default.PNUnknownCategory}}]),e}());t.default=s,e.exports=t.default},function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default={get:function(e){try{return localStorage.getItem(e)}catch(e){return null}},set:function(e,t){try{return localStorage.setItem(e,t)}catch(e){return null}}},e.exports=t.default},function(e,t,n){"use strict";function r(e,t,n){var r=this;return this._config.logVerbosity&&(e=e.use(function(e){var t=(new Date).getTime(),n=(new Date).toISOString(),r=console&&console.log?console:window&&window.console&&window.console.log?window.console:console;r.log("<<<<<"),r.log("["+n+"]","\n",e.url,"\n",e.qs),r.log("-----"),e.on("response",function(n){var i=(new Date).getTime()-t,o=(new Date).toISOString();r.log(">>>>>>"),r.log("["+o+" / "+i+"]","\n",e.url,"\n",e.qs,"\n",n.text),r.log("-----")})})),this._config.proxy&&this._modules.proxy&&(e=this._modules.proxy.call(this,e)),this._config.keepAlive&&this._modules.keepAlive&&(e=this._modules.keepAlive(e)),e.timeout(t.timeout).end(function(e,i){var o={};if(o.error=null!==e,o.operation=t.operation,i&&i.status&&(o.statusCode=i.status),e)return o.errorData=e,o.category=r._detectErrorCategory(e),n(o,null);var s=JSON.parse(i.text);return s.error&&1===s.error&&s.status&&s.message&&s.service?(o.errorData=s,o.statusCode=s.status,o.error=!0,o.category=r._detectErrorCategory(o),n(o,null)):n(o,s)})}Object.defineProperty(t,"__esModule",{value:!0}),t.get=function(e,t,n){var o=i.default.get(this.getStandardOrigin()+t.url).query(e);return r.call(this,o,t,n)},t.post=function(e,t,n,o){var s=i.default.post(this.getStandardOrigin()+n.url).query(e).send(t);return r.call(this,s,n,o)},t.del=function(e,t,n){var o=i.default.delete(this.getStandardOrigin()+t.url).query(e);return r.call(this,o,t,n)};var i=function(e){return e&&e.__esModule?e:{default:e}}(n(42));n(5)},function(e,t,n){function r(e){if(!p(e))return e;var t=[];for(var n in e)i(t,n,e[n]);return t.join("&")}function i(e,t,n){if(null!=n)if(Array.isArray(n))n.forEach(function(n){i(e,t,n)});else if(p(n))for(var r in n)i(e,t+"["+r+"]",n[r]);else e.push(encodeURIComponent(t)+"="+encodeURIComponent(n));else null===n&&e.push(encodeURIComponent(t))}function o(e){for(var t,n,r={},i=e.split("&"),o=0,s=i.length;o=300)&&(r=new Error(t.statusText||"Unsuccessful HTTP response"),r.original=e,r.response=t,r.status=t.status)}catch(e){r=e}r?n.callback(r,t):n.callback(null,t)})}function c(e,t){var n=d("DELETE",e);return t&&n.end(t),n}var l;"undefined"!=typeof window?l=window:"undefined"!=typeof self?l=self:(console.warn("Using browser-only version of superagent in non-browser environment"),l=this);var f=n(43),h=n(44),p=n(45),d=e.exports=n(46).bind(null,u);d.getXHR=function(){if(!(!l.XMLHttpRequest||l.location&&"file:"==l.location.protocol&&l.ActiveXObject))return new XMLHttpRequest;try{return new ActiveXObject("Microsoft.XMLHTTP")}catch(e){}try{return new ActiveXObject("Msxml2.XMLHTTP.6.0")}catch(e){}try{return new ActiveXObject("Msxml2.XMLHTTP.3.0")}catch(e){}try{return new ActiveXObject("Msxml2.XMLHTTP")}catch(e){}throw Error("Browser-only verison of superagent could not find XHR")};var g="".trim?function(e){return e.trim()}:function(e){return e.replace(/(^\s*|\s*$)/g,"")};d.serializeObject=r,d.parseString=o,d.types={html:"text/html",json:"application/json",xml:"application/xml",urlencoded:"application/x-www-form-urlencoded",form:"application/x-www-form-urlencoded","form-data":"application/x-www-form-urlencoded"},d.serialize={"application/x-www-form-urlencoded":r,"application/json":JSON.stringify},d.parse={"application/x-www-form-urlencoded":o,"application/json":JSON.parse},a.prototype.get=function(e){return this.header[e.toLowerCase()]},a.prototype._setHeaderProperties=function(e){var t=this.header["content-type"]||"";this.type=function(e){return e.split(/ *; */).shift()}(t);var n=function(e){return e.split(/ *; */).reduce(function(e,t){var n=t.split(/ *= */),r=n.shift(),i=n.shift();return r&&i&&(e[r]=i),e},{})}(t);for(var r in n)this[r]=n[r]},a.prototype._parseBody=function(e){var t=d.parse[this.type];return!t&&s(this.type)&&(t=d.parse["application/json"]),t&&e&&(e.length||e instanceof Object)?t(e):null},a.prototype._setStatusProperties=function(e){1223===e&&(e=204);var t=e/100|0;this.status=this.statusCode=e,this.statusType=t,this.info=1==t,this.ok=2==t,this.clientError=4==t,this.serverError=5==t,this.error=(4==t||5==t)&&this.toError(),this.accepted=202==e,this.noContent=204==e,this.badRequest=400==e,this.unauthorized=401==e,this.notAcceptable=406==e,this.notFound=404==e,this.forbidden=403==e},a.prototype.toError=function(){var e=this.req,t=e.method,n=e.url,r="cannot "+t+" "+n+" ("+this.status+")",i=new Error(r);return i.status=this.status,i.method=t,i.url=n,i},d.Response=a,f(u.prototype);for(var y in h)u.prototype[y]=h[y];u.prototype.type=function(e){return this.set("Content-Type",d.types[e]||e),this},u.prototype.responseType=function(e){return this._responseType=e,this},u.prototype.accept=function(e){return this.set("Accept",d.types[e]||e),this},u.prototype.auth=function(e,t,n){switch(n||(n={type:"basic"}),n.type){case"basic":var r=btoa(e+":"+t);this.set("Authorization","Basic "+r);break;case"auto":this.username=e,this.password=t}return this},u.prototype.query=function(e){return"string"!=typeof e&&(e=r(e)),e&&this._query.push(e),this},u.prototype.attach=function(e,t,n){return this._getFormData().append(e,t,n||t.name),this},u.prototype._getFormData=function(){return this._formData||(this._formData=new l.FormData),this._formData},u.prototype.callback=function(e,t){var n=this._callback;this.clearTimeout(),n(e,t)},u.prototype.crossDomainError=function(){var e=new Error("Request has been terminated\nPossible causes: the network is offline, Origin is not allowed by Access-Control-Allow-Origin, the page is being unloaded, etc.");e.crossDomain=!0,e.status=this.status,e.method=this.method,e.url=this.url,this.callback(e)},u.prototype._timeoutError=function(){var e=this._timeout,t=new Error("timeout of "+e+"ms exceeded");t.timeout=e,this.callback(t)},u.prototype._appendQueryString=function(){var e=this._query.join("&");e&&(this.url+=~this.url.indexOf("?")?"&"+e:"?"+e)},u.prototype.end=function(e){var t=this,n=this.xhr=d.getXHR(),r=this._timeout,i=this._formData||this._data;this._callback=e||function(){},n.onreadystatechange=function(){if(4==n.readyState){var e;try{e=n.status}catch(t){e=0}if(0==e){if(t.timedout)return t._timeoutError();if(t._aborted)return;return t.crossDomainError()}t.emit("end")}};var o=function(e,n){n.total>0&&(n.percent=n.loaded/n.total*100),n.direction=e,t.emit("progress",n)};if(this.hasListeners("progress"))try{n.onprogress=o.bind(null,"download"),n.upload&&(n.upload.onprogress=o.bind(null,"upload"))}catch(e){}if(r&&!this._timer&&(this._timer=setTimeout(function(){t.timedout=!0,t.abort()},r)),this._appendQueryString(),this.username&&this.password?n.open(this.method,this.url,!0,this.username,this.password):n.open(this.method,this.url,!0),this._withCredentials&&(n.withCredentials=!0),"GET"!=this.method&&"HEAD"!=this.method&&"string"!=typeof i&&!this._isHost(i)){var a=this._header["content-type"],u=this._serializer||d.serialize[a?a.split(";")[0]:""];!u&&s(a)&&(u=d.serialize["application/json"]),u&&(i=u(i))}for(var c in this.header)null!=this.header[c]&&n.setRequestHeader(c,this.header[c]);return this._responseType&&(n.responseType=this._responseType),this.emit("request",this),n.send(void 0!==i?i:null),this},d.Request=u,d.get=function(e,t,n){var r=d("GET",e);return"function"==typeof t&&(n=t,t=null),t&&r.query(t),n&&r.end(n),r},d.head=function(e,t,n){var r=d("HEAD",e);return"function"==typeof t&&(n=t,t=null),t&&r.send(t),n&&r.end(n),r},d.options=function(e,t,n){var r=d("OPTIONS",e);return"function"==typeof t&&(n=t,t=null),t&&r.send(t),n&&r.end(n),r},d.del=c,d.delete=c,d.patch=function(e,t,n){var r=d("PATCH",e);return"function"==typeof t&&(n=t,t=null),t&&r.send(t),n&&r.end(n),r},d.post=function(e,t,n){var r=d("POST",e);return"function"==typeof t&&(n=t,t=null),t&&r.send(t),n&&r.end(n),r},d.put=function(e,t,n){var r=d("PUT",e);return"function"==typeof t&&(n=t,t=null),t&&r.send(t),n&&r.end(n),r}},function(e,t,n){function r(e){if(e)return function(e){for(var t in r.prototype)e[t]=r.prototype[t];return e}(e)}e.exports=r,r.prototype.on=r.prototype.addEventListener=function(e,t){return this._callbacks=this._callbacks||{},(this._callbacks["$"+e]=this._callbacks["$"+e]||[]).push(t),this},r.prototype.once=function(e,t){function n(){this.off(e,n),t.apply(this,arguments)}return n.fn=t,this.on(e,n),this},r.prototype.off=r.prototype.removeListener=r.prototype.removeAllListeners=r.prototype.removeEventListener=function(e,t){if(this._callbacks=this._callbacks||{},0==arguments.length)return this._callbacks={},this;var n=this._callbacks["$"+e];if(!n)return this;if(1==arguments.length)return delete this._callbacks["$"+e],this;for(var r,i=0;i3)for(t=new Array(a),i=0;i3)for(t=new Array(a-1),i=1;i3)for(t=new Array(u),i=1;i3)for(t=new Array(u-1),i=1;i0&&o._listeners.length>this._events.maxListeners&&(o._listeners.warned=!0,a.call(this,o._listeners.length,s))):o._listeners=t,!0;s=e.shift()}return!0}.call(this,e,t),this):(this._events[e]?("function"==typeof this._events[e]&&(this._events[e]=[this._events[e]]),this._events[e].push(t),!this._events[e].warned&&this._events.maxListeners>0&&this._events[e].length>this._events.maxListeners&&(this._events[e].warned=!0,a.call(this,this._events[e].length,e))):this._events[e]=t,this)},u.prototype.onAny=function(e){if("function"!=typeof e)throw new Error("onAny only accepts instances of Function");return this._all||(this._all=[]),this._all.push(e),this},u.prototype.addListener=u.prototype.on,u.prototype.off=function(e,t){function n(e){if(e!==i){var t=Object.keys(e);for(var r in t){var o=t[r],s=e[o];s instanceof Function||"object"!=typeof s||null===s||(Object.keys(s).length>0&&n(e[o]),0===Object.keys(s).length&&delete e[o])}}}if("function"!=typeof t)throw new Error("removeListener only takes instances of Function");var r,o=[];if(this.wildcard){var s="string"==typeof e?e.split(this.delimiter):e.slice();o=c.call(this,null,s,this.listenerTree,0)}else{if(!this._events[e])return this;r=this._events[e],o.push({_listeners:r})}for(var a=0;a0){for(n=0,r=(t=this._all).length;n{this.userUpdate(e.uuid,e.state)})}}objectify(){return{channel:this.channel,group:this.group,private:this.isPrivate,meta:this.meta}}invite(e){this.chatEngine.request("post","invite",{to:e.uuid,chat:this.objectify()}).then(()=>{let t=()=>{e.direct.emit("$.invite",{channel:this.channel})};e.direct.connected?t():(e.direct.connect(),e.direct.on("$.connected",t))}).catch(e=>{this.chatEngine.throwError(this,"trigger","auth",new Error("Something went wrong while making a request to authentication server."),{error:e})})}onPresence(e){if("join"===e.action){let t=this.createUser(e.uuid,e.state);this.users[t.uuid]||this.trigger("$.online.join",{user:t})}"leave"===e.action&&this.userLeave(e.uuid),"timeout"===e.action&&this.userDisconnect(e.uuid),"state-change"===e.action&&this.userUpdate(e.uuid,e.state)}update(e){let t=this.meta||{};this.meta=Object.assign(t,e),this.chatEngine.request("post","chat",{chat:this.objectify()}).then(()=>{}).catch(e=>{this.chatEngine.throwError(this,"trigger","auth",new Error("Something went wrong while making a request to authentication server."),{error:e})})}emit(e,t){if("message"===e&&"object"!=typeof t)throw new Error("the payload has to be an object");let n={data:t,sender:this.chatEngine.me.uuid,chat:this,event:e,chatengineSDK:this.chatEngine.package.version};this.runPluginQueue("emit",e,e=>{e(null,n)},(t,n)=>{delete n.chat,this.events[e]=this.events[e]||new o(this.chatEngine,this,e),this.events[e].publish(n)})}createUser(e,t){return this.chatEngine.users[e]=this.chatEngine.users[e]||new this.chatEngine.User(e),this.chatEngine.users[e].assign(t),this.users[e]||this.trigger("$.online.here",{user:this.chatEngine.users[e]}),this.users[e]=this.chatEngine.users[e],this.chatEngine.users[e]}userUpdate(e,t){this.chatEngine.users[e]=this.chatEngine.users[e]||new this.chatEngine.User(e),this.users[e]||this.createUser(e,t),this.users[e].assign(t),this.chatEngine._emit("$.state",{user:this.users[e],state:this.users[e].state})}leave(){this.chatEngine.pubnub.unsubscribe({channels:[this.channel]}),this.chatEngine.request("post","leave",{chat:this.objectify()}).then(()=>{this.connected=!1,this.trigger("$.disconnected"),this.chatEngine.me.sync.emit("$.session.chat.leave",{subject:this.objectify()})}).catch(e=>{this.chatEngine.throwError(this,"trigger","auth",new Error("Something went wrong while making a request to chat server."),{error:e})})}userLeave(e){this.users[e]&&(this.trigger("$.offline.leave",{user:this.users[e]}),delete this.users[e])}userDisconnect(e){this.users[e]&&this.trigger("$.offline.disconnect",{user:this.users[e]})}setState(e){this.chatEngine.pubnub.setState({state:e,channels:[this.chatEngine.global.channel]},()=>{})}search(e){return new s(this.chatEngine,this,e)}onConnectionReady(){this.trigger("$.connected"),this.chatEngine.me.sync.emit("$.session.chat.join",{subject:this.objectify()}),this.connected=!0,this.users[this.chatEngine.me.uuid]=this.chatEngine.me,this.trigger("$.online.join",{user:this.chatEngine.me}),this.channel!==this.chatEngine.global.channel&&"custom"===this.group&&(this.getUserUpdates(),setTimeout(()=>{this.getUserUpdates()},5e3))}getUserUpdates(){this.chatEngine.pubnub.hereNow({channels:[this.channel],includeUUIDs:!0,includeState:!0},this.onHereNow.bind(this))}connect(){r.waterfall([e=>{this.chatEngine.pubnub?e():e("You must call ChatEngine.connect() and wait for the $.ready event before creating new Chats.")},e=>{this.chatEngine.request("post","grant",{chat:this.objectify()}).then(()=>{e()}).catch(e)},e=>{this.chatEngine.request("post","join",{chat:this.objectify()}).then(()=>{e()}).catch(e)},e=>{this.chatEngine.request("get","chat",{},{channel:this.channel}).then(e=>{e.data.found?this.meta=e.data.chat.meta:this.update(this.meta),this.onConnectionReady()}).catch(e)}],e=>{this.chatEngine.throwError(this,"trigger","auth",new Error("Something went wrong while making a request to authentication server."),{error:e})})}}e.exports=a},function(e,t,n){(function(e,t){!function(e,n){"use strict";function r(e){delete a[e]}function i(e){if(u)setTimeout(i,0,e);else{var t=a[e];if(t){u=!0;try{!function(e){var t=e.callback,r=e.args;switch(r.length){case 0:t();break;case 1:t(r[0]);break;case 2:t(r[0],r[1]);break;case 3:t(r[0],r[1],r[2]);break;default:t.apply(n,r)}}(t)}finally{r(e),u=!1}}}}if(!e.setImmediate){var o,s=1,a={},u=!1,c=e.document,l=Object.getPrototypeOf&&Object.getPrototypeOf(e);l=l&&l.setTimeout?l:e,"[object process]"==={}.toString.call(e.process)?o=function(e){t.nextTick(function(){i(e)})}:function(){if(e.postMessage&&!e.importScripts){var t=!0,n=e.onmessage;return e.onmessage=function(){t=!1},e.postMessage("","*"),e.onmessage=n,t}}()?function(){var t="setImmediate$"+Math.random()+"$",n=function(n){n.source===e&&"string"==typeof n.data&&0===n.data.indexOf(t)&&i(+n.data.slice(t.length))};e.addEventListener?e.addEventListener("message",n,!1):e.attachEvent("onmessage",n),o=function(n){e.postMessage(t+n,"*")}}():e.MessageChannel?function(){var e=new MessageChannel;e.port1.onmessage=function(e){i(e.data)},o=function(t){e.port2.postMessage(t)}}():c&&"onreadystatechange"in c.createElement("script")?function(){var e=c.documentElement;o=function(t){var n=c.createElement("script");n.onreadystatechange=function(){i(t),n.onreadystatechange=null,e.removeChild(n),n=null},e.appendChild(n)}}():o=function(e){setTimeout(i,0,e)},l.setImmediate=function(e){"function"!=typeof e&&(e=new Function(""+e));for(var t=new Array(arguments.length-1),n=0;n(e.sort((e,n)=>{let r=t?n:e,i=t?e:n;return parseInt(r.timetoken,10)-parseInt(i.timetoken,10)}),e)),this.page=(e=>{this._emit("$.search.page.request"),this.config.start=this.config.reverse?this.lastTT:this.firstTT,this.firstPage=!1,this.chatEngine.pubnub.history(this.config,(t,n)=>{this._emit("$.search.page.response"),t.error?this.chatEngine.throwError(this,"trigger","search",new Error("There was a problem searching history. Make sure your request parameters are valid and history is enabled for this PubNub key."),t):(this.firstTT=n.startTimeToken,this.lastTT=n.endTimeToken,n.messages=this.sortHistory(n.messages),e(n))})});this.needleCount=0,this.triggerHistory=((e,t)=>{this.needleCount{e||(this.needleCount+=1),t()}):t()}),this.maxPage=10,this.numPage=0,this.next=(()=>{this.maxPage=this.maxPage+this.config.pages,this.find()}),this.find=(()=>(this.page(e=>{this.config.reverse||e.messages.reverse(),i(e.messages,this.triggerHistory,()=>{this.numPage===this.maxPage?this._emit("$.search.pause"):e.messages&&e.messages.length===this.config.count&&this.needleCount({middleware:{on:{"*":(t,n)=>{n(!(t&&t.event&&t.event===e),t)}}}}))(this.config.event)),this.config.sender&&this.plugin((e=>({middleware:{on:{"*":(t,n)=>{n(!(t&&t.sender&&t.sender.uuid===e.uuid),t)}}}}))(this.config.sender)),this._emit("$.search.start"),this.find()}}e.exports=o},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0});var i=r(n(62)),o=r(n(87));t.default=(0,o.default)(i.default,1),e.exports=t.default},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e,t,n,r){(0,i.default)(t)(e,(0,o.default)((0,s.default)(n)),r)};var i=r(n(63)),o=r(n(86)),s=r(n(21));e.exports=t.default},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e){return function(t,n,r){function c(){for(;h-1&&e%1==0&&e{this.addChatToSession(e.data.subject)}),this.sync.on("$.session.chat.leave",e=>{this.removeChatFromSession(e.data.subject)}),this}assign(e){super.update(e)}update(e){super.update(e),this.chatEngine.global.setState(e)}addChatToSession(e){this.session[e.group]=this.session[e.group]||{};let t=this.chatEngine.chats[e.channel];t?this.session[e.group][e.channel]=t:(this.session[e.group][e.channel]=new this.chatEngine.Chat(e.channel,e.private,!1,e.meta,e.group),this.trigger("$.session.chat.join",{chat:this.session[e.group][e.channel]}))}removeChatFromSession(e){this.session[e.group]&&this.session[e.group][e.channel]&&(e=this.session[e.group][e.channel]||e,delete this.chatEngine.chats[e.channel],delete this.session[e.group][e.channel],this.trigger("$.session.chat.leave",{chat:e}))}}e.exports=i}])}); \ No newline at end of file diff --git a/dist/stats.json b/dist/stats.json index ac652560..fa23f673 100644 --- a/dist/stats.json +++ b/dist/stats.json @@ -1 +1 @@ -{"errors":[],"warnings":[],"version":"3.7.1","hash":"06ed435f47757a7b2c11","publicPath":"","assetsByChunkName":{"main":"chat-engine.js"},"assets":[{"name":"chat-engine.js","size":459380,"chunks":[0],"chunkNames":["main"],"emitted":true},{"name":"stats.json","size":0,"chunks":[],"chunkNames":[]}],"filteredAssets":0,"entrypoints":{"main":{"chunks":[0],"assets":["chat-engine.js"]}},"chunks":[{"id":0,"rendered":true,"initial":true,"entry":true,"extraAsync":false,"size":449025,"names":["main"],"files":["chat-engine.js"],"hash":"49563d2d226b611c3dbc","parents":[],"modules":[{"id":3,"identifier":"/Users/max/Desktop/CLIENT/chat-engine/node_modules/webpack/buildin/global.js","name":"(webpack)/buildin/global.js","index":37,"index2":31,"size":509,"cacheable":true,"built":true,"optional":false,"prefetched":false,"chunks":[0],"assets":[],"issuer":"/Users/max/Desktop/CLIENT/chat-engine/node_modules/async/dist/async.js","issuerId":15,"issuerName":"./node_modules/async/dist/async.js","profile":{"factory":218,"building":38},"failed":false,"errors":0,"warnings":0,"reasons":[{"moduleId":15,"moduleIdentifier":"/Users/max/Desktop/CLIENT/chat-engine/node_modules/async/dist/async.js","module":"./node_modules/async/dist/async.js","moduleName":"./node_modules/async/dist/async.js","type":"cjs require","userRequest":"global","loc":"1:0-44"},{"moduleId":27,"moduleIdentifier":"/Users/max/Desktop/CLIENT/chat-engine/node_modules/lodash/_freeGlobal.js","module":"./node_modules/lodash/_freeGlobal.js","moduleName":"./node_modules/lodash/_freeGlobal.js","type":"cjs require","userRequest":"global","loc":"1:0-41"},{"moduleId":55,"moduleIdentifier":"/Users/max/Desktop/CLIENT/chat-engine/node_modules/setimmediate/setImmediate.js","module":"./node_modules/setimmediate/setImmediate.js","moduleName":"./node_modules/setimmediate/setImmediate.js","type":"cjs require","userRequest":"global","loc":"1:0-41"}],"usedExports":true,"providedExports":null,"optimizationBailout":[],"depth":3,"source":"var g;\r\n\r\n// This works in non-strict mode\r\ng = (function() {\r\n\treturn this;\r\n})();\r\n\r\ntry {\r\n\t// This works if eval is allowed (see CSP)\r\n\tg = g || Function(\"return this\")() || (1,eval)(\"this\");\r\n} catch(e) {\r\n\t// This works if the window reference is available\r\n\tif(typeof window === \"object\")\r\n\t\tg = window;\r\n}\r\n\r\n// g can still be undefined, but nothing to do about it...\r\n// We return undefined, instead of nothing here, so it's\r\n// easier to handle this case. if(!global) { ...}\r\n\r\nmodule.exports = g;\r\n"},{"id":4,"identifier":"/Users/max/Desktop/CLIENT/chat-engine/node_modules/webpack/buildin/module.js","name":"(webpack)/buildin/module.js","index":38,"index2":34,"size":517,"cacheable":true,"built":true,"optional":false,"prefetched":false,"chunks":[0],"assets":[],"issuer":"/Users/max/Desktop/CLIENT/chat-engine/node_modules/async/dist/async.js","issuerId":15,"issuerName":"./node_modules/async/dist/async.js","profile":{"factory":218,"building":39},"failed":false,"errors":0,"warnings":0,"reasons":[{"moduleId":15,"moduleIdentifier":"/Users/max/Desktop/CLIENT/chat-engine/node_modules/async/dist/async.js","module":"./node_modules/async/dist/async.js","moduleName":"./node_modules/async/dist/async.js","type":"cjs require","userRequest":"module","loc":"1:0-44"},{"moduleId":74,"moduleIdentifier":"/Users/max/Desktop/CLIENT/chat-engine/node_modules/lodash/isBuffer.js","module":"./node_modules/lodash/isBuffer.js","moduleName":"./node_modules/lodash/isBuffer.js","type":"cjs require","userRequest":"module","loc":"1:0-41"},{"moduleId":80,"moduleIdentifier":"/Users/max/Desktop/CLIENT/chat-engine/node_modules/lodash/_nodeUtil.js","module":"./node_modules/lodash/_nodeUtil.js","moduleName":"./node_modules/lodash/_nodeUtil.js","type":"cjs require","userRequest":"module","loc":"1:0-41"}],"usedExports":true,"providedExports":null,"optimizationBailout":[],"depth":3,"source":"module.exports = function(module) {\r\n\tif(!module.webpackPolyfill) {\r\n\t\tmodule.deprecate = function() {};\r\n\t\tmodule.paths = [];\r\n\t\t// module.parent = undefined by default\r\n\t\tif(!module.children) module.children = [];\r\n\t\tObject.defineProperty(module, \"loaded\", {\r\n\t\t\tenumerable: true,\r\n\t\t\tget: function() {\r\n\t\t\t\treturn module.l;\r\n\t\t\t}\r\n\t\t});\r\n\t\tObject.defineProperty(module, \"id\", {\r\n\t\t\tenumerable: true,\r\n\t\t\tget: function() {\r\n\t\t\t\treturn module.i;\r\n\t\t\t}\r\n\t\t});\r\n\t\tmodule.webpackPolyfill = 1;\r\n\t}\r\n\treturn module;\r\n};\r\n"},{"id":5,"identifier":"/Users/max/Desktop/CLIENT/chat-engine/src/modules/emitter.js","name":"./src/modules/emitter.js","index":39,"index2":48,"size":7500,"cacheable":true,"built":true,"optional":false,"prefetched":false,"chunks":[0],"assets":[],"issuer":"/Users/max/Desktop/CLIENT/chat-engine/src/components/user.js","issuerId":29,"issuerName":"./src/components/user.js","profile":{"factory":47,"building":88,"dependencies":2},"failed":false,"errors":0,"warnings":0,"reasons":[{"moduleId":29,"moduleIdentifier":"/Users/max/Desktop/CLIENT/chat-engine/src/components/user.js","module":"./src/components/user.js","moduleName":"./src/components/user.js","type":"cjs require","userRequest":"../modules/emitter","loc":"1:16-45"},{"moduleId":54,"moduleIdentifier":"/Users/max/Desktop/CLIENT/chat-engine/src/components/chat.js","module":"./src/components/chat.js","moduleName":"./src/components/chat.js","type":"cjs require","userRequest":"../modules/emitter","loc":"2:16-45"},{"moduleId":60,"moduleIdentifier":"/Users/max/Desktop/CLIENT/chat-engine/src/components/search.js","module":"./src/components/search.js","moduleName":"./src/components/search.js","type":"cjs require","userRequest":"../modules/emitter","loc":"1:16-45"}],"usedExports":true,"providedExports":null,"optimizationBailout":[],"depth":3,"source":"const waterfall = require('async/waterfall');\nconst RootEmitter = require('./root_emitter');\nconst Event = require('../components/event');\n\n/**\n An ChatEngine generic emitter that supports plugins and forwards\n events to the root emitter.\n @class Emitter\n @extends RootEmitter\n */\nclass Emitter extends RootEmitter {\n\n constructor(chatEngine) {\n\n super();\n\n this.chatEngine = chatEngine;\n\n this.name = 'Emitter';\n\n /**\n Stores a list of plugins bound to this object\n @private\n */\n this.plugins = [];\n\n /**\n Stores in memory keys and values\n @private\n */\n this._dataset = {};\n\n /**\n Emit events locally.\n\n @private\n @param {String} event The event payload object\n */\n this._emit = (event, data = {}) => {\n\n // all events are forwarded to ChatEngine object\n // so you can globally bind to events with ChatEngine.on()\n this.chatEngine._emit(event, data, this);\n\n // emit the event from the object that created it\n this.emitter.emit(event, data);\n\n return this;\n\n };\n\n /**\n * Listen for a specific event and fire a callback when it's emitted. Supports wildcard matching.\n * @method\n * @param {String} event The event name\n * @param {Function} cb The function to run when the event is emitted\n * @example\n *\n * // Get notified whenever someone joins the room\n * object.on('event', (payload) => {\n * console.log('event was fired').\n * })\n *\n * // Get notified of event.a and event.b\n * object.on('event.*', (payload) => {\n * console.log('event.a or event.b was fired').;\n * })\n */\n this.on = (event, cb) => {\n\n // keep track of all events on this emitter\n this.events[event] = this.events[event] || new Event(this.chatEngine, this, event);\n\n // call the private _on property\n this._on(event, cb);\n\n return this;\n\n };\n\n }\n\n // add an object as a subobject under a namespoace\n addChild(childName, childOb) {\n // assign the new child object as a property of parent under the\n // given namespace\n this[childName] = childOb;\n\n // assign a data set for the namespace if it doesn't exist\n if (!this._dataset[childName]) {\n this._dataset[childName] = {};\n }\n\n // the new object can use ```this.parent``` to access\n // the root class\n childOb.parent = this;\n\n // bind get() and set() to the data set\n childOb.get = this.get.bind(this._dataset[childName]);\n childOb.set = this.set.bind(this._dataset[childName]);\n }\n\n get(key) {\n return this[key];\n }\n\n set(key, value) {\n if (this[key] && !value) {\n delete this[key];\n } else {\n this[key] = value;\n }\n }\n\n /**\n Binds a plugin to this object\n @param {Object} module The plugin module\n @tutorial using\n */\n plugin(module) {\n\n // add this plugin to a list of plugins for this object\n this.plugins.push(module);\n\n // see if there are plugins to attach to this class\n if (module.extends && module.extends[this.name]) {\n // attach the plugins to this class\n // under their namespace\n this.addChild(module.namespace, new module.extends[this.name]());\n\n this[module.namespace].ChatEngine = this.chatEngine;\n\n // if the plugin has a special construct function\n // run it\n if (this[module.namespace].construct) {\n this[module.namespace].construct();\n }\n\n }\n\n return this;\n\n }\n\n bindProtoPlugins() {\n\n if (this.chatEngine.protoPlugins[this.name]) {\n\n this.chatEngine.protoPlugins[this.name].forEach((module) => {\n this.plugin(module);\n });\n\n }\n\n }\n\n /**\n Broadcasts an event locally to all listeners.\n @private\n @param {String} event The event name\n @param {Object} payload The event payload object\n */\n trigger(event, payload = {}, done = () => {}) {\n\n let complete = () => {\n\n // let plugins modify the event\n this.runPluginQueue('on', event, (next) => {\n next(null, payload);\n }, (reject, pluginResponse) => {\n\n if (reject) {\n done(reject);\n } else {\n // emit this event to any listener\n this._emit(event, pluginResponse);\n done(null, event, pluginResponse);\n }\n\n });\n\n };\n\n // this can be made into plugin\n if (typeof payload === 'object') {\n\n // restore chat in payload\n if (!payload.chat) {\n payload.chat = this;\n }\n\n // if we should try to restore the sender property\n if (payload.sender) {\n\n // the user doesn't exist, create it\n payload.sender = new this.chatEngine.User(payload.sender);\n\n payload.sender._getState(() => {\n complete();\n });\n\n } else {\n // there's no \"sender\" in this object, move on\n complete();\n }\n\n } else {\n // payload is not an object, we want nothing to do with it.\n complete();\n }\n }\n\n /**\n Load plugins and attach a queue of functions to execute before and\n after events are trigger or received.\n\n @private\n @param {String} location Where in the middleeware the event should run (emit, trigger)\n @param {String} event The event name\n @param {String} first The first function to run before the plugins have run\n @param {String} last The last function to run after the plugins have run\n */\n runPluginQueue(location, event, first, last) {\n\n // this assembles a queue of functions to run as middleware\n // event is a triggered event key\n let pluginQueue = [];\n\n // the first function is always required\n pluginQueue.push(first);\n\n // look through the configured plugins\n this.plugins.forEach((pluginItem) => {\n\n // if they have defined a function to run specifically\n // for this event\n if (pluginItem.middleware && pluginItem.middleware[location]) {\n\n if (pluginItem.middleware[location][event]) {\n // add the function to the queue\n pluginQueue.push(pluginItem.middleware[location][event]);\n }\n\n if (pluginItem.middleware[location]['*']) {\n // add the function to the queue\n pluginQueue.push(pluginItem.middleware[location]['*']);\n }\n\n }\n\n });\n\n // waterfall runs the functions in assigned order\n // waiting for one to complete before moving to the next\n // when it's done, the ```last``` parameter is called\n waterfall(pluginQueue, last);\n\n }\n\n onConstructed() {\n\n this.bindProtoPlugins();\n this.trigger(['$', 'created', this.name.toLowerCase()].join('.'));\n\n }\n\n}\n\nmodule.exports = Emitter;\n"},{"id":14,"identifier":"/Users/max/Desktop/CLIENT/chat-engine/src/modules/root_emitter.js","name":"./src/modules/root_emitter.js","index":31,"index2":30,"size":4109,"cacheable":true,"built":true,"optional":false,"prefetched":false,"chunks":[0],"assets":[],"issuer":"/Users/max/Desktop/CLIENT/chat-engine/src/bootstrap.js","issuerId":31,"issuerName":"./src/bootstrap.js","profile":{"factory":10,"building":26},"failed":false,"errors":0,"warnings":0,"reasons":[{"moduleId":5,"moduleIdentifier":"/Users/max/Desktop/CLIENT/chat-engine/src/modules/emitter.js","module":"./src/modules/emitter.js","moduleName":"./src/modules/emitter.js","type":"cjs require","userRequest":"./root_emitter","loc":"2:20-45"},{"moduleId":31,"moduleIdentifier":"/Users/max/Desktop/CLIENT/chat-engine/src/bootstrap.js","module":"./src/bootstrap.js","moduleName":"./src/bootstrap.js","type":"cjs require","userRequest":"./modules/root_emitter","loc":"5:20-53"}],"usedExports":true,"providedExports":null,"optimizationBailout":[],"depth":2,"source":"\n// Allows us to create and bind to events. Everything in ChatEngine is an event\n// emitter\nconst EventEmitter2 = require('eventemitter2').EventEmitter2;\n\n/**\n* The {@link ChatEngine} object is a RootEmitter. Configures an event emitter that other ChatEngine objects inherit. Adds shortcut methods for\n* ```this.on()```, ```this.emit()```, etc.\n* @class RootEmitter\n*/\nclass RootEmitter {\n\n constructor() {\n\n /**\n * @private\n */\n this.events = {};\n\n this.name = 'RootEmitter';\n\n /**\n Create a new EventEmitter2 object for this class.\n\n @private\n */\n this.emitter = new EventEmitter2({\n wildcard: true,\n newListener: true,\n maxListeners: 50,\n verboseMemoryLeak: true\n });\n\n // we bind to make sure wildcards work\n // https://github.com/asyncly/EventEmitter2/issues/186\n\n /**\n Private emit method that broadcasts the event to listeners on this page.\n\n @private\n @param {String} event The event name\n @param {Object} the event payload\n */\n this._emit = this.emitter.emit.bind(this.emitter);\n\n /**\n Listen for a specific event and fire a callback when it's emitted. This is reserved in case ```this.on``` is overwritten.\n\n @private\n @param {String} event The event name\n @param {Function} callback The function to run when the event is emitted\n */\n\n this._on = this.emitter.on.bind(this.emitter);\n\n /**\n * Listen for a specific event and fire a callback when it's emitted. Supports wildcard matching.\n * @method\n * @param {String} event The event name\n * @param {Function} cb The function to run when the event is emitted\n * @example\n *\n * // Get notified whenever someone joins the room\n * object.on('event', (payload) => {\n * console.log('event was fired').\n * })\n *\n * // Get notified of event.a and event.b\n * object.on('event.*', (payload) => {\n * console.log('event.a or event.b was fired').;\n * })\n */\n this.on = (event, callback) => {\n\n // emit the event from the object that created it\n this.emitter.on(event, callback);\n\n return this;\n\n };\n\n /**\n * Stop a callback from listening to an event.\n * @method\n * @param {String} event The event name\n * @example\n * let callback = function(payload;) {\n * console.log('something happend!');\n * };\n * object.on('event', callback);\n * // ...\n * object.off('event', callback);\n */\n this.off = (event, callback) => {\n\n // emit the event from the object that created it\n this.emitter.off(event, callback);\n\n return this;\n\n };\n\n /**\n * Listen for any event on this object and fire a callback when it's emitted\n * @method\n * @param {Function} callback The function to run when any event is emitted. First parameter is the event name and second is the payload.\n * @example\n * object.onAny((event, payload) => {\n * console.log('All events trigger this.');\n * });\n */\n this.onAny = (event, callback) => {\n\n // emit the event from the object that created it\n this.emitter.onAny(event, callback);\n\n return this;\n\n };\n\n /**\n * Listen for an event and only fire the callback a single time\n * @method\n * @param {String} event The event name\n * @param {Function} callback The function to run once\n * @example\n * object.once('message', => (event, payload) {\n * console.log('This is only fired once!');\n * });\n */\n this.once = (event, callback) => {\n\n // emit the event from the object that created it\n this.emitter.once(event, callback);\n\n return this;\n\n };\n\n }\n\n}\n\nmodule.exports = RootEmitter;\n"},{"id":23,"identifier":"/Users/max/Desktop/CLIENT/chat-engine/src/components/event.js","name":"./src/components/event.js","index":51,"index2":47,"size":2220,"cacheable":true,"built":true,"optional":false,"prefetched":false,"chunks":[0],"assets":[],"issuer":"/Users/max/Desktop/CLIENT/chat-engine/src/components/chat.js","issuerId":54,"issuerName":"./src/components/chat.js","profile":{"factory":15,"building":90},"failed":false,"errors":0,"warnings":0,"reasons":[{"moduleId":5,"moduleIdentifier":"/Users/max/Desktop/CLIENT/chat-engine/src/modules/emitter.js","module":"./src/modules/emitter.js","moduleName":"./src/modules/emitter.js","type":"cjs require","userRequest":"../components/event","loc":"3:14-44"},{"moduleId":54,"moduleIdentifier":"/Users/max/Desktop/CLIENT/chat-engine/src/components/chat.js","module":"./src/components/chat.js","moduleName":"./src/components/chat.js","type":"cjs require","userRequest":"../components/event","loc":"3:14-44"}],"usedExports":true,"providedExports":null,"optimizationBailout":[],"depth":3,"source":"/**\n * @class Event\n * Represents an event that may be emitted or subscribed to.\n */\nclass Event {\n\n constructor(chatEngine, chat, event) {\n\n /**\n Events are always a property of a {@link Chat}. Responsible for\n listening to specific events and firing events when they occur.\n @readonly\n @type String\n @see [PubNub Channels](https://support.pubnub.com/support/solutions/articles/14000045182-what-is-a-channel-)\n */\n this.channel = chat.channel;\n\n this.chatEngine = chatEngine;\n\n this.chat = chat;\n\n this.event = event;\n\n this.name = 'Event';\n\n /**\n Forwards events to the Chat that registered the event {@link Chat}\n\n @private\n @param {Object} data The event payload object\n */\n\n // call onMessage when PubNub receives an event\n this.chatEngine.pubnub.addListener({\n message: this.onMessage.bind(this)\n });\n\n return this;\n\n }\n\n onMessage(m) {\n\n if (this.channel === m.channel && m.message.event === this.event) {\n this.chat.trigger(m.message.event, m.message);\n }\n\n }\n\n /**\n Publishes the event over the PubNub network to the {@link Event} channel\n\n @private\n @param {Object} data The event payload object\n */\n publish(m) {\n\n m.event = this.event;\n\n this.chatEngine.pubnub.publish({\n message: m,\n channel: this.channel\n }, (status) => {\n\n if (status.statusCode === 200) {\n\n /**\n * Message successfully published\n * @event Chat#$\".\"publish\".\"success\n * @param {Object} data The message object\n */\n this.chat.trigger('$.publish.success', m);\n } else {\n\n /**\n * There was a problem publishing over the PubNub network.\n * @event Chat#$\".\"error\".\"publish\n */\n this.chatEngine.throwError(this.chat, 'trigger', 'publish', new Error('There was a problem publishing over the PubNub network.'), status);\n }\n\n });\n\n }\n\n}\n\nmodule.exports = Event;\n"},{"id":29,"identifier":"/Users/max/Desktop/CLIENT/chat-engine/src/components/user.js","name":"./src/components/user.js","index":88,"index2":85,"size":5484,"cacheable":true,"built":true,"optional":false,"prefetched":false,"chunks":[0],"assets":[],"issuer":"/Users/max/Desktop/CLIENT/chat-engine/src/bootstrap.js","issuerId":31,"issuerName":"./src/bootstrap.js","profile":{"factory":12,"building":35},"failed":false,"errors":0,"warnings":0,"reasons":[{"moduleId":31,"moduleIdentifier":"/Users/max/Desktop/CLIENT/chat-engine/src/bootstrap.js","module":"./src/bootstrap.js","moduleName":"./src/bootstrap.js","type":"cjs require","userRequest":"./components/user","loc":"8:13-41"},{"moduleId":88,"moduleIdentifier":"/Users/max/Desktop/CLIENT/chat-engine/src/components/me.js","module":"./src/components/me.js","moduleName":"./src/components/me.js","type":"cjs require","userRequest":"./user","loc":"1:13-30"}],"usedExports":true,"providedExports":null,"optimizationBailout":[],"depth":2,"source":"const Emitter = require('../modules/emitter');\n\n/**\n This is our User class which represents a connected client. User's are automatically created and managed by {@link Chat}s, but you can also instantiate them yourself.\n If a User has been created but has never been authenticated, you will recieve 403s when connecting to their feed or direct Chats.\n @class User\n @extends Emitter\n @extends RootEmitter\n @param uuid\n @param state\n */\nclass User extends Emitter {\n\n constructor(chatEngine, uuid, state = {}) {\n\n super();\n\n this.chatEngine = chatEngine;\n\n this.name = 'User';\n\n /**\n The User's unique identifier, usually a device uuid. This helps ChatEngine identify the user between events. This is public id exposed to the network.\n Check out [the wikipedia page on UUIDs](https://en.wikipedia.org/wiki/Universally_unique_identifier).\n\n @readonly\n @type String\n */\n this.uuid = uuid;\n\n /**\n * Gets the user state. See {@link Me#update} for how to assign state values.\n * @return {Object} Returns a generic JSON object containing state information.\n * @example\n *\n * // State\n * let state = user.state;\n */\n this.state = {};\n\n this._stateFetched = false;\n\n /**\n * Feed is a Chat that only streams things a User does, like\n * 'startTyping' or 'idle' events for example. Anybody can subscribe\n * to a User's feed, but only the User can publish to it. Users will\n * not be able to converse in this channel.\n *\n * @type Chat\n * @example\n * // me\n * me.feed.emit('update', 'I may be away from my computer right now');\n *\n * // another instance\n * them.feed.connect();\n * them.feed.on('update', (payload) => {})\n */\n\n // grants for these chats are done on auth. Even though they're marked private, they are locked down via the server\n this.feed = new this.chatEngine.Chat([chatEngine.global.channel, 'user', uuid, 'read.', 'feed'].join('#'), false, this.constructor.name === 'Me', {}, 'system');\n\n /**\n * Direct is a private channel that anybody can publish to but only\n * the user can subscribe to. Great for pushing notifications or\n * inviting to other chats. Users will not be able to communicate\n * with one another inside of this chat. Check out the\n * {@link Chat#invite} method for private chats utilizing\n * {@link User#direct}.\n *\n * @type Chat\n * @example\n * // me\n * me.direct.on('private-message', (payload) -> {\n * console.log(payload.sender.uuid, 'sent your a direct message');\n * });\n *\n * // another instance\n * them.direct.connect();\n * them.direct.emit('private-message', {secret: 42});\n */\n this.direct = new this.chatEngine.Chat([chatEngine.global.channel, 'user', uuid, 'write.', 'direct'].join('#'), false, this.constructor.name === 'Me', {}, 'system');\n\n // if the user does not exist at all and we get enough\n // information to build the user\n if (!chatEngine.users[uuid]) {\n chatEngine.users[uuid] = this;\n }\n\n // update this user's state in it's created context\n this.assign(state);\n\n return this;\n\n }\n\n /**\n * @private\n * @param {Object} state The new state for the user\n * @param {Chat} chat Chatroom to retrieve state from\n */\n update(state) {\n let oldState = this.state || {};\n this.state = Object.assign(oldState, state);\n }\n\n /**\n this is only called from network updates\n\n @private\n */\n assign(state) {\n this.update(state);\n }\n\n /**\n Get stored user state from remote server.\n @private\n */\n _getState(callback) {\n\n if (!this._stateFetched) {\n\n this.chatEngine.pubnub.getState({\n uuid: this.uuid,\n channels: [this.chatEngine.global.channel]\n }, (status, response) => {\n\n if (status.statusCode === 200) {\n\n let pnState = response.channels[this.chatEngine.global.channel];\n if (Object.keys(pnState).length) {\n\n this.assign(response.data);\n\n this._stateFetched = true;\n callback(this.state);\n\n } else {\n\n this.chatEngine.request('get', 'user_state', {\n user: this.uuid\n })\n .then((res) => {\n\n this.assign(res.data);\n\n this._stateFetched = true;\n callback(this.state);\n\n })\n .catch((err) => {\n // console.log('this is hte err', err);\n this.chatEngine.throwError(this, 'trigger', 'getState', err);\n });\n\n }\n\n } else {\n this.chatEngine.throwError(this, 'trigger', 'getState', new Error('There was a problem getting state from the PubNub network.'));\n }\n\n });\n\n } else {\n callback(this.state);\n }\n\n }\n\n}\n\nmodule.exports = User;\n"},{"id":30,"identifier":"/Users/max/Desktop/CLIENT/chat-engine/src/index.js","name":"./src/index.js","index":0,"index2":88,"size":1425,"cacheable":true,"built":true,"optional":false,"prefetched":false,"chunks":[0],"assets":[],"issuer":null,"issuerId":null,"issuerName":null,"profile":{"factory":17,"building":18},"failed":false,"errors":0,"warnings":0,"reasons":[],"usedExports":true,"providedExports":null,"optimizationBailout":[],"depth":0,"source":"// allows asynchronous execution flow.\nconst init = require('./bootstrap');\n\n/**\nGlobal object used to create an instance of {@link ChatEngine}.\n\n@alias ChatEngineCore\n@param pnConfig {Object} ChatEngine is based off PubNub. Supply your PubNub configuration parameters here. See the getting started tutorial and [the PubNub docs](https://www.pubnub.com/docs/java-se-java/api-reference-configuration).\n@param ceConfig {Object} A list of chat engine specific config options.\n@param [ceConfig.globalChannel=chat-engine] {String} The root channel. See {@link ChatEngine.global}\n@param [ceConfig.throwErrors=true] {Boolean} Throws errors in JS console.\n@param [ceConfig.endpoint] {String} The root URL used to manage permissions for private channels.\n@return {ChatEngine} Returns an instance of {@link ChatEngine}\n@example\nChatEngine = ChatEngineCore.create({\n publishKey: 'demo',\n subscribeKey: 'demo'\n});\n*/\n\nconst create = (pnConfig, ceConfig = {}) => {\n\n if (ceConfig.globalChannel) {\n ceConfig.globalChannel = ceConfig.globalChannel.toString();\n } else {\n ceConfig.globalChannel = 'chat-engine';\n }\n\n if (typeof ceConfig.throwErrors === 'undefined') {\n ceConfig.throwErrors = true;\n }\n\n // return an instance of ChatEngine\n return init(ceConfig, pnConfig);\n\n};\n\n// export the ChatEngine api\nmodule.exports = {\n plugin: {}, // leave a spot for plugins to exist\n create\n};\n"},{"id":31,"identifier":"/Users/max/Desktop/CLIENT/chat-engine/src/bootstrap.js","name":"./src/bootstrap.js","index":1,"index2":87,"size":16020,"cacheable":true,"built":true,"optional":false,"prefetched":false,"chunks":[0],"assets":[],"issuer":"/Users/max/Desktop/CLIENT/chat-engine/src/index.js","issuerId":30,"issuerName":"./src/index.js","profile":{"factory":3,"building":37},"failed":false,"errors":0,"warnings":0,"reasons":[{"moduleId":30,"moduleIdentifier":"/Users/max/Desktop/CLIENT/chat-engine/src/index.js","module":"./src/index.js","moduleName":"./src/index.js","type":"cjs require","userRequest":"./bootstrap","loc":"2:13-35"}],"usedExports":true,"providedExports":null,"optimizationBailout":[],"depth":1,"source":"const axios = require('axios');\nconst PubNub = require('pubnub');\nconst pack = require('../package.json');\n\nconst RootEmitter = require('./modules/root_emitter');\nconst Chat = require('./components/chat');\nconst Me = require('./components/me');\nconst User = require('./components/user');\nconst async = require('async');\n\n/**\n @class ChatEngine\n @extends RootEmitter\n @return {ChatEngine} Returns an instance of {@link ChatEngine}\n */\nmodule.exports = (ceConfig = {}, pnConfig = {}) => {\n\n // Create the root ChatEngine object\n let ChatEngine = new RootEmitter();\n\n ChatEngine.ceConfig = ceConfig;\n ChatEngine.pnConfig = pnConfig;\n\n ChatEngine.pnConfig.heartbeatInterval = ChatEngine.pnConfig.heartbeatInterval || 30;\n ChatEngine.pnConfig.presenceTimeout = ChatEngine.pnConfig.presenceTimeout || 60;\n\n ChatEngine.ceConfig.endpoint = ChatEngine.ceConfig.endpoint || 'https://pubsub.pubnub.com/v1/blocks/sub-key/' + ChatEngine.pnConfig.subscribeKey + '/chat-engine-server';\n ChatEngine.ceConfig.globalChannel = ChatEngine.ceConfig.globalChannel || 'chat-engine-global';\n\n /**\n * A map of all known {@link User}s in this instance of ChatEngine.\n * @type {Object}\n * @memberof ChatEngine\n */\n ChatEngine.users = {};\n\n /**\n * A map of all known {@link Chat}s in this instance of ChatEngine.\n * @memberof ChatEngine\n * @type {Object}\n */\n ChatEngine.chats = {};\n\n /**\n * A global {@link Chat} that all {@link User}s join when they connect to ChatEngine. Useful for announcements, alerts, and global events.\n * @member {Chat} global\n * @memberof ChatEngine\n */\n ChatEngine.global = false;\n\n /**\n * This instance of ChatEngine represented as a special {@link User} know as {@link Me}.\n * @member {Me} me\n * @memberof ChatEngine\n */\n ChatEngine.me = false;\n\n /**\n * An instance of PubNub, the networking infrastructure that powers the realtime communication between {@link User}s in {@link Chats}.\n * @member {Object} pubnub\n * @memberof ChatEngine\n */\n ChatEngine.pubnub = false;\n\n /**\n * Indicates if ChatEngine has fired the {@link ChatEngine#$\".\"ready} event.\n * @member {Object} ready\n * @memberof ChatEngine\n */\n ChatEngine.ready = false;\n\n /**\n * The package.json for ChatEngine. Used mainly for detecting package version.\n * @type {Object}\n */\n ChatEngine.package = pack;\n\n ChatEngine.throwError = (self, cb, key, ceError, payload = {}) => {\n\n if (ceConfig.throwErrors) {\n // throw ceError;\n console.error(payload);\n throw ceError;\n }\n\n payload.ceError = ceError.toString();\n\n self[cb](['$', 'error', key].join('.'), payload);\n\n };\n\n if (ceConfig.debug) {\n ChatEngine.onAny((event, payload) => {\n console.info('debug:', event, payload);\n });\n }\n\n ChatEngine.protoPlugins = {};\n\n /**\n * Bind a plugin to all future instances of a Class.\n * @method ChatEngine#proto\n * @param {String} className The string representation of a class to bind to\n * @param {Class} plugin The plugin function.\n */\n ChatEngine.proto = (className, plugin) => {\n ChatEngine.protoPlugins[className] = ChatEngine.protoPlugins[className] || [];\n ChatEngine.protoPlugins[className].push(plugin);\n };\n\n ChatEngine.request = (method, route, inputBody = {}, inputParams = {}) => {\n\n let body = {\n uuid: pnConfig.uuid,\n global: ceConfig.globalChannel,\n authData: ChatEngine.me.authData,\n authKey: pnConfig.authKey\n };\n\n let params = {\n route\n };\n\n body = Object.assign(body, inputBody);\n params = Object.assign(params, inputParams);\n\n if (method === 'get' || method === 'delete') {\n params = Object.assign(params, body);\n return axios[method](ceConfig.endpoint, { params });\n } else {\n return axios[method](ceConfig.endpoint, body, { params });\n }\n\n\n };\n\n ChatEngine.parseChannel = (channel) => {\n\n let info = channel.split('#');\n\n return {\n global: info[0],\n type: info[1],\n private: info[2] === 'private.'\n };\n\n };\n\n /**\n * Get the internal channel name of supplied string\n * @private\n * @param {[type]} original [description]\n * @param {Boolean} isPrivate [description]\n * @return {[type]} [description]\n */\n ChatEngine.augmentChannel = (original = new Date().getTime(), isPrivate = true) => {\n\n let channel = original.toString();\n\n // public.* has PubNub permissions for everyone to read and write\n // private.* is totally locked down and users must be granted access one by one\n let chanPrivString = 'public.';\n\n if (isPrivate) {\n chanPrivString = 'private.';\n }\n\n if (channel.indexOf(ChatEngine.ceConfig.globalChannel) === -1) {\n channel = [ChatEngine.ceConfig.globalChannel, 'chat', chanPrivString, channel].join('#');\n }\n\n return channel;\n\n };\n\n /**\n * Connect to realtime service and create instance of {@link Me}\n * @method ChatEngine#connect\n * @param {String} uuid A unique string for {@link Me}. It can be a device id, username, user id, email, etc.\n * @param {Object} state An object containing information about this client ({@link Me}). This JSON object is sent to all other clients on the network, so no passwords!\n * @param {String} [authKey] A authentication secret. Will be sent to authentication backend for validation. This is usually an access token or password. This is different from UUID as a user can have a single UUID but multiple auth keys.\n * @param {Object} [authData] Additional data to send to the authentication endpoint to help verify a valid session. ChatEngine SDK does not make use of this, but you might!\n * @fires $\".\"connected\n */\n ChatEngine.connect = (uuid, state = {}, authKey = false, authData) => {\n\n // this creates a user known as Me and\n // connects to the global chatroom\n\n pnConfig.uuid = uuid;\n\n pnConfig.authKey = authKey || pnConfig.uuid;\n\n let restoreSession = () => {\n\n let groups = ['custom', 'rooms', 'system'];\n\n groups.forEach((group) => {\n\n let channelGroup = [ceConfig.globalChannel, pnConfig.uuid, group].join('#');\n\n ChatEngine.pubnub.channelGroups.listChannels({\n channelGroup\n }, (status, response) => {\n\n if (status.error) {\n console.log('operation failed w/ error:', status);\n return;\n }\n\n response.channels.forEach((channel) => {\n\n ChatEngine.me.addChatToSession({\n channel,\n private: ChatEngine.parseChannel(channel).private,\n group\n });\n\n });\n\n });\n\n });\n\n };\n\n let complete = () => {\n\n ChatEngine.pubnub = new PubNub(pnConfig);\n\n // create a new chat to use as global chat\n // we don't do auth on this one because it's assumed to be done with the /auth request below\n ChatEngine.global = new ChatEngine.Chat(ceConfig.globalChannel, false, true, {}, 'system');\n\n // build the current user\n ChatEngine.me = new Me(ChatEngine, pnConfig.uuid, authData);\n ChatEngine.me.update(state);\n\n /**\n * Fired when a {@link Me} has been created within ChatEngine.\n * @event ChatEngine#$\".\"created\".\"me\n * @example\n * ChatEngine.on('$.created.me', (data, me) => {\n * console.log('Me was created', me);\n * });\n */\n ChatEngine.me.onConstructed();\n\n ChatEngine.global.on('$.connected', () => {\n\n /**\n * Fired when ChatEngine is connected to the internet and ready to go!\n * @event ChatEngine#$\".\"ready\n * @example\n * ChatEngine.on('$.ready', (data) => {\n * let me = data.me;\n * })\n */\n ChatEngine._emit('$.ready', {\n me: ChatEngine.me\n });\n\n ChatEngine.global.getUserUpdates();\n\n let chanGroups = [\n ceConfig.globalChannel + '#' + ChatEngine.me.uuid + '#rooms',\n ceConfig.globalChannel + '#' + ChatEngine.me.uuid + '#system',\n ceConfig.globalChannel + '#' + ChatEngine.me.uuid + '#custom'\n ];\n\n // listen to all PubNub events for this Chat\n ChatEngine.pubnub.addListener({\n presence: (payload) => {\n\n if (ChatEngine.chats[payload.channel]) {\n ChatEngine.chats[payload.channel].onPresence(payload);\n }\n\n }\n });\n\n ChatEngine.pubnub.subscribe({\n channelGroups: chanGroups,\n withPresence: true\n });\n\n ChatEngine.ready = true;\n\n restoreSession();\n\n });\n\n /**\n Fires when PubNub network connection changes.\n\n @private\n @param {Object} statusEvent The response status\n */\n ChatEngine.pubnub.addListener({\n status: (statusEvent) => {\n\n /**\n * SDK detected that network is online.\n * @event ChatEngine#$\".\"network\".\"up\".\"online\n */\n\n /**\n * SDK detected that network is down.\n * @event ChatEngine#$\".\"network\".\"down\".\"offline\n */\n\n /**\n * A subscribe event experienced an exception when running.\n * @event ChatEngine#$\".\"network\".\"down\".\"issue\n */\n\n /**\n * SDK was able to reconnect to pubnub.\n * @event ChatEngine#$\".\"network\".\"up\".\"reconnected\n */\n\n /**\n * SDK subscribed with a new mix of channels.\n * @event ChatEngine#$\".\"network\".\"up\".\"connected\n */\n\n /**\n * JSON parsing crashed.\n * @event ChatEngine#$\".\"network\".\"down\".\"malformed\n */\n\n /**\n * Server rejected the request.\n * @event ChatEngine#$\".\"network\".\"down\".\"badrequest\n */\n\n /**\n * If using decryption strategies and the decryption fails.\n * @event ChatEngine#$\".\"network\".\"down\".\"decryption\n */\n\n /**\n * Request timed out.\n * @event ChatEngine#$\".\"network\".\"down\".\"timeout\n */\n\n /**\n * PAM permission failure.\n * @event ChatEngine#$\".\"network\".\"down\".\"denied\n */\n\n // map the pubnub events into chat engine events\n let categories = {\n PNNetworkUpCategory: 'up.online',\n PNNetworkDownCategory: 'down.offline',\n PNNetworkIssuesCategory: 'down.issue',\n PNReconnectedCategory: 'up.reconnected',\n PNConnectedCategory: 'up.connected',\n PNAccessDeniedCategory: 'down.denied',\n PNMalformedResponseCategory: 'down.malformed',\n PNBadRequestCategory: 'down.badrequest',\n PNDecryptionErrorCategory: 'down.decryption',\n PNTimeoutCategory: 'down.timeout'\n };\n\n let eventName = ['$', 'network', categories[statusEvent.category] || 'other'].join('.');\n\n if (statusEvent.affectedChannels) {\n statusEvent.affectedChannels.forEach((channel) => {\n\n let chat = ChatEngine.chats[channel];\n\n if (chat) {\n // connected category tells us the chat is ready\n if (statusEvent.category === 'PNConnectedCategory') {\n chat.onConnectionReady();\n }\n\n // trigger the network events\n chat.trigger(eventName, statusEvent);\n\n } else {\n ChatEngine._emit(eventName, statusEvent);\n }\n });\n } else {\n ChatEngine._emit(eventName, statusEvent);\n }\n }\n });\n };\n\n async.parallel([\n (next) => {\n ChatEngine.request('post', 'bootstrap').then(() => {\n next(null);\n }).catch(next);\n },\n (next) => {\n ChatEngine.request('post', 'user_read').then(() => {\n next(null);\n }).catch(next);\n },\n (next) => {\n ChatEngine.request('post', 'user_write').then(() => {\n next(null);\n }).catch(next);\n },\n (next) => {\n ChatEngine.request('post', 'group').then(complete).catch(next);\n }\n ], (error) => {\n if (error) {\n ChatEngine.throwError(ChatEngine, '_emit', 'auth', new Error('There was a problem logging into the auth server (' + ceConfig.endpoint + ').'), { error });\n }\n });\n\n };\n\n /**\n * The {@link Chat} class.\n * @member {Chat} Chat\n * @memberof ChatEngine\n * @see {@link Chat}\n */\n ChatEngine.Chat = function (...args) {\n\n let internalChannel = ChatEngine.augmentChannel(args[0], args[1]);\n\n if (ChatEngine.chats[internalChannel]) {\n return ChatEngine.chats[internalChannel];\n } else {\n\n let newChat = new Chat(ChatEngine, ...args);\n\n /**\n * Fired when a {@link Chat} has been created within ChatEngine.\n * @event ChatEngine#$\".\"created\".\"chat\n * @example\n * ChatEngine.on('$.created.chat', (data, chat) => {\n * console.log('Chat was created', chat);\n * });\n */\n newChat.onConstructed();\n\n return newChat;\n\n }\n\n };\n\n /**\n * The {@link User} class.\n * @member {User} User\n * @memberof ChatEngine\n * @see {@link User}\n */\n ChatEngine.User = function (...args) {\n\n if (ChatEngine.me.uuid === args[0]) {\n return ChatEngine.me;\n } else if (ChatEngine.users[args[0]]) {\n return ChatEngine.users[args[0]];\n } else {\n\n let newUser = new User(ChatEngine, ...args);\n\n /**\n * Fired when a {@link User} has been created within ChatEngine.\n * @event ChatEngine#$\".\"created\".\"user\n * @example\n * ChatEngine.on('$.created.user', (data, user) => {\n * console.log('Chat was created', user);\n * });\n */\n newUser.onConstructed();\n\n return newUser;\n\n }\n\n };\n\n return ChatEngine;\n\n};\n"},{"id":52,"identifier":"/Users/max/Desktop/CLIENT/chat-engine/node_modules/json-loader/index.js!/Users/max/Desktop/CLIENT/chat-engine/package.json","name":"./package.json","index":30,"index2":28,"size":1304,"cacheable":true,"built":true,"optional":false,"prefetched":false,"chunks":[0],"assets":[],"issuer":"/Users/max/Desktop/CLIENT/chat-engine/src/bootstrap.js","issuerId":31,"issuerName":"./src/bootstrap.js","profile":{"factory":97,"building":3},"failed":false,"errors":0,"warnings":0,"reasons":[{"moduleId":31,"moduleIdentifier":"/Users/max/Desktop/CLIENT/chat-engine/src/bootstrap.js","module":"./src/bootstrap.js","moduleName":"./src/bootstrap.js","type":"cjs require","userRequest":"../package.json","loc":"3:13-39"}],"usedExports":true,"providedExports":null,"optimizationBailout":[],"depth":2,"source":"module.exports = {\"author\":\"PubNub\",\"name\":\"chat-engine\",\"version\":\"0.8.3\",\"description\":\"ChatEngine\",\"main\":\"src/index.js\",\"scripts\":{\"deploy\":\"gulp; npm publish;\",\"docs\":\"jsdoc src/index.js -c jsdoc.json\"},\"repository\":{\"type\":\"git\",\"url\":\"git+https://github.com/pubnub/chat-engine.git\"},\"keywords\":[\"pubnub\",\"chat\",\"sdk\",\"realtime\"],\"bugs\":{\"url\":\"https://github.com/pubnub/chat-engine/issues\"},\"homepage\":\"https://github.com/pubnub/chat-engine#readme\",\"devDependencies\":{\"body-parser\":\"^1.17.2\",\"chai\":\"^3.5.0\",\"chat-engine-typing-indicator\":\"0.0.x\",\"docdash\":\"^0.4.0\",\"es6-promise\":\"^4.1.1\",\"eslint\":\"^4.7.1\",\"eslint-config-airbnb\":\"^15.1.0\",\"eslint-plugin-import\":\"^2.7.0\",\"express\":\"^4.15.3\",\"gulp\":\"^3.9.1\",\"gulp-clean\":\"^0.3.2\",\"gulp-eslint\":\"^4.0.0\",\"gulp-istanbul\":\"^1.1.2\",\"gulp-jsdoc3\":\"^1.0.1\",\"gulp-mocha\":\"^3.0.1\",\"gulp-rename\":\"^1.2.2\",\"gulp-uglify\":\"^2.0.0\",\"gulp-uglify-es\":\"^0.1.3\",\"http-server\":\"^0.10.0\",\"isparta\":\"^4.0.0\",\"jsdoc\":\"^3.5.5\",\"mocha\":\"^3.1.2\",\"proxyquire\":\"^1.8.0\",\"pubnub-functions-mock\":\"^0.0.6\",\"request\":\"^2.82.0\",\"run-sequence\":\"^2.2.0\",\"sinon\":\"^4.0.0\",\"stats-webpack-plugin\":\"^0.6.1\",\"uglifyjs-webpack-plugin\":\"^1.0.1\",\"webpack\":\"^3.6.0\",\"webpack-stream\":\"^4.0.0\"},\"dependencies\":{\"async\":\"^2.1.2\",\"axios\":\"^0.16.2\",\"eventemitter2\":\"^2.2.1\",\"pubnub\":\"^4.17.0\"}}"},{"id":54,"identifier":"/Users/max/Desktop/CLIENT/chat-engine/src/components/chat.js","name":"./src/components/chat.js","index":33,"index2":84,"size":21104,"cacheable":true,"built":true,"optional":false,"prefetched":false,"chunks":[0],"assets":[],"issuer":"/Users/max/Desktop/CLIENT/chat-engine/src/bootstrap.js","issuerId":31,"issuerName":"./src/bootstrap.js","profile":{"factory":11,"building":69,"dependencies":14},"failed":false,"errors":0,"warnings":0,"reasons":[{"moduleId":31,"moduleIdentifier":"/Users/max/Desktop/CLIENT/chat-engine/src/bootstrap.js","module":"./src/bootstrap.js","moduleName":"./src/bootstrap.js","type":"cjs require","userRequest":"./components/chat","loc":"6:13-41"}],"usedExports":true,"providedExports":null,"optimizationBailout":[],"depth":2,"source":"const async = require('async');\nconst Emitter = require('../modules/emitter');\nconst Event = require('../components/event');\nconst Search = require('../components/search');\n\n/**\n This is the root {@link Chat} class that represents a chat room\n\n @param {String} [channel=new Date().getTime()] A unique identifier for this chat {@link Chat}. The channel is the unique name of a {@link Chat}, and is usually something like \"The Watercooler\", \"Support\", or \"Off Topic\". See [PubNub Channels](https://support.pubnub.com/support/solutions/articles/14000045182-what-is-a-channel-).\n @param {Boolean} [isPrivate=true] Attempt to authenticate ourselves before connecting to this {@link Chat}.\n @param {Boolean} [autoConnect=true] Connect to this chat as soon as its initiated. If set to ```false```, call the {@link Chat#connect} method to connect to this {@link Chat}.\n @param {String} [group='default'] Groups chat into a \"type\". This is the key which chats will be grouped into within {@link ChatEngine.session} object.\n @class Chat\n @extends Emitter\n @extends RootEmitter\n @fires Chat#$\".\"ready\n @fires Chat#$\".\"state\n @fires Chat#$\".\"online\".\"*\n @fires Chat#$\".\"offline\".\"*\n */\nclass Chat extends Emitter {\n\n constructor(chatEngine, channel = new Date().getTime(), isPrivate = true, autoConnect = true, meta = {}, group = 'custom') {\n\n super(chatEngine);\n\n this.chatEngine = chatEngine;\n\n this.name = 'Chat';\n\n this.meta = meta;\n\n this.group = group;\n\n /**\n * Excludes all users from reading or writing to the {@link chat} unless they have been explicitly invited via {@link Chat#invite};\n * @type Boolean\n * @readonly\n */\n this.isPrivate = isPrivate;\n\n /**\n * A string identifier for the Chat room. Any chat with an identical channel will be able to communicate with one another.\n * @type String\n * @readonly\n * @see [PubNub Channels](https://support.pubnub.com/support/solutions/articles/14000045182-what-is-a-channel-)\n */\n\n this.meta = {};\n\n /**\n * Excludes all users from reading or writing to the {@link chat} unless they have been explicitly invited via {@link Chat#invite};\n * @type Boolean\n * @readonly\n */\n this.isPrivate = isPrivate;\n\n this.channel = this.chatEngine.augmentChannel(channel, this.isPrivate);\n\n /**\n A list of users in this {@link Chat}. Automatically kept in sync as users join and leave the chat.\n Use [$.join](/Chat.html#event:$%2522.%2522join) and related events to get notified when this changes\n\n @type Object\n @readonly\n */\n this.users = {};\n\n /**\n * Boolean value that indicates of the Chat is connected to the network\n * @type {Boolean}\n */\n this.connected = false;\n\n this.chatEngine.chats[this.channel] = this;\n\n if (autoConnect) {\n this.connect();\n }\n\n return this;\n\n }\n\n /**\n Updates list of {@link User}s in this {@link Chat}\n based on who is online now.\n\n @private\n @param {Object} status The response status\n @param {Object} response The response payload object\n */\n onHereNow(status, response) {\n\n if (status.error) {\n\n /**\n * There was a problem fetching the presence of this chat\n * @event Chat#$\".\"error\".\"presence\n */\n this.chatEngine.throwError(this, 'trigger', 'presence', new Error('Getting presence of this Chat. Make sure PubNub presence is enabled for this key'), status);\n\n } else {\n\n // get the list of occupants in this channel\n let occupants = response.channels[this.channel].occupants;\n\n // format the userList for rltm.js standard\n occupants.forEach((occupant) => {\n this.userUpdate(occupant.uuid, occupant.state);\n });\n\n }\n\n }\n\n /**\n * Turns a {@link Chat} into a JSON representation.\n * @return {Object}\n */\n objectify() {\n\n return {\n channel: this.channel,\n group: this.group,\n private: this.isPrivate,\n meta: this.meta\n };\n\n }\n\n /**\n * Invite a user to this Chat. Authorizes the invited user in the Chat and sends them an invite via {@link User#direct}.\n * @param {User} user The {@link User} to invite to this chatroom.\n * @fires Me#event:$\".\"invite\n * @example\n * // one user running ChatEngine\n * let secretChat = new ChatEngine.Chat('secret-channel');\n * secretChat.invite(someoneElse);\n *\n * // someoneElse in another instance of ChatEngine\n * me.direct.on('$.invite', (payload) => {\n * let secretChat = new ChatEngine.Chat(payload.data.channel);\n * });\n */\n invite(user) {\n\n this.chatEngine.request('post', 'invite', {\n to: user.uuid,\n chat: this.objectify()\n })\n .then(() => {\n\n let send = () => {\n\n /**\n * Notifies {@link Me} that they've been invited to a new private {@link Chat}.\n * Fired by the {@link Chat#invite} method.\n * @event Me#$\".\"invite\n * @tutorial private\n * @example\n * me.direct.on('$.invite', (payload) => {\n * let privChat = new ChatEngine.Chat(payload.data.channel));\n * });\n */\n user.direct.emit('$.invite', {\n channel: this.channel\n });\n\n };\n\n if (!user.direct.connected) {\n user.direct.connect();\n user.direct.on('$.connected', send);\n } else {\n send();\n }\n\n })\n .catch((error) => {\n this.chatEngine.throwError(this, 'trigger', 'auth', new Error('Something went wrong while making a request to authentication server.'), { error });\n });\n\n }\n\n /**\n Keep track of {@link User}s in the room by subscribing to PubNub presence events.\n\n @private\n @param {Object} data The PubNub presence response for this event\n */\n onPresence(presenceEvent) {\n\n // make sure channel matches this channel\n\n // someone joins channel\n if (presenceEvent.action === 'join') {\n\n let user = this.createUser(presenceEvent.uuid, presenceEvent.state);\n\n /**\n * Fired when a {@link User} has joined the room.\n *\n * @event Chat#$\".\"online\".\"join\n * @param {Object} data The payload returned by the event\n * @param {User} data.user The {@link User} that came online\n * @example\n * chat.on('$.join', (data) => {\n * console.log('User has joined the room!', data.user);\n * });\n */\n\n // It's possible for PubNub to send us both a join and have the user appear in here_now\n // Avoid firing duplicate $.online events.\n if (!this.users[user.uuid]) {\n this.trigger('$.online.join', { user });\n }\n\n }\n\n // someone leaves channel\n if (presenceEvent.action === 'leave') {\n this.userLeave(presenceEvent.uuid);\n }\n\n // someone timesout\n if (presenceEvent.action === 'timeout') {\n this.userDisconnect(presenceEvent.uuid);\n }\n\n // someone's state is updated\n if (presenceEvent.action === 'state-change') {\n this.userUpdate(presenceEvent.uuid, presenceEvent.state);\n }\n\n\n }\n\n update(data) {\n\n let oldMeta = this.meta || {};\n this.meta = Object.assign(oldMeta, data);\n\n this.chatEngine.request('post', 'chat', {\n chat: this.objectify()\n }).then(() => {\n }).catch((error) => {\n this.chatEngine.throwError(this, 'trigger', 'auth', new Error('Something went wrong while making a request to authentication server.'), { error });\n });\n\n }\n\n /**\n * Send events to other clients in this {@link User}.\n * Events are trigger over the network and all events are made\n * on behalf of {@link Me}\n *\n * @param {String} event The event name\n * @param {Object} data The event payload object\n * @example\n * chat.emit('custom-event', {value: true});\n * chat.on('custom-event', (payload) => {\n * console.log(payload.sender.uuid, 'emitted the value', payload.data.value);\n * });\n */\n emit(event, data) {\n if (event === 'message' && typeof data !== 'object') {\n throw new Error('the payload has to be an object');\n }\n\n // create a standardized payload object\n let payload = {\n data, // the data supplied from params\n sender: this.chatEngine.me.uuid, // my own uuid\n chat: this, // an instance of this chat\n event,\n chatengineSDK: this.chatEngine.package.version\n };\n\n // run the plugin queue to modify the event\n this.runPluginQueue('emit', event, (next) => {\n next(null, payload);\n }, (err, pluginResponse) => {\n\n // remove chat otherwise it would be serialized\n // instead, it's rebuilt on the other end.\n // see this.trigger\n delete pluginResponse.chat;\n\n // publish the event and data over the configured channel\n\n // ensure the event exists within the global space\n this.events[event] = this.events[event] || new Event(this.chatEngine, this, event);\n\n this.events[event].publish(pluginResponse);\n\n });\n\n }\n\n /**\n Add a user to the {@link Chat}, creating it if it doesn't already exist.\n\n @private\n @param {String} uuid The user uuid\n @param {Object} state The user initial state\n @param {Boolean} trigger Force a trigger that this user is online\n */\n createUser(uuid, state) {\n\n // Ensure that this user exists in the global list\n // so we can reference it from here out\n this.chatEngine.users[uuid] = this.chatEngine.users[uuid] || new this.chatEngine.User(uuid);\n this.chatEngine.users[uuid].assign(state);\n\n // trigger the join event over this chatroom\n if (!this.users[uuid]) {\n\n /**\n * Broadcast that a {@link User} has come online. This is when\n * the framework firsts learn of a user. This can be triggered\n * by, ```$.join```, or other network events that\n * notify the framework of a new user.\n *\n * @event Chat#$\".\"online\".\"here\n * @param {Object} data The payload returned by the event\n * @param {User} data.user The {@link User} that came online\n * @example\n * chat.on('$.online.here', (data) => {\n * console.log('User has come online:', data.user);\n * });\n */\n\n this.trigger('$.online.here', {\n user: this.chatEngine.users[uuid]\n });\n\n }\n\n // store this user in the chatroom\n this.users[uuid] = this.chatEngine.users[uuid];\n\n // return the instance of this user\n return this.chatEngine.users[uuid];\n\n }\n\n /**\n * Update a user's state.\n * @private\n * @param {String} uuid The {@link User} uuid\n * @param {Object} state State to update for the user\n */\n userUpdate(uuid, state) {\n\n // ensure the user exists within the global space\n this.chatEngine.users[uuid] = this.chatEngine.users[uuid] || new this.chatEngine.User(uuid);\n\n // if we don't know about this user\n if (!this.users[uuid]) {\n // do the whole join thing\n this.createUser(uuid, state);\n }\n\n // update this user's state in this chatroom\n this.users[uuid].assign(state);\n\n /**\n * Broadcast that a {@link User} has changed state.\n * @event ChatEngine#$\".\"state\n * @param {Object} data The payload returned by the event\n * @param {User} data.user The {@link User} that changed state\n * @param {Object} data.state The new user state\n * @example\n * ChatEngine.on('$.state', (data) => {\n * console.log('User has changed state:', data.user, 'new state:', data.state);\n * });\n */\n this.chatEngine._emit('$.state', {\n user: this.users[uuid],\n state: this.users[uuid].state\n });\n\n }\n\n /**\n * Leave from the {@link Chat} on behalf of {@link Me}. Disconnects from the {@link Chat} and will stop\n * receiving events.\n * @fires Chat#event:$\".\"offline\".\"leave\n * @example\n * chat.leave();\n */\n leave() {\n\n // unsubscribe from the channel locally\n this.chatEngine.pubnub.unsubscribe({\n channels: [this.channel]\n });\n\n this.chatEngine.request('post', 'leave', { chat: this.objectify() })\n .then(() => {\n\n this.connected = false;\n\n this.trigger('$.disconnected');\n\n this.chatEngine.me.sync.emit('$.session.chat.leave', { subject: this.objectify() });\n\n })\n .catch((error) => {\n this.chatEngine.throwError(this, 'trigger', 'auth', new Error('Something went wrong while making a request to chat server.'), { error });\n });\n\n }\n\n /**\n Perform updates when a user has left the {@link Chat}.\n\n @private\n */\n userLeave(uuid) {\n\n // make sure this event is real, user may have already left\n if (this.users[uuid]) {\n\n // if a user leaves, trigger the event\n\n /**\n * Fired when a {@link User} intentionally leaves a {@link Chat}.\n *\n * @event Chat#$\".\"offline\".\"leave\n * @param {Object} data The data payload from the event\n * @param {User} user The {@link User} that has left the room\n * @example\n * chat.on('$.offline.leave', (data) => {\n * console.log('User left the room manually:', data.user);\n * });\n */\n this.trigger('$.offline.leave', {\n user: this.users[uuid]\n });\n\n // remove the user from the local list of users\n delete this.users[uuid];\n\n // we don't remove the user from the global list,\n // because they may be online in other channels\n\n } else {\n\n // that user isn't in the user list\n // we never knew about this user or they already left\n\n // console.log('user already left');\n }\n }\n\n /**\n Fired when a user disconnects from the {@link Chat}\n\n @private\n @param {String} uuid The uuid of the {@link Chat} that left\n */\n userDisconnect(uuid) {\n\n // make sure this event is real, user may have already left\n if (this.users[uuid]) {\n\n /**\n * Fired specifically when a {@link User} looses network connection\n * to the {@link Chat} involuntarily.\n *\n * @event Chat#$\".\"offline\".\"disconnect\n * @param {Object} data The {@link User} that disconnected\n * @param {Object} data.user The {@link User} that disconnected\n * @example\n * chat.on('$.offline.disconnect', (data) => {\n * console.log('User disconnected from the network:', data.user);\n * });\n */\n\n this.trigger('$.offline.disconnect', { user: this.users[uuid] });\n }\n\n }\n\n /**\n Set the state for {@link Me} within this {@link User}.\n Broadcasts the ```$.state``` event on other clients\n\n @private\n @param {Object} state The new state {@link Me} will have within this {@link User}\n */\n setState(state) {\n this.chatEngine.pubnub.setState({ state, channels: [this.chatEngine.global.channel] }, () => {\n // handle status, response\n });\n }\n\n /**\n Search through previously emitted events. Parameters act as AND operators. Returns an instance of the emitter based {@link History}. Will\n which will emit all old events unless ```config.event``` is supplied.\n @param {Object} [config] Our configuration for the PubNub history request. See the [PubNub History](https://www.pubnub.com/docs/web-javascript/storage-and-history) docs for more information on these parameters.\n @param {Event} [config.event] The {@link Event} to search for.\n @param {User} [config.sender] The {@link User} who sent the message.\n @param {Number} [config.limit=20] The maximum number of results to return that match search criteria. Search will continue operating until it returns this number of results or it reached the end of history.\n @param {Number} [config.start=0] The timetoken to begin searching between.\n @param {Number} [config.end=0] The timetoken to end searching between.\n @param {Boolean} [config.reverse=false] Search oldest messages first.\n @return {Search}\n @example\n chat.search({\n event: 'my-custom-event',\n sender: ChatEngine.me,\n limit: 20\n }).on('my-custom-event', (event) => {\n console.log('this is an old event!', event);\n }).on('$.search.finish', () => {\n console.log('we have all our results!')\n });\n */\n search(config) {\n return new Search(this.chatEngine, this, config);\n }\n\n onConnectionReady() {\n\n /**\n * Broadcast that the {@link Chat} is connected to the network.\n * @event Chat#$\".\"connected\n * @example\n * chat.on('$.connected', () => {\n * console.log('chat is ready to go!');\n * });\n */\n this.trigger('$.connected');\n\n this.chatEngine.me.sync.emit('$.session.chat.join', { subject: this.objectify() });\n\n this.connected = true;\n\n // add self to list of users\n this.users[this.chatEngine.me.uuid] = this.chatEngine.me;\n\n // trigger my own online event\n this.trigger('$.online.join', {\n user: this.chatEngine.me\n });\n\n // global channel updates are triggered manually, only get presence on custom chats\n if (this.channel !== this.chatEngine.global.channel && this.group === 'custom') {\n\n this.getUserUpdates();\n\n // we may miss updates, so call this again 5 seconds later\n setTimeout(() => {\n this.getUserUpdates();\n }, 5000);\n\n }\n\n }\n\n getUserUpdates() {\n\n // get a list of users online now\n // ask PubNub for information about connected users in this channel\n this.chatEngine.pubnub.hereNow({\n channels: [this.channel],\n includeUUIDs: true,\n includeState: true\n }, this.onHereNow.bind(this));\n\n }\n\n /**\n * Connect to PubNub servers to initialize the chat.\n * @example\n * // create a new chatroom, but don't connect to it automatically\n * let chat = new Chat('some-chat', false)\n *\n * // connect to the chat when we feel like it\n * chat.connect();\n */\n connect() {\n\n async.waterfall([\n (next) => {\n if (!this.chatEngine.pubnub) {\n next('You must call ChatEngine.connect() and wait for the $.ready event before creating new Chats.');\n } else {\n next();\n }\n },\n (next) => {\n\n this.chatEngine.request('post', 'grant', { chat: this.objectify() })\n .then(() => {\n next();\n })\n .catch(next);\n\n },\n (next) => {\n\n this.chatEngine.request('post', 'join', { chat: this.objectify() })\n .then(() => {\n next();\n })\n .catch(next);\n\n },\n (next) => {\n\n this.chatEngine.request('get', 'chat', {}, { channel: this.channel })\n .then((response) => {\n\n if (response.data.found) {\n this.meta = response.data.chat.meta;\n } else {\n this.update(this.meta);\n }\n\n this.onConnectionReady();\n\n })\n .catch(next);\n\n }\n ], (error) => {\n this.chatEngine.throwError(this, 'trigger', 'auth', new Error('Something went wrong while making a request to authentication server.'), { error });\n });\n\n }\n\n}\n\nmodule.exports = Chat;\n"},{"id":60,"identifier":"/Users/max/Desktop/CLIENT/chat-engine/src/components/search.js","name":"./src/components/search.js","index":52,"index2":83,"size":6596,"cacheable":true,"built":true,"optional":false,"prefetched":false,"chunks":[0],"assets":[],"issuer":"/Users/max/Desktop/CLIENT/chat-engine/src/components/chat.js","issuerId":54,"issuerName":"./src/components/chat.js","profile":{"factory":15,"building":96,"dependencies":0},"failed":false,"errors":0,"warnings":0,"reasons":[{"moduleId":54,"moduleIdentifier":"/Users/max/Desktop/CLIENT/chat-engine/src/components/chat.js","module":"./src/components/chat.js","moduleName":"./src/components/chat.js","type":"cjs require","userRequest":"../components/search","loc":"4:15-46"}],"usedExports":true,"providedExports":null,"optimizationBailout":[],"depth":3,"source":"const Emitter = require('../modules/emitter');\nconst eachSeries = require('async/eachSeries');\n/**\nReturned by {@link Chat#search}. This is our Search class which allows one to search the backlog of messages.\n\n\n Powered by [PubNub History](https://www.pubnub.com/docs/web-javascript/storage-and-history).\n\n @class Search\n @extends Emitter\n @extends RootEmitter\n @param chatEngine\n @param chat\n @param config\n */\nclass Search extends Emitter {\n\n constructor(chatEngine, chat, config = {}) {\n\n super();\n\n this.chatEngine = chatEngine;\n\n /**\n Handy property to identify what this class is.\n @type String\n */\n this.name = 'Search';\n\n /**\n The {@link Chat} used for searching.\n @type Chat\n */\n this.chat = chat;\n\n /**\n An object containing configuration parameters supplied by {@link Chat#search}. See {@link Chat#search} for possible parameters.\n @type {Object}\n */\n this.config = config;\n this.config.event = config.event;\n this.config.limit = config.limit || 20;\n this.config.channel = this.chat.channel;\n this.config.includeTimetoken = true;\n this.config.stringifiedTimeToken = true;\n this.config.count = this.config.count || 100;\n\n this.config.pages = this.config.pages || 10;\n\n this.needleCount = 0;\n\n this.firstTT = 0;\n this.lastTT = 0;\n\n this.firstPage = true;\n\n /**\n * @private\n */\n this.sortHistory = (messages, desc) => {\n\n messages.sort((a, b) => {\n let e1 = desc ? b : a;\n let e2 = desc ? a : b;\n return parseInt(e1.timetoken, 10) - parseInt(e2.timetoken, 10);\n });\n\n return messages;\n\n };\n\n /**\n * Call PubNub history in a loop.\n * Unapologetically stolen from https://www.pubnub.com/docs/web-javascript/storage-and-history\n * @private\n */\n this.page = (pageDone) => {\n\n /**\n * Requesting another page from PubNub History.\n * @event Search#$\".\"page\".\"request\n */\n this._emit('$.search.page.request');\n\n // only set start if this is the first call and the user hasn't set it themselves\n this.config.start = this.config.reverse ? this.lastTT : this.firstTT;\n\n this.firstPage = false;\n\n this.chatEngine.pubnub.history(this.config, (status, response) => {\n\n /**\n * PubNub History returned a response.\n * @event Search#$\".\"page\".\"response\n */\n this._emit('$.search.page.response');\n\n if (status.error) {\n\n /**\n * There was a problem fetching the history of this chat\n * @event Chat#$\".\"error\".\"history\n */\n this.chatEngine.throwError(this, 'trigger', 'search', new Error('There was a problem searching history. Make sure your request parameters are valid and history is enabled for this PubNub key.'), status);\n\n } else {\n\n // timetoken of the first message in response\n this.firstTT = response.startTimeToken;\n // timetoken of the last message in response\n this.lastTT = response.endTimeToken;\n\n response.messages = this.sortHistory(response.messages);\n\n pageDone(response);\n\n }\n\n });\n };\n\n let eventFilter = (event) => {\n return {\n middleware: {\n on: {\n '*': (payload, next) => {\n let matches = payload && payload.event && payload.event === event;\n next(!matches, payload);\n }\n }\n }\n };\n };\n\n let senderFilter = (user) => {\n return {\n middleware: {\n on: {\n '*': (payload, next) => {\n let matches = payload && payload.sender && payload.sender.uuid === user.uuid;\n next(!matches, payload);\n }\n }\n }\n };\n };\n\n this.needleCount = 0;\n\n /**\n * @private\n */\n this.triggerHistory = (message, cb) => {\n\n if (this.needleCount < this.config.limit) {\n\n this.trigger(message.entry.event, message.entry, (reject) => {\n\n if (!reject) {\n this.needleCount += 1;\n }\n cb();\n\n });\n\n } else {\n cb();\n }\n\n };\n\n this.maxPage = 10;\n this.numPage = 0;\n\n this.next = () => {\n\n this.maxPage = this.maxPage + this.config.pages;\n\n this.find();\n\n };\n\n /**\n * @private\n */\n this.find = () => {\n\n this.page((response) => {\n\n if (!this.config.reverse) {\n response.messages.reverse();\n }\n\n eachSeries(response.messages, this.triggerHistory, () => {\n\n if (this.numPage === this.maxPage) {\n this._emit('$.search.pause');\n } else if (\n response.messages &&\n response.messages.length === this.config.count &&\n this.needleCount < this.config.limit) {\n this.numPage += 1;\n this.find();\n } else {\n\n /**\n * Search has returned all results or reached the end of history.\n * @event Search#$\".\"search\".\"finish\n */\n this._emit('$.search.finish');\n }\n\n });\n\n });\n\n return this;\n\n };\n\n if (this.config.event) {\n this.plugin(eventFilter(this.config.event));\n }\n\n if (this.config.sender) {\n this.plugin(senderFilter(this.config.sender));\n }\n\n /**\n * Search has started.\n * @event Search#$\".\"search\".\"start\n */\n this._emit('$.search.start');\n this.find();\n\n }\n\n}\n\nmodule.exports = Search;\n"},{"id":88,"identifier":"/Users/max/Desktop/CLIENT/chat-engine/src/components/me.js","name":"./src/components/me.js","index":87,"index2":86,"size":4890,"cacheable":true,"built":true,"optional":false,"prefetched":false,"chunks":[0],"assets":[],"issuer":"/Users/max/Desktop/CLIENT/chat-engine/src/bootstrap.js","issuerId":31,"issuerName":"./src/bootstrap.js","profile":{"factory":12,"building":15,"dependencies":2},"failed":false,"errors":0,"warnings":0,"reasons":[{"moduleId":31,"moduleIdentifier":"/Users/max/Desktop/CLIENT/chat-engine/src/bootstrap.js","module":"./src/bootstrap.js","moduleName":"./src/bootstrap.js","type":"cjs require","userRequest":"./components/me","loc":"7:11-37"}],"usedExports":true,"providedExports":null,"optimizationBailout":[],"depth":2,"source":"const User = require('./user');\n\n/**\n Represents the client connection as a special {@link User} with write permissions.\n Has the ability to update it's state on the network. An instance of\n {@link Me} is returned by the ```ChatEngine.connect()```\n method.\n\n @class Me\n @extends User\n @extends Emitter\n @extends RootEmitter\n @param {String} uuid The uuid of this user\n */\nclass Me extends User {\n\n constructor(chatEngine, uuid, authData) {\n\n // call the User constructor\n super(chatEngine, uuid);\n\n this.name = 'Me';\n\n this.authData = authData;\n this.chatEngine = chatEngine;\n\n /**\n * Stores a map of {@link Chat} objects that this {@link Me} has joined across all clients.\n * @type {Object}\n */\n this.session = {};\n\n this.sync = new this.chatEngine.Chat([chatEngine.global.channel, 'user', uuid, 'me.', 'sync'].join('#'), false, true, {}, 'system');\n\n this.sync.on('$.session.chat.join', (payload) => {\n this.addChatToSession(payload.data.subject);\n });\n\n this.sync.on('$.session.chat.leave', (payload) => {\n this.removeChatFromSession(payload.data.subject);\n });\n\n return this;\n\n }\n\n // assign updates from network\n assign(state) {\n // we call \"update\" because calling \"super.assign\"\n // will direct back to \"this.update\" which creates\n // a loop of network updates\n super.update(state);\n }\n\n /**\n * Update {@link Me}'s state in a {@link Chat}. All other {@link User}s\n * will be notified of this change via ```$.state```.\n * Retrieve state at any time with {@link User#state}.\n * @param {Object} state The new state for {@link Me}\n * @param {Chat} chat An instance of the {@link Chat} where state will be updated.\n * Defaults to ```ChatEngine.global```.\n * @fires Chat#event:$\".\"state\n * @example\n * // update state\n * me.update({value: true});\n */\n update(state) {\n\n // run the root update function\n super.update(state);\n\n // publish the update over the global channel\n this.chatEngine.global.setState(state);\n\n }\n\n /**\n Stores {@link Chat} within ```ChatEngine.session``` keyed based on the ```chat.group``` property.\n @param {Object} chat JSON object representing {@link Chat}. Originally supplied via {@link Chat#objectify}.\n @private\n */\n addChatToSession(chat) {\n\n // create the chat group if it doesn't exist\n this.session[chat.group] = this.session[chat.group] || {};\n\n // check the chat exists within the global list but is not grouped\n let existingChat = this.chatEngine.chats[chat.channel];\n\n // if it exists\n if (existingChat) {\n // assign it to the group\n this.session[chat.group][chat.channel] = existingChat;\n } else {\n\n // otherwise, try to recreate it with the server information\n this.session[chat.group][chat.channel] = new this.chatEngine.Chat(chat.channel, chat.private, false, chat.meta, chat.group);\n\n /**\n Fired when another identical instance of {@link ChatEngine} and {@link Me} joins a {@link Chat} that this instance of {@link ChatEngine} is unaware of.\n Used to synchronize ChatEngine sessions between desktop and mobile, duplicate windows, etc.\n ChatEngine stores sessions on the server side identified by {@link User#uuid}.\n @event Me#$\".\"session\".\"chat\".\"join\n @example\n *\n * // Logged in as \"Ian\" in first window\n * ChatEngine.me.on('$.session.chat.join', (data) => {\n * console.log('I joined a new chat in a second window!', data.chat);\n * });\n *\n * // Logged in as \"Ian\" in second window\n * new ChatEngine.Chat('another-chat');\n */\n // this.trigger('$.session.chat.join', {\n // chat: this.session[chat.group][chat.channel]\n // });\n //\n this.trigger('$.session.chat.join', { chat: this.session[chat.group][chat.channel] });\n\n }\n\n }\n\n /**\n Removes {@link Chat} within this.session\n @private\n */\n removeChatFromSession(chat) {\n\n if (this.session[chat.group] && this.session[chat.group][chat.channel]) {\n\n chat = this.session[chat.group][chat.channel] || chat;\n\n /**\n * Fired when another identical instance of {@link ChatEngine} with an identical {@link Me} leaves a {@link Chat} via {@link Chat#leave}.\n * @event Me#$\".\"session\".\"chat\".\"leave\n */\n\n delete this.chatEngine.chats[chat.channel];\n delete this.session[chat.group][chat.channel];\n\n this.trigger('$.session.chat.leave', { chat });\n\n }\n\n }\n\n}\n\nmodule.exports = Me;\n"}],"filteredModules":77,"origins":[{"moduleId":30,"module":"/Users/max/Desktop/CLIENT/chat-engine/src/index.js","moduleIdentifier":"/Users/max/Desktop/CLIENT/chat-engine/src/index.js","moduleName":"./src/index.js","loc":"","name":"main","reasons":[]}]}],"modules":[{"id":3,"identifier":"/Users/max/Desktop/CLIENT/chat-engine/node_modules/webpack/buildin/global.js","name":"(webpack)/buildin/global.js","index":37,"index2":31,"size":509,"cacheable":true,"built":true,"optional":false,"prefetched":false,"chunks":[0],"assets":[],"issuer":"/Users/max/Desktop/CLIENT/chat-engine/node_modules/async/dist/async.js","issuerId":15,"issuerName":"./node_modules/async/dist/async.js","profile":{"factory":218,"building":38},"failed":false,"errors":0,"warnings":0,"reasons":[{"moduleId":15,"moduleIdentifier":"/Users/max/Desktop/CLIENT/chat-engine/node_modules/async/dist/async.js","module":"./node_modules/async/dist/async.js","moduleName":"./node_modules/async/dist/async.js","type":"cjs require","userRequest":"global","loc":"1:0-44"},{"moduleId":27,"moduleIdentifier":"/Users/max/Desktop/CLIENT/chat-engine/node_modules/lodash/_freeGlobal.js","module":"./node_modules/lodash/_freeGlobal.js","moduleName":"./node_modules/lodash/_freeGlobal.js","type":"cjs require","userRequest":"global","loc":"1:0-41"},{"moduleId":55,"moduleIdentifier":"/Users/max/Desktop/CLIENT/chat-engine/node_modules/setimmediate/setImmediate.js","module":"./node_modules/setimmediate/setImmediate.js","moduleName":"./node_modules/setimmediate/setImmediate.js","type":"cjs require","userRequest":"global","loc":"1:0-41"}],"usedExports":true,"providedExports":null,"optimizationBailout":[],"depth":3,"source":"var g;\r\n\r\n// This works in non-strict mode\r\ng = (function() {\r\n\treturn this;\r\n})();\r\n\r\ntry {\r\n\t// This works if eval is allowed (see CSP)\r\n\tg = g || Function(\"return this\")() || (1,eval)(\"this\");\r\n} catch(e) {\r\n\t// This works if the window reference is available\r\n\tif(typeof window === \"object\")\r\n\t\tg = window;\r\n}\r\n\r\n// g can still be undefined, but nothing to do about it...\r\n// We return undefined, instead of nothing here, so it's\r\n// easier to handle this case. if(!global) { ...}\r\n\r\nmodule.exports = g;\r\n"},{"id":4,"identifier":"/Users/max/Desktop/CLIENT/chat-engine/node_modules/webpack/buildin/module.js","name":"(webpack)/buildin/module.js","index":38,"index2":34,"size":517,"cacheable":true,"built":true,"optional":false,"prefetched":false,"chunks":[0],"assets":[],"issuer":"/Users/max/Desktop/CLIENT/chat-engine/node_modules/async/dist/async.js","issuerId":15,"issuerName":"./node_modules/async/dist/async.js","profile":{"factory":218,"building":39},"failed":false,"errors":0,"warnings":0,"reasons":[{"moduleId":15,"moduleIdentifier":"/Users/max/Desktop/CLIENT/chat-engine/node_modules/async/dist/async.js","module":"./node_modules/async/dist/async.js","moduleName":"./node_modules/async/dist/async.js","type":"cjs require","userRequest":"module","loc":"1:0-44"},{"moduleId":74,"moduleIdentifier":"/Users/max/Desktop/CLIENT/chat-engine/node_modules/lodash/isBuffer.js","module":"./node_modules/lodash/isBuffer.js","moduleName":"./node_modules/lodash/isBuffer.js","type":"cjs require","userRequest":"module","loc":"1:0-41"},{"moduleId":80,"moduleIdentifier":"/Users/max/Desktop/CLIENT/chat-engine/node_modules/lodash/_nodeUtil.js","module":"./node_modules/lodash/_nodeUtil.js","moduleName":"./node_modules/lodash/_nodeUtil.js","type":"cjs require","userRequest":"module","loc":"1:0-41"}],"usedExports":true,"providedExports":null,"optimizationBailout":[],"depth":3,"source":"module.exports = function(module) {\r\n\tif(!module.webpackPolyfill) {\r\n\t\tmodule.deprecate = function() {};\r\n\t\tmodule.paths = [];\r\n\t\t// module.parent = undefined by default\r\n\t\tif(!module.children) module.children = [];\r\n\t\tObject.defineProperty(module, \"loaded\", {\r\n\t\t\tenumerable: true,\r\n\t\t\tget: function() {\r\n\t\t\t\treturn module.l;\r\n\t\t\t}\r\n\t\t});\r\n\t\tObject.defineProperty(module, \"id\", {\r\n\t\t\tenumerable: true,\r\n\t\t\tget: function() {\r\n\t\t\t\treturn module.i;\r\n\t\t\t}\r\n\t\t});\r\n\t\tmodule.webpackPolyfill = 1;\r\n\t}\r\n\treturn module;\r\n};\r\n"},{"id":5,"identifier":"/Users/max/Desktop/CLIENT/chat-engine/src/modules/emitter.js","name":"./src/modules/emitter.js","index":39,"index2":48,"size":7500,"cacheable":true,"built":true,"optional":false,"prefetched":false,"chunks":[0],"assets":[],"issuer":"/Users/max/Desktop/CLIENT/chat-engine/src/components/user.js","issuerId":29,"issuerName":"./src/components/user.js","profile":{"factory":47,"building":88,"dependencies":2},"failed":false,"errors":0,"warnings":0,"reasons":[{"moduleId":29,"moduleIdentifier":"/Users/max/Desktop/CLIENT/chat-engine/src/components/user.js","module":"./src/components/user.js","moduleName":"./src/components/user.js","type":"cjs require","userRequest":"../modules/emitter","loc":"1:16-45"},{"moduleId":54,"moduleIdentifier":"/Users/max/Desktop/CLIENT/chat-engine/src/components/chat.js","module":"./src/components/chat.js","moduleName":"./src/components/chat.js","type":"cjs require","userRequest":"../modules/emitter","loc":"2:16-45"},{"moduleId":60,"moduleIdentifier":"/Users/max/Desktop/CLIENT/chat-engine/src/components/search.js","module":"./src/components/search.js","moduleName":"./src/components/search.js","type":"cjs require","userRequest":"../modules/emitter","loc":"1:16-45"}],"usedExports":true,"providedExports":null,"optimizationBailout":[],"depth":3,"source":"const waterfall = require('async/waterfall');\nconst RootEmitter = require('./root_emitter');\nconst Event = require('../components/event');\n\n/**\n An ChatEngine generic emitter that supports plugins and forwards\n events to the root emitter.\n @class Emitter\n @extends RootEmitter\n */\nclass Emitter extends RootEmitter {\n\n constructor(chatEngine) {\n\n super();\n\n this.chatEngine = chatEngine;\n\n this.name = 'Emitter';\n\n /**\n Stores a list of plugins bound to this object\n @private\n */\n this.plugins = [];\n\n /**\n Stores in memory keys and values\n @private\n */\n this._dataset = {};\n\n /**\n Emit events locally.\n\n @private\n @param {String} event The event payload object\n */\n this._emit = (event, data = {}) => {\n\n // all events are forwarded to ChatEngine object\n // so you can globally bind to events with ChatEngine.on()\n this.chatEngine._emit(event, data, this);\n\n // emit the event from the object that created it\n this.emitter.emit(event, data);\n\n return this;\n\n };\n\n /**\n * Listen for a specific event and fire a callback when it's emitted. Supports wildcard matching.\n * @method\n * @param {String} event The event name\n * @param {Function} cb The function to run when the event is emitted\n * @example\n *\n * // Get notified whenever someone joins the room\n * object.on('event', (payload) => {\n * console.log('event was fired').\n * })\n *\n * // Get notified of event.a and event.b\n * object.on('event.*', (payload) => {\n * console.log('event.a or event.b was fired').;\n * })\n */\n this.on = (event, cb) => {\n\n // keep track of all events on this emitter\n this.events[event] = this.events[event] || new Event(this.chatEngine, this, event);\n\n // call the private _on property\n this._on(event, cb);\n\n return this;\n\n };\n\n }\n\n // add an object as a subobject under a namespoace\n addChild(childName, childOb) {\n // assign the new child object as a property of parent under the\n // given namespace\n this[childName] = childOb;\n\n // assign a data set for the namespace if it doesn't exist\n if (!this._dataset[childName]) {\n this._dataset[childName] = {};\n }\n\n // the new object can use ```this.parent``` to access\n // the root class\n childOb.parent = this;\n\n // bind get() and set() to the data set\n childOb.get = this.get.bind(this._dataset[childName]);\n childOb.set = this.set.bind(this._dataset[childName]);\n }\n\n get(key) {\n return this[key];\n }\n\n set(key, value) {\n if (this[key] && !value) {\n delete this[key];\n } else {\n this[key] = value;\n }\n }\n\n /**\n Binds a plugin to this object\n @param {Object} module The plugin module\n @tutorial using\n */\n plugin(module) {\n\n // add this plugin to a list of plugins for this object\n this.plugins.push(module);\n\n // see if there are plugins to attach to this class\n if (module.extends && module.extends[this.name]) {\n // attach the plugins to this class\n // under their namespace\n this.addChild(module.namespace, new module.extends[this.name]());\n\n this[module.namespace].ChatEngine = this.chatEngine;\n\n // if the plugin has a special construct function\n // run it\n if (this[module.namespace].construct) {\n this[module.namespace].construct();\n }\n\n }\n\n return this;\n\n }\n\n bindProtoPlugins() {\n\n if (this.chatEngine.protoPlugins[this.name]) {\n\n this.chatEngine.protoPlugins[this.name].forEach((module) => {\n this.plugin(module);\n });\n\n }\n\n }\n\n /**\n Broadcasts an event locally to all listeners.\n @private\n @param {String} event The event name\n @param {Object} payload The event payload object\n */\n trigger(event, payload = {}, done = () => {}) {\n\n let complete = () => {\n\n // let plugins modify the event\n this.runPluginQueue('on', event, (next) => {\n next(null, payload);\n }, (reject, pluginResponse) => {\n\n if (reject) {\n done(reject);\n } else {\n // emit this event to any listener\n this._emit(event, pluginResponse);\n done(null, event, pluginResponse);\n }\n\n });\n\n };\n\n // this can be made into plugin\n if (typeof payload === 'object') {\n\n // restore chat in payload\n if (!payload.chat) {\n payload.chat = this;\n }\n\n // if we should try to restore the sender property\n if (payload.sender) {\n\n // the user doesn't exist, create it\n payload.sender = new this.chatEngine.User(payload.sender);\n\n payload.sender._getState(() => {\n complete();\n });\n\n } else {\n // there's no \"sender\" in this object, move on\n complete();\n }\n\n } else {\n // payload is not an object, we want nothing to do with it.\n complete();\n }\n }\n\n /**\n Load plugins and attach a queue of functions to execute before and\n after events are trigger or received.\n\n @private\n @param {String} location Where in the middleeware the event should run (emit, trigger)\n @param {String} event The event name\n @param {String} first The first function to run before the plugins have run\n @param {String} last The last function to run after the plugins have run\n */\n runPluginQueue(location, event, first, last) {\n\n // this assembles a queue of functions to run as middleware\n // event is a triggered event key\n let pluginQueue = [];\n\n // the first function is always required\n pluginQueue.push(first);\n\n // look through the configured plugins\n this.plugins.forEach((pluginItem) => {\n\n // if they have defined a function to run specifically\n // for this event\n if (pluginItem.middleware && pluginItem.middleware[location]) {\n\n if (pluginItem.middleware[location][event]) {\n // add the function to the queue\n pluginQueue.push(pluginItem.middleware[location][event]);\n }\n\n if (pluginItem.middleware[location]['*']) {\n // add the function to the queue\n pluginQueue.push(pluginItem.middleware[location]['*']);\n }\n\n }\n\n });\n\n // waterfall runs the functions in assigned order\n // waiting for one to complete before moving to the next\n // when it's done, the ```last``` parameter is called\n waterfall(pluginQueue, last);\n\n }\n\n onConstructed() {\n\n this.bindProtoPlugins();\n this.trigger(['$', 'created', this.name.toLowerCase()].join('.'));\n\n }\n\n}\n\nmodule.exports = Emitter;\n"},{"id":14,"identifier":"/Users/max/Desktop/CLIENT/chat-engine/src/modules/root_emitter.js","name":"./src/modules/root_emitter.js","index":31,"index2":30,"size":4109,"cacheable":true,"built":true,"optional":false,"prefetched":false,"chunks":[0],"assets":[],"issuer":"/Users/max/Desktop/CLIENT/chat-engine/src/bootstrap.js","issuerId":31,"issuerName":"./src/bootstrap.js","profile":{"factory":10,"building":26},"failed":false,"errors":0,"warnings":0,"reasons":[{"moduleId":5,"moduleIdentifier":"/Users/max/Desktop/CLIENT/chat-engine/src/modules/emitter.js","module":"./src/modules/emitter.js","moduleName":"./src/modules/emitter.js","type":"cjs require","userRequest":"./root_emitter","loc":"2:20-45"},{"moduleId":31,"moduleIdentifier":"/Users/max/Desktop/CLIENT/chat-engine/src/bootstrap.js","module":"./src/bootstrap.js","moduleName":"./src/bootstrap.js","type":"cjs require","userRequest":"./modules/root_emitter","loc":"5:20-53"}],"usedExports":true,"providedExports":null,"optimizationBailout":[],"depth":2,"source":"\n// Allows us to create and bind to events. Everything in ChatEngine is an event\n// emitter\nconst EventEmitter2 = require('eventemitter2').EventEmitter2;\n\n/**\n* The {@link ChatEngine} object is a RootEmitter. Configures an event emitter that other ChatEngine objects inherit. Adds shortcut methods for\n* ```this.on()```, ```this.emit()```, etc.\n* @class RootEmitter\n*/\nclass RootEmitter {\n\n constructor() {\n\n /**\n * @private\n */\n this.events = {};\n\n this.name = 'RootEmitter';\n\n /**\n Create a new EventEmitter2 object for this class.\n\n @private\n */\n this.emitter = new EventEmitter2({\n wildcard: true,\n newListener: true,\n maxListeners: 50,\n verboseMemoryLeak: true\n });\n\n // we bind to make sure wildcards work\n // https://github.com/asyncly/EventEmitter2/issues/186\n\n /**\n Private emit method that broadcasts the event to listeners on this page.\n\n @private\n @param {String} event The event name\n @param {Object} the event payload\n */\n this._emit = this.emitter.emit.bind(this.emitter);\n\n /**\n Listen for a specific event and fire a callback when it's emitted. This is reserved in case ```this.on``` is overwritten.\n\n @private\n @param {String} event The event name\n @param {Function} callback The function to run when the event is emitted\n */\n\n this._on = this.emitter.on.bind(this.emitter);\n\n /**\n * Listen for a specific event and fire a callback when it's emitted. Supports wildcard matching.\n * @method\n * @param {String} event The event name\n * @param {Function} cb The function to run when the event is emitted\n * @example\n *\n * // Get notified whenever someone joins the room\n * object.on('event', (payload) => {\n * console.log('event was fired').\n * })\n *\n * // Get notified of event.a and event.b\n * object.on('event.*', (payload) => {\n * console.log('event.a or event.b was fired').;\n * })\n */\n this.on = (event, callback) => {\n\n // emit the event from the object that created it\n this.emitter.on(event, callback);\n\n return this;\n\n };\n\n /**\n * Stop a callback from listening to an event.\n * @method\n * @param {String} event The event name\n * @example\n * let callback = function(payload;) {\n * console.log('something happend!');\n * };\n * object.on('event', callback);\n * // ...\n * object.off('event', callback);\n */\n this.off = (event, callback) => {\n\n // emit the event from the object that created it\n this.emitter.off(event, callback);\n\n return this;\n\n };\n\n /**\n * Listen for any event on this object and fire a callback when it's emitted\n * @method\n * @param {Function} callback The function to run when any event is emitted. First parameter is the event name and second is the payload.\n * @example\n * object.onAny((event, payload) => {\n * console.log('All events trigger this.');\n * });\n */\n this.onAny = (event, callback) => {\n\n // emit the event from the object that created it\n this.emitter.onAny(event, callback);\n\n return this;\n\n };\n\n /**\n * Listen for an event and only fire the callback a single time\n * @method\n * @param {String} event The event name\n * @param {Function} callback The function to run once\n * @example\n * object.once('message', => (event, payload) {\n * console.log('This is only fired once!');\n * });\n */\n this.once = (event, callback) => {\n\n // emit the event from the object that created it\n this.emitter.once(event, callback);\n\n return this;\n\n };\n\n }\n\n}\n\nmodule.exports = RootEmitter;\n"},{"id":23,"identifier":"/Users/max/Desktop/CLIENT/chat-engine/src/components/event.js","name":"./src/components/event.js","index":51,"index2":47,"size":2220,"cacheable":true,"built":true,"optional":false,"prefetched":false,"chunks":[0],"assets":[],"issuer":"/Users/max/Desktop/CLIENT/chat-engine/src/components/chat.js","issuerId":54,"issuerName":"./src/components/chat.js","profile":{"factory":15,"building":90},"failed":false,"errors":0,"warnings":0,"reasons":[{"moduleId":5,"moduleIdentifier":"/Users/max/Desktop/CLIENT/chat-engine/src/modules/emitter.js","module":"./src/modules/emitter.js","moduleName":"./src/modules/emitter.js","type":"cjs require","userRequest":"../components/event","loc":"3:14-44"},{"moduleId":54,"moduleIdentifier":"/Users/max/Desktop/CLIENT/chat-engine/src/components/chat.js","module":"./src/components/chat.js","moduleName":"./src/components/chat.js","type":"cjs require","userRequest":"../components/event","loc":"3:14-44"}],"usedExports":true,"providedExports":null,"optimizationBailout":[],"depth":3,"source":"/**\n * @class Event\n * Represents an event that may be emitted or subscribed to.\n */\nclass Event {\n\n constructor(chatEngine, chat, event) {\n\n /**\n Events are always a property of a {@link Chat}. Responsible for\n listening to specific events and firing events when they occur.\n @readonly\n @type String\n @see [PubNub Channels](https://support.pubnub.com/support/solutions/articles/14000045182-what-is-a-channel-)\n */\n this.channel = chat.channel;\n\n this.chatEngine = chatEngine;\n\n this.chat = chat;\n\n this.event = event;\n\n this.name = 'Event';\n\n /**\n Forwards events to the Chat that registered the event {@link Chat}\n\n @private\n @param {Object} data The event payload object\n */\n\n // call onMessage when PubNub receives an event\n this.chatEngine.pubnub.addListener({\n message: this.onMessage.bind(this)\n });\n\n return this;\n\n }\n\n onMessage(m) {\n\n if (this.channel === m.channel && m.message.event === this.event) {\n this.chat.trigger(m.message.event, m.message);\n }\n\n }\n\n /**\n Publishes the event over the PubNub network to the {@link Event} channel\n\n @private\n @param {Object} data The event payload object\n */\n publish(m) {\n\n m.event = this.event;\n\n this.chatEngine.pubnub.publish({\n message: m,\n channel: this.channel\n }, (status) => {\n\n if (status.statusCode === 200) {\n\n /**\n * Message successfully published\n * @event Chat#$\".\"publish\".\"success\n * @param {Object} data The message object\n */\n this.chat.trigger('$.publish.success', m);\n } else {\n\n /**\n * There was a problem publishing over the PubNub network.\n * @event Chat#$\".\"error\".\"publish\n */\n this.chatEngine.throwError(this.chat, 'trigger', 'publish', new Error('There was a problem publishing over the PubNub network.'), status);\n }\n\n });\n\n }\n\n}\n\nmodule.exports = Event;\n"},{"id":29,"identifier":"/Users/max/Desktop/CLIENT/chat-engine/src/components/user.js","name":"./src/components/user.js","index":88,"index2":85,"size":5484,"cacheable":true,"built":true,"optional":false,"prefetched":false,"chunks":[0],"assets":[],"issuer":"/Users/max/Desktop/CLIENT/chat-engine/src/bootstrap.js","issuerId":31,"issuerName":"./src/bootstrap.js","profile":{"factory":12,"building":35},"failed":false,"errors":0,"warnings":0,"reasons":[{"moduleId":31,"moduleIdentifier":"/Users/max/Desktop/CLIENT/chat-engine/src/bootstrap.js","module":"./src/bootstrap.js","moduleName":"./src/bootstrap.js","type":"cjs require","userRequest":"./components/user","loc":"8:13-41"},{"moduleId":88,"moduleIdentifier":"/Users/max/Desktop/CLIENT/chat-engine/src/components/me.js","module":"./src/components/me.js","moduleName":"./src/components/me.js","type":"cjs require","userRequest":"./user","loc":"1:13-30"}],"usedExports":true,"providedExports":null,"optimizationBailout":[],"depth":2,"source":"const Emitter = require('../modules/emitter');\n\n/**\n This is our User class which represents a connected client. User's are automatically created and managed by {@link Chat}s, but you can also instantiate them yourself.\n If a User has been created but has never been authenticated, you will recieve 403s when connecting to their feed or direct Chats.\n @class User\n @extends Emitter\n @extends RootEmitter\n @param uuid\n @param state\n */\nclass User extends Emitter {\n\n constructor(chatEngine, uuid, state = {}) {\n\n super();\n\n this.chatEngine = chatEngine;\n\n this.name = 'User';\n\n /**\n The User's unique identifier, usually a device uuid. This helps ChatEngine identify the user between events. This is public id exposed to the network.\n Check out [the wikipedia page on UUIDs](https://en.wikipedia.org/wiki/Universally_unique_identifier).\n\n @readonly\n @type String\n */\n this.uuid = uuid;\n\n /**\n * Gets the user state. See {@link Me#update} for how to assign state values.\n * @return {Object} Returns a generic JSON object containing state information.\n * @example\n *\n * // State\n * let state = user.state;\n */\n this.state = {};\n\n this._stateFetched = false;\n\n /**\n * Feed is a Chat that only streams things a User does, like\n * 'startTyping' or 'idle' events for example. Anybody can subscribe\n * to a User's feed, but only the User can publish to it. Users will\n * not be able to converse in this channel.\n *\n * @type Chat\n * @example\n * // me\n * me.feed.emit('update', 'I may be away from my computer right now');\n *\n * // another instance\n * them.feed.connect();\n * them.feed.on('update', (payload) => {})\n */\n\n // grants for these chats are done on auth. Even though they're marked private, they are locked down via the server\n this.feed = new this.chatEngine.Chat([chatEngine.global.channel, 'user', uuid, 'read.', 'feed'].join('#'), false, this.constructor.name === 'Me', {}, 'system');\n\n /**\n * Direct is a private channel that anybody can publish to but only\n * the user can subscribe to. Great for pushing notifications or\n * inviting to other chats. Users will not be able to communicate\n * with one another inside of this chat. Check out the\n * {@link Chat#invite} method for private chats utilizing\n * {@link User#direct}.\n *\n * @type Chat\n * @example\n * // me\n * me.direct.on('private-message', (payload) -> {\n * console.log(payload.sender.uuid, 'sent your a direct message');\n * });\n *\n * // another instance\n * them.direct.connect();\n * them.direct.emit('private-message', {secret: 42});\n */\n this.direct = new this.chatEngine.Chat([chatEngine.global.channel, 'user', uuid, 'write.', 'direct'].join('#'), false, this.constructor.name === 'Me', {}, 'system');\n\n // if the user does not exist at all and we get enough\n // information to build the user\n if (!chatEngine.users[uuid]) {\n chatEngine.users[uuid] = this;\n }\n\n // update this user's state in it's created context\n this.assign(state);\n\n return this;\n\n }\n\n /**\n * @private\n * @param {Object} state The new state for the user\n * @param {Chat} chat Chatroom to retrieve state from\n */\n update(state) {\n let oldState = this.state || {};\n this.state = Object.assign(oldState, state);\n }\n\n /**\n this is only called from network updates\n\n @private\n */\n assign(state) {\n this.update(state);\n }\n\n /**\n Get stored user state from remote server.\n @private\n */\n _getState(callback) {\n\n if (!this._stateFetched) {\n\n this.chatEngine.pubnub.getState({\n uuid: this.uuid,\n channels: [this.chatEngine.global.channel]\n }, (status, response) => {\n\n if (status.statusCode === 200) {\n\n let pnState = response.channels[this.chatEngine.global.channel];\n if (Object.keys(pnState).length) {\n\n this.assign(response.data);\n\n this._stateFetched = true;\n callback(this.state);\n\n } else {\n\n this.chatEngine.request('get', 'user_state', {\n user: this.uuid\n })\n .then((res) => {\n\n this.assign(res.data);\n\n this._stateFetched = true;\n callback(this.state);\n\n })\n .catch((err) => {\n // console.log('this is hte err', err);\n this.chatEngine.throwError(this, 'trigger', 'getState', err);\n });\n\n }\n\n } else {\n this.chatEngine.throwError(this, 'trigger', 'getState', new Error('There was a problem getting state from the PubNub network.'));\n }\n\n });\n\n } else {\n callback(this.state);\n }\n\n }\n\n}\n\nmodule.exports = User;\n"},{"id":30,"identifier":"/Users/max/Desktop/CLIENT/chat-engine/src/index.js","name":"./src/index.js","index":0,"index2":88,"size":1425,"cacheable":true,"built":true,"optional":false,"prefetched":false,"chunks":[0],"assets":[],"issuer":null,"issuerId":null,"issuerName":null,"profile":{"factory":17,"building":18},"failed":false,"errors":0,"warnings":0,"reasons":[],"usedExports":true,"providedExports":null,"optimizationBailout":[],"depth":0,"source":"// allows asynchronous execution flow.\nconst init = require('./bootstrap');\n\n/**\nGlobal object used to create an instance of {@link ChatEngine}.\n\n@alias ChatEngineCore\n@param pnConfig {Object} ChatEngine is based off PubNub. Supply your PubNub configuration parameters here. See the getting started tutorial and [the PubNub docs](https://www.pubnub.com/docs/java-se-java/api-reference-configuration).\n@param ceConfig {Object} A list of chat engine specific config options.\n@param [ceConfig.globalChannel=chat-engine] {String} The root channel. See {@link ChatEngine.global}\n@param [ceConfig.throwErrors=true] {Boolean} Throws errors in JS console.\n@param [ceConfig.endpoint] {String} The root URL used to manage permissions for private channels.\n@return {ChatEngine} Returns an instance of {@link ChatEngine}\n@example\nChatEngine = ChatEngineCore.create({\n publishKey: 'demo',\n subscribeKey: 'demo'\n});\n*/\n\nconst create = (pnConfig, ceConfig = {}) => {\n\n if (ceConfig.globalChannel) {\n ceConfig.globalChannel = ceConfig.globalChannel.toString();\n } else {\n ceConfig.globalChannel = 'chat-engine';\n }\n\n if (typeof ceConfig.throwErrors === 'undefined') {\n ceConfig.throwErrors = true;\n }\n\n // return an instance of ChatEngine\n return init(ceConfig, pnConfig);\n\n};\n\n// export the ChatEngine api\nmodule.exports = {\n plugin: {}, // leave a spot for plugins to exist\n create\n};\n"},{"id":31,"identifier":"/Users/max/Desktop/CLIENT/chat-engine/src/bootstrap.js","name":"./src/bootstrap.js","index":1,"index2":87,"size":16020,"cacheable":true,"built":true,"optional":false,"prefetched":false,"chunks":[0],"assets":[],"issuer":"/Users/max/Desktop/CLIENT/chat-engine/src/index.js","issuerId":30,"issuerName":"./src/index.js","profile":{"factory":3,"building":37},"failed":false,"errors":0,"warnings":0,"reasons":[{"moduleId":30,"moduleIdentifier":"/Users/max/Desktop/CLIENT/chat-engine/src/index.js","module":"./src/index.js","moduleName":"./src/index.js","type":"cjs require","userRequest":"./bootstrap","loc":"2:13-35"}],"usedExports":true,"providedExports":null,"optimizationBailout":[],"depth":1,"source":"const axios = require('axios');\nconst PubNub = require('pubnub');\nconst pack = require('../package.json');\n\nconst RootEmitter = require('./modules/root_emitter');\nconst Chat = require('./components/chat');\nconst Me = require('./components/me');\nconst User = require('./components/user');\nconst async = require('async');\n\n/**\n @class ChatEngine\n @extends RootEmitter\n @return {ChatEngine} Returns an instance of {@link ChatEngine}\n */\nmodule.exports = (ceConfig = {}, pnConfig = {}) => {\n\n // Create the root ChatEngine object\n let ChatEngine = new RootEmitter();\n\n ChatEngine.ceConfig = ceConfig;\n ChatEngine.pnConfig = pnConfig;\n\n ChatEngine.pnConfig.heartbeatInterval = ChatEngine.pnConfig.heartbeatInterval || 30;\n ChatEngine.pnConfig.presenceTimeout = ChatEngine.pnConfig.presenceTimeout || 60;\n\n ChatEngine.ceConfig.endpoint = ChatEngine.ceConfig.endpoint || 'https://pubsub.pubnub.com/v1/blocks/sub-key/' + ChatEngine.pnConfig.subscribeKey + '/chat-engine-server';\n ChatEngine.ceConfig.globalChannel = ChatEngine.ceConfig.globalChannel || 'chat-engine-global';\n\n /**\n * A map of all known {@link User}s in this instance of ChatEngine.\n * @type {Object}\n * @memberof ChatEngine\n */\n ChatEngine.users = {};\n\n /**\n * A map of all known {@link Chat}s in this instance of ChatEngine.\n * @memberof ChatEngine\n * @type {Object}\n */\n ChatEngine.chats = {};\n\n /**\n * A global {@link Chat} that all {@link User}s join when they connect to ChatEngine. Useful for announcements, alerts, and global events.\n * @member {Chat} global\n * @memberof ChatEngine\n */\n ChatEngine.global = false;\n\n /**\n * This instance of ChatEngine represented as a special {@link User} know as {@link Me}.\n * @member {Me} me\n * @memberof ChatEngine\n */\n ChatEngine.me = false;\n\n /**\n * An instance of PubNub, the networking infrastructure that powers the realtime communication between {@link User}s in {@link Chats}.\n * @member {Object} pubnub\n * @memberof ChatEngine\n */\n ChatEngine.pubnub = false;\n\n /**\n * Indicates if ChatEngine has fired the {@link ChatEngine#$\".\"ready} event.\n * @member {Object} ready\n * @memberof ChatEngine\n */\n ChatEngine.ready = false;\n\n /**\n * The package.json for ChatEngine. Used mainly for detecting package version.\n * @type {Object}\n */\n ChatEngine.package = pack;\n\n ChatEngine.throwError = (self, cb, key, ceError, payload = {}) => {\n\n if (ceConfig.throwErrors) {\n // throw ceError;\n console.error(payload);\n throw ceError;\n }\n\n payload.ceError = ceError.toString();\n\n self[cb](['$', 'error', key].join('.'), payload);\n\n };\n\n if (ceConfig.debug) {\n ChatEngine.onAny((event, payload) => {\n console.info('debug:', event, payload);\n });\n }\n\n ChatEngine.protoPlugins = {};\n\n /**\n * Bind a plugin to all future instances of a Class.\n * @method ChatEngine#proto\n * @param {String} className The string representation of a class to bind to\n * @param {Class} plugin The plugin function.\n */\n ChatEngine.proto = (className, plugin) => {\n ChatEngine.protoPlugins[className] = ChatEngine.protoPlugins[className] || [];\n ChatEngine.protoPlugins[className].push(plugin);\n };\n\n ChatEngine.request = (method, route, inputBody = {}, inputParams = {}) => {\n\n let body = {\n uuid: pnConfig.uuid,\n global: ceConfig.globalChannel,\n authData: ChatEngine.me.authData,\n authKey: pnConfig.authKey\n };\n\n let params = {\n route\n };\n\n body = Object.assign(body, inputBody);\n params = Object.assign(params, inputParams);\n\n if (method === 'get' || method === 'delete') {\n params = Object.assign(params, body);\n return axios[method](ceConfig.endpoint, { params });\n } else {\n return axios[method](ceConfig.endpoint, body, { params });\n }\n\n\n };\n\n ChatEngine.parseChannel = (channel) => {\n\n let info = channel.split('#');\n\n return {\n global: info[0],\n type: info[1],\n private: info[2] === 'private.'\n };\n\n };\n\n /**\n * Get the internal channel name of supplied string\n * @private\n * @param {[type]} original [description]\n * @param {Boolean} isPrivate [description]\n * @return {[type]} [description]\n */\n ChatEngine.augmentChannel = (original = new Date().getTime(), isPrivate = true) => {\n\n let channel = original.toString();\n\n // public.* has PubNub permissions for everyone to read and write\n // private.* is totally locked down and users must be granted access one by one\n let chanPrivString = 'public.';\n\n if (isPrivate) {\n chanPrivString = 'private.';\n }\n\n if (channel.indexOf(ChatEngine.ceConfig.globalChannel) === -1) {\n channel = [ChatEngine.ceConfig.globalChannel, 'chat', chanPrivString, channel].join('#');\n }\n\n return channel;\n\n };\n\n /**\n * Connect to realtime service and create instance of {@link Me}\n * @method ChatEngine#connect\n * @param {String} uuid A unique string for {@link Me}. It can be a device id, username, user id, email, etc.\n * @param {Object} state An object containing information about this client ({@link Me}). This JSON object is sent to all other clients on the network, so no passwords!\n * @param {String} [authKey] A authentication secret. Will be sent to authentication backend for validation. This is usually an access token or password. This is different from UUID as a user can have a single UUID but multiple auth keys.\n * @param {Object} [authData] Additional data to send to the authentication endpoint to help verify a valid session. ChatEngine SDK does not make use of this, but you might!\n * @fires $\".\"connected\n */\n ChatEngine.connect = (uuid, state = {}, authKey = false, authData) => {\n\n // this creates a user known as Me and\n // connects to the global chatroom\n\n pnConfig.uuid = uuid;\n\n pnConfig.authKey = authKey || pnConfig.uuid;\n\n let restoreSession = () => {\n\n let groups = ['custom', 'rooms', 'system'];\n\n groups.forEach((group) => {\n\n let channelGroup = [ceConfig.globalChannel, pnConfig.uuid, group].join('#');\n\n ChatEngine.pubnub.channelGroups.listChannels({\n channelGroup\n }, (status, response) => {\n\n if (status.error) {\n console.log('operation failed w/ error:', status);\n return;\n }\n\n response.channels.forEach((channel) => {\n\n ChatEngine.me.addChatToSession({\n channel,\n private: ChatEngine.parseChannel(channel).private,\n group\n });\n\n });\n\n });\n\n });\n\n };\n\n let complete = () => {\n\n ChatEngine.pubnub = new PubNub(pnConfig);\n\n // create a new chat to use as global chat\n // we don't do auth on this one because it's assumed to be done with the /auth request below\n ChatEngine.global = new ChatEngine.Chat(ceConfig.globalChannel, false, true, {}, 'system');\n\n // build the current user\n ChatEngine.me = new Me(ChatEngine, pnConfig.uuid, authData);\n ChatEngine.me.update(state);\n\n /**\n * Fired when a {@link Me} has been created within ChatEngine.\n * @event ChatEngine#$\".\"created\".\"me\n * @example\n * ChatEngine.on('$.created.me', (data, me) => {\n * console.log('Me was created', me);\n * });\n */\n ChatEngine.me.onConstructed();\n\n ChatEngine.global.on('$.connected', () => {\n\n /**\n * Fired when ChatEngine is connected to the internet and ready to go!\n * @event ChatEngine#$\".\"ready\n * @example\n * ChatEngine.on('$.ready', (data) => {\n * let me = data.me;\n * })\n */\n ChatEngine._emit('$.ready', {\n me: ChatEngine.me\n });\n\n ChatEngine.global.getUserUpdates();\n\n let chanGroups = [\n ceConfig.globalChannel + '#' + ChatEngine.me.uuid + '#rooms',\n ceConfig.globalChannel + '#' + ChatEngine.me.uuid + '#system',\n ceConfig.globalChannel + '#' + ChatEngine.me.uuid + '#custom'\n ];\n\n // listen to all PubNub events for this Chat\n ChatEngine.pubnub.addListener({\n presence: (payload) => {\n\n if (ChatEngine.chats[payload.channel]) {\n ChatEngine.chats[payload.channel].onPresence(payload);\n }\n\n }\n });\n\n ChatEngine.pubnub.subscribe({\n channelGroups: chanGroups,\n withPresence: true\n });\n\n ChatEngine.ready = true;\n\n restoreSession();\n\n });\n\n /**\n Fires when PubNub network connection changes.\n\n @private\n @param {Object} statusEvent The response status\n */\n ChatEngine.pubnub.addListener({\n status: (statusEvent) => {\n\n /**\n * SDK detected that network is online.\n * @event ChatEngine#$\".\"network\".\"up\".\"online\n */\n\n /**\n * SDK detected that network is down.\n * @event ChatEngine#$\".\"network\".\"down\".\"offline\n */\n\n /**\n * A subscribe event experienced an exception when running.\n * @event ChatEngine#$\".\"network\".\"down\".\"issue\n */\n\n /**\n * SDK was able to reconnect to pubnub.\n * @event ChatEngine#$\".\"network\".\"up\".\"reconnected\n */\n\n /**\n * SDK subscribed with a new mix of channels.\n * @event ChatEngine#$\".\"network\".\"up\".\"connected\n */\n\n /**\n * JSON parsing crashed.\n * @event ChatEngine#$\".\"network\".\"down\".\"malformed\n */\n\n /**\n * Server rejected the request.\n * @event ChatEngine#$\".\"network\".\"down\".\"badrequest\n */\n\n /**\n * If using decryption strategies and the decryption fails.\n * @event ChatEngine#$\".\"network\".\"down\".\"decryption\n */\n\n /**\n * Request timed out.\n * @event ChatEngine#$\".\"network\".\"down\".\"timeout\n */\n\n /**\n * PAM permission failure.\n * @event ChatEngine#$\".\"network\".\"down\".\"denied\n */\n\n // map the pubnub events into chat engine events\n let categories = {\n PNNetworkUpCategory: 'up.online',\n PNNetworkDownCategory: 'down.offline',\n PNNetworkIssuesCategory: 'down.issue',\n PNReconnectedCategory: 'up.reconnected',\n PNConnectedCategory: 'up.connected',\n PNAccessDeniedCategory: 'down.denied',\n PNMalformedResponseCategory: 'down.malformed',\n PNBadRequestCategory: 'down.badrequest',\n PNDecryptionErrorCategory: 'down.decryption',\n PNTimeoutCategory: 'down.timeout'\n };\n\n let eventName = ['$', 'network', categories[statusEvent.category] || 'other'].join('.');\n\n if (statusEvent.affectedChannels) {\n statusEvent.affectedChannels.forEach((channel) => {\n\n let chat = ChatEngine.chats[channel];\n\n if (chat) {\n // connected category tells us the chat is ready\n if (statusEvent.category === 'PNConnectedCategory') {\n chat.onConnectionReady();\n }\n\n // trigger the network events\n chat.trigger(eventName, statusEvent);\n\n } else {\n ChatEngine._emit(eventName, statusEvent);\n }\n });\n } else {\n ChatEngine._emit(eventName, statusEvent);\n }\n }\n });\n };\n\n async.parallel([\n (next) => {\n ChatEngine.request('post', 'bootstrap').then(() => {\n next(null);\n }).catch(next);\n },\n (next) => {\n ChatEngine.request('post', 'user_read').then(() => {\n next(null);\n }).catch(next);\n },\n (next) => {\n ChatEngine.request('post', 'user_write').then(() => {\n next(null);\n }).catch(next);\n },\n (next) => {\n ChatEngine.request('post', 'group').then(complete).catch(next);\n }\n ], (error) => {\n if (error) {\n ChatEngine.throwError(ChatEngine, '_emit', 'auth', new Error('There was a problem logging into the auth server (' + ceConfig.endpoint + ').'), { error });\n }\n });\n\n };\n\n /**\n * The {@link Chat} class.\n * @member {Chat} Chat\n * @memberof ChatEngine\n * @see {@link Chat}\n */\n ChatEngine.Chat = function (...args) {\n\n let internalChannel = ChatEngine.augmentChannel(args[0], args[1]);\n\n if (ChatEngine.chats[internalChannel]) {\n return ChatEngine.chats[internalChannel];\n } else {\n\n let newChat = new Chat(ChatEngine, ...args);\n\n /**\n * Fired when a {@link Chat} has been created within ChatEngine.\n * @event ChatEngine#$\".\"created\".\"chat\n * @example\n * ChatEngine.on('$.created.chat', (data, chat) => {\n * console.log('Chat was created', chat);\n * });\n */\n newChat.onConstructed();\n\n return newChat;\n\n }\n\n };\n\n /**\n * The {@link User} class.\n * @member {User} User\n * @memberof ChatEngine\n * @see {@link User}\n */\n ChatEngine.User = function (...args) {\n\n if (ChatEngine.me.uuid === args[0]) {\n return ChatEngine.me;\n } else if (ChatEngine.users[args[0]]) {\n return ChatEngine.users[args[0]];\n } else {\n\n let newUser = new User(ChatEngine, ...args);\n\n /**\n * Fired when a {@link User} has been created within ChatEngine.\n * @event ChatEngine#$\".\"created\".\"user\n * @example\n * ChatEngine.on('$.created.user', (data, user) => {\n * console.log('Chat was created', user);\n * });\n */\n newUser.onConstructed();\n\n return newUser;\n\n }\n\n };\n\n return ChatEngine;\n\n};\n"},{"id":52,"identifier":"/Users/max/Desktop/CLIENT/chat-engine/node_modules/json-loader/index.js!/Users/max/Desktop/CLIENT/chat-engine/package.json","name":"./package.json","index":30,"index2":28,"size":1304,"cacheable":true,"built":true,"optional":false,"prefetched":false,"chunks":[0],"assets":[],"issuer":"/Users/max/Desktop/CLIENT/chat-engine/src/bootstrap.js","issuerId":31,"issuerName":"./src/bootstrap.js","profile":{"factory":97,"building":3},"failed":false,"errors":0,"warnings":0,"reasons":[{"moduleId":31,"moduleIdentifier":"/Users/max/Desktop/CLIENT/chat-engine/src/bootstrap.js","module":"./src/bootstrap.js","moduleName":"./src/bootstrap.js","type":"cjs require","userRequest":"../package.json","loc":"3:13-39"}],"usedExports":true,"providedExports":null,"optimizationBailout":[],"depth":2,"source":"module.exports = {\"author\":\"PubNub\",\"name\":\"chat-engine\",\"version\":\"0.8.3\",\"description\":\"ChatEngine\",\"main\":\"src/index.js\",\"scripts\":{\"deploy\":\"gulp; npm publish;\",\"docs\":\"jsdoc src/index.js -c jsdoc.json\"},\"repository\":{\"type\":\"git\",\"url\":\"git+https://github.com/pubnub/chat-engine.git\"},\"keywords\":[\"pubnub\",\"chat\",\"sdk\",\"realtime\"],\"bugs\":{\"url\":\"https://github.com/pubnub/chat-engine/issues\"},\"homepage\":\"https://github.com/pubnub/chat-engine#readme\",\"devDependencies\":{\"body-parser\":\"^1.17.2\",\"chai\":\"^3.5.0\",\"chat-engine-typing-indicator\":\"0.0.x\",\"docdash\":\"^0.4.0\",\"es6-promise\":\"^4.1.1\",\"eslint\":\"^4.7.1\",\"eslint-config-airbnb\":\"^15.1.0\",\"eslint-plugin-import\":\"^2.7.0\",\"express\":\"^4.15.3\",\"gulp\":\"^3.9.1\",\"gulp-clean\":\"^0.3.2\",\"gulp-eslint\":\"^4.0.0\",\"gulp-istanbul\":\"^1.1.2\",\"gulp-jsdoc3\":\"^1.0.1\",\"gulp-mocha\":\"^3.0.1\",\"gulp-rename\":\"^1.2.2\",\"gulp-uglify\":\"^2.0.0\",\"gulp-uglify-es\":\"^0.1.3\",\"http-server\":\"^0.10.0\",\"isparta\":\"^4.0.0\",\"jsdoc\":\"^3.5.5\",\"mocha\":\"^3.1.2\",\"proxyquire\":\"^1.8.0\",\"pubnub-functions-mock\":\"^0.0.6\",\"request\":\"^2.82.0\",\"run-sequence\":\"^2.2.0\",\"sinon\":\"^4.0.0\",\"stats-webpack-plugin\":\"^0.6.1\",\"uglifyjs-webpack-plugin\":\"^1.0.1\",\"webpack\":\"^3.6.0\",\"webpack-stream\":\"^4.0.0\"},\"dependencies\":{\"async\":\"^2.1.2\",\"axios\":\"^0.16.2\",\"eventemitter2\":\"^2.2.1\",\"pubnub\":\"^4.17.0\"}}"},{"id":54,"identifier":"/Users/max/Desktop/CLIENT/chat-engine/src/components/chat.js","name":"./src/components/chat.js","index":33,"index2":84,"size":21104,"cacheable":true,"built":true,"optional":false,"prefetched":false,"chunks":[0],"assets":[],"issuer":"/Users/max/Desktop/CLIENT/chat-engine/src/bootstrap.js","issuerId":31,"issuerName":"./src/bootstrap.js","profile":{"factory":11,"building":69,"dependencies":14},"failed":false,"errors":0,"warnings":0,"reasons":[{"moduleId":31,"moduleIdentifier":"/Users/max/Desktop/CLIENT/chat-engine/src/bootstrap.js","module":"./src/bootstrap.js","moduleName":"./src/bootstrap.js","type":"cjs require","userRequest":"./components/chat","loc":"6:13-41"}],"usedExports":true,"providedExports":null,"optimizationBailout":[],"depth":2,"source":"const async = require('async');\nconst Emitter = require('../modules/emitter');\nconst Event = require('../components/event');\nconst Search = require('../components/search');\n\n/**\n This is the root {@link Chat} class that represents a chat room\n\n @param {String} [channel=new Date().getTime()] A unique identifier for this chat {@link Chat}. The channel is the unique name of a {@link Chat}, and is usually something like \"The Watercooler\", \"Support\", or \"Off Topic\". See [PubNub Channels](https://support.pubnub.com/support/solutions/articles/14000045182-what-is-a-channel-).\n @param {Boolean} [isPrivate=true] Attempt to authenticate ourselves before connecting to this {@link Chat}.\n @param {Boolean} [autoConnect=true] Connect to this chat as soon as its initiated. If set to ```false```, call the {@link Chat#connect} method to connect to this {@link Chat}.\n @param {String} [group='default'] Groups chat into a \"type\". This is the key which chats will be grouped into within {@link ChatEngine.session} object.\n @class Chat\n @extends Emitter\n @extends RootEmitter\n @fires Chat#$\".\"ready\n @fires Chat#$\".\"state\n @fires Chat#$\".\"online\".\"*\n @fires Chat#$\".\"offline\".\"*\n */\nclass Chat extends Emitter {\n\n constructor(chatEngine, channel = new Date().getTime(), isPrivate = true, autoConnect = true, meta = {}, group = 'custom') {\n\n super(chatEngine);\n\n this.chatEngine = chatEngine;\n\n this.name = 'Chat';\n\n this.meta = meta;\n\n this.group = group;\n\n /**\n * Excludes all users from reading or writing to the {@link chat} unless they have been explicitly invited via {@link Chat#invite};\n * @type Boolean\n * @readonly\n */\n this.isPrivate = isPrivate;\n\n /**\n * A string identifier for the Chat room. Any chat with an identical channel will be able to communicate with one another.\n * @type String\n * @readonly\n * @see [PubNub Channels](https://support.pubnub.com/support/solutions/articles/14000045182-what-is-a-channel-)\n */\n\n this.meta = {};\n\n /**\n * Excludes all users from reading or writing to the {@link chat} unless they have been explicitly invited via {@link Chat#invite};\n * @type Boolean\n * @readonly\n */\n this.isPrivate = isPrivate;\n\n this.channel = this.chatEngine.augmentChannel(channel, this.isPrivate);\n\n /**\n A list of users in this {@link Chat}. Automatically kept in sync as users join and leave the chat.\n Use [$.join](/Chat.html#event:$%2522.%2522join) and related events to get notified when this changes\n\n @type Object\n @readonly\n */\n this.users = {};\n\n /**\n * Boolean value that indicates of the Chat is connected to the network\n * @type {Boolean}\n */\n this.connected = false;\n\n this.chatEngine.chats[this.channel] = this;\n\n if (autoConnect) {\n this.connect();\n }\n\n return this;\n\n }\n\n /**\n Updates list of {@link User}s in this {@link Chat}\n based on who is online now.\n\n @private\n @param {Object} status The response status\n @param {Object} response The response payload object\n */\n onHereNow(status, response) {\n\n if (status.error) {\n\n /**\n * There was a problem fetching the presence of this chat\n * @event Chat#$\".\"error\".\"presence\n */\n this.chatEngine.throwError(this, 'trigger', 'presence', new Error('Getting presence of this Chat. Make sure PubNub presence is enabled for this key'), status);\n\n } else {\n\n // get the list of occupants in this channel\n let occupants = response.channels[this.channel].occupants;\n\n // format the userList for rltm.js standard\n occupants.forEach((occupant) => {\n this.userUpdate(occupant.uuid, occupant.state);\n });\n\n }\n\n }\n\n /**\n * Turns a {@link Chat} into a JSON representation.\n * @return {Object}\n */\n objectify() {\n\n return {\n channel: this.channel,\n group: this.group,\n private: this.isPrivate,\n meta: this.meta\n };\n\n }\n\n /**\n * Invite a user to this Chat. Authorizes the invited user in the Chat and sends them an invite via {@link User#direct}.\n * @param {User} user The {@link User} to invite to this chatroom.\n * @fires Me#event:$\".\"invite\n * @example\n * // one user running ChatEngine\n * let secretChat = new ChatEngine.Chat('secret-channel');\n * secretChat.invite(someoneElse);\n *\n * // someoneElse in another instance of ChatEngine\n * me.direct.on('$.invite', (payload) => {\n * let secretChat = new ChatEngine.Chat(payload.data.channel);\n * });\n */\n invite(user) {\n\n this.chatEngine.request('post', 'invite', {\n to: user.uuid,\n chat: this.objectify()\n })\n .then(() => {\n\n let send = () => {\n\n /**\n * Notifies {@link Me} that they've been invited to a new private {@link Chat}.\n * Fired by the {@link Chat#invite} method.\n * @event Me#$\".\"invite\n * @tutorial private\n * @example\n * me.direct.on('$.invite', (payload) => {\n * let privChat = new ChatEngine.Chat(payload.data.channel));\n * });\n */\n user.direct.emit('$.invite', {\n channel: this.channel\n });\n\n };\n\n if (!user.direct.connected) {\n user.direct.connect();\n user.direct.on('$.connected', send);\n } else {\n send();\n }\n\n })\n .catch((error) => {\n this.chatEngine.throwError(this, 'trigger', 'auth', new Error('Something went wrong while making a request to authentication server.'), { error });\n });\n\n }\n\n /**\n Keep track of {@link User}s in the room by subscribing to PubNub presence events.\n\n @private\n @param {Object} data The PubNub presence response for this event\n */\n onPresence(presenceEvent) {\n\n // make sure channel matches this channel\n\n // someone joins channel\n if (presenceEvent.action === 'join') {\n\n let user = this.createUser(presenceEvent.uuid, presenceEvent.state);\n\n /**\n * Fired when a {@link User} has joined the room.\n *\n * @event Chat#$\".\"online\".\"join\n * @param {Object} data The payload returned by the event\n * @param {User} data.user The {@link User} that came online\n * @example\n * chat.on('$.join', (data) => {\n * console.log('User has joined the room!', data.user);\n * });\n */\n\n // It's possible for PubNub to send us both a join and have the user appear in here_now\n // Avoid firing duplicate $.online events.\n if (!this.users[user.uuid]) {\n this.trigger('$.online.join', { user });\n }\n\n }\n\n // someone leaves channel\n if (presenceEvent.action === 'leave') {\n this.userLeave(presenceEvent.uuid);\n }\n\n // someone timesout\n if (presenceEvent.action === 'timeout') {\n this.userDisconnect(presenceEvent.uuid);\n }\n\n // someone's state is updated\n if (presenceEvent.action === 'state-change') {\n this.userUpdate(presenceEvent.uuid, presenceEvent.state);\n }\n\n\n }\n\n update(data) {\n\n let oldMeta = this.meta || {};\n this.meta = Object.assign(oldMeta, data);\n\n this.chatEngine.request('post', 'chat', {\n chat: this.objectify()\n }).then(() => {\n }).catch((error) => {\n this.chatEngine.throwError(this, 'trigger', 'auth', new Error('Something went wrong while making a request to authentication server.'), { error });\n });\n\n }\n\n /**\n * Send events to other clients in this {@link User}.\n * Events are trigger over the network and all events are made\n * on behalf of {@link Me}\n *\n * @param {String} event The event name\n * @param {Object} data The event payload object\n * @example\n * chat.emit('custom-event', {value: true});\n * chat.on('custom-event', (payload) => {\n * console.log(payload.sender.uuid, 'emitted the value', payload.data.value);\n * });\n */\n emit(event, data) {\n if (event === 'message' && typeof data !== 'object') {\n throw new Error('the payload has to be an object');\n }\n\n // create a standardized payload object\n let payload = {\n data, // the data supplied from params\n sender: this.chatEngine.me.uuid, // my own uuid\n chat: this, // an instance of this chat\n event,\n chatengineSDK: this.chatEngine.package.version\n };\n\n // run the plugin queue to modify the event\n this.runPluginQueue('emit', event, (next) => {\n next(null, payload);\n }, (err, pluginResponse) => {\n\n // remove chat otherwise it would be serialized\n // instead, it's rebuilt on the other end.\n // see this.trigger\n delete pluginResponse.chat;\n\n // publish the event and data over the configured channel\n\n // ensure the event exists within the global space\n this.events[event] = this.events[event] || new Event(this.chatEngine, this, event);\n\n this.events[event].publish(pluginResponse);\n\n });\n\n }\n\n /**\n Add a user to the {@link Chat}, creating it if it doesn't already exist.\n\n @private\n @param {String} uuid The user uuid\n @param {Object} state The user initial state\n @param {Boolean} trigger Force a trigger that this user is online\n */\n createUser(uuid, state) {\n\n // Ensure that this user exists in the global list\n // so we can reference it from here out\n this.chatEngine.users[uuid] = this.chatEngine.users[uuid] || new this.chatEngine.User(uuid);\n this.chatEngine.users[uuid].assign(state);\n\n // trigger the join event over this chatroom\n if (!this.users[uuid]) {\n\n /**\n * Broadcast that a {@link User} has come online. This is when\n * the framework firsts learn of a user. This can be triggered\n * by, ```$.join```, or other network events that\n * notify the framework of a new user.\n *\n * @event Chat#$\".\"online\".\"here\n * @param {Object} data The payload returned by the event\n * @param {User} data.user The {@link User} that came online\n * @example\n * chat.on('$.online.here', (data) => {\n * console.log('User has come online:', data.user);\n * });\n */\n\n this.trigger('$.online.here', {\n user: this.chatEngine.users[uuid]\n });\n\n }\n\n // store this user in the chatroom\n this.users[uuid] = this.chatEngine.users[uuid];\n\n // return the instance of this user\n return this.chatEngine.users[uuid];\n\n }\n\n /**\n * Update a user's state.\n * @private\n * @param {String} uuid The {@link User} uuid\n * @param {Object} state State to update for the user\n */\n userUpdate(uuid, state) {\n\n // ensure the user exists within the global space\n this.chatEngine.users[uuid] = this.chatEngine.users[uuid] || new this.chatEngine.User(uuid);\n\n // if we don't know about this user\n if (!this.users[uuid]) {\n // do the whole join thing\n this.createUser(uuid, state);\n }\n\n // update this user's state in this chatroom\n this.users[uuid].assign(state);\n\n /**\n * Broadcast that a {@link User} has changed state.\n * @event ChatEngine#$\".\"state\n * @param {Object} data The payload returned by the event\n * @param {User} data.user The {@link User} that changed state\n * @param {Object} data.state The new user state\n * @example\n * ChatEngine.on('$.state', (data) => {\n * console.log('User has changed state:', data.user, 'new state:', data.state);\n * });\n */\n this.chatEngine._emit('$.state', {\n user: this.users[uuid],\n state: this.users[uuid].state\n });\n\n }\n\n /**\n * Leave from the {@link Chat} on behalf of {@link Me}. Disconnects from the {@link Chat} and will stop\n * receiving events.\n * @fires Chat#event:$\".\"offline\".\"leave\n * @example\n * chat.leave();\n */\n leave() {\n\n // unsubscribe from the channel locally\n this.chatEngine.pubnub.unsubscribe({\n channels: [this.channel]\n });\n\n this.chatEngine.request('post', 'leave', { chat: this.objectify() })\n .then(() => {\n\n this.connected = false;\n\n this.trigger('$.disconnected');\n\n this.chatEngine.me.sync.emit('$.session.chat.leave', { subject: this.objectify() });\n\n })\n .catch((error) => {\n this.chatEngine.throwError(this, 'trigger', 'auth', new Error('Something went wrong while making a request to chat server.'), { error });\n });\n\n }\n\n /**\n Perform updates when a user has left the {@link Chat}.\n\n @private\n */\n userLeave(uuid) {\n\n // make sure this event is real, user may have already left\n if (this.users[uuid]) {\n\n // if a user leaves, trigger the event\n\n /**\n * Fired when a {@link User} intentionally leaves a {@link Chat}.\n *\n * @event Chat#$\".\"offline\".\"leave\n * @param {Object} data The data payload from the event\n * @param {User} user The {@link User} that has left the room\n * @example\n * chat.on('$.offline.leave', (data) => {\n * console.log('User left the room manually:', data.user);\n * });\n */\n this.trigger('$.offline.leave', {\n user: this.users[uuid]\n });\n\n // remove the user from the local list of users\n delete this.users[uuid];\n\n // we don't remove the user from the global list,\n // because they may be online in other channels\n\n } else {\n\n // that user isn't in the user list\n // we never knew about this user or they already left\n\n // console.log('user already left');\n }\n }\n\n /**\n Fired when a user disconnects from the {@link Chat}\n\n @private\n @param {String} uuid The uuid of the {@link Chat} that left\n */\n userDisconnect(uuid) {\n\n // make sure this event is real, user may have already left\n if (this.users[uuid]) {\n\n /**\n * Fired specifically when a {@link User} looses network connection\n * to the {@link Chat} involuntarily.\n *\n * @event Chat#$\".\"offline\".\"disconnect\n * @param {Object} data The {@link User} that disconnected\n * @param {Object} data.user The {@link User} that disconnected\n * @example\n * chat.on('$.offline.disconnect', (data) => {\n * console.log('User disconnected from the network:', data.user);\n * });\n */\n\n this.trigger('$.offline.disconnect', { user: this.users[uuid] });\n }\n\n }\n\n /**\n Set the state for {@link Me} within this {@link User}.\n Broadcasts the ```$.state``` event on other clients\n\n @private\n @param {Object} state The new state {@link Me} will have within this {@link User}\n */\n setState(state) {\n this.chatEngine.pubnub.setState({ state, channels: [this.chatEngine.global.channel] }, () => {\n // handle status, response\n });\n }\n\n /**\n Search through previously emitted events. Parameters act as AND operators. Returns an instance of the emitter based {@link History}. Will\n which will emit all old events unless ```config.event``` is supplied.\n @param {Object} [config] Our configuration for the PubNub history request. See the [PubNub History](https://www.pubnub.com/docs/web-javascript/storage-and-history) docs for more information on these parameters.\n @param {Event} [config.event] The {@link Event} to search for.\n @param {User} [config.sender] The {@link User} who sent the message.\n @param {Number} [config.limit=20] The maximum number of results to return that match search criteria. Search will continue operating until it returns this number of results or it reached the end of history.\n @param {Number} [config.start=0] The timetoken to begin searching between.\n @param {Number} [config.end=0] The timetoken to end searching between.\n @param {Boolean} [config.reverse=false] Search oldest messages first.\n @return {Search}\n @example\n chat.search({\n event: 'my-custom-event',\n sender: ChatEngine.me,\n limit: 20\n }).on('my-custom-event', (event) => {\n console.log('this is an old event!', event);\n }).on('$.search.finish', () => {\n console.log('we have all our results!')\n });\n */\n search(config) {\n return new Search(this.chatEngine, this, config);\n }\n\n onConnectionReady() {\n\n /**\n * Broadcast that the {@link Chat} is connected to the network.\n * @event Chat#$\".\"connected\n * @example\n * chat.on('$.connected', () => {\n * console.log('chat is ready to go!');\n * });\n */\n this.trigger('$.connected');\n\n this.chatEngine.me.sync.emit('$.session.chat.join', { subject: this.objectify() });\n\n this.connected = true;\n\n // add self to list of users\n this.users[this.chatEngine.me.uuid] = this.chatEngine.me;\n\n // trigger my own online event\n this.trigger('$.online.join', {\n user: this.chatEngine.me\n });\n\n // global channel updates are triggered manually, only get presence on custom chats\n if (this.channel !== this.chatEngine.global.channel && this.group === 'custom') {\n\n this.getUserUpdates();\n\n // we may miss updates, so call this again 5 seconds later\n setTimeout(() => {\n this.getUserUpdates();\n }, 5000);\n\n }\n\n }\n\n getUserUpdates() {\n\n // get a list of users online now\n // ask PubNub for information about connected users in this channel\n this.chatEngine.pubnub.hereNow({\n channels: [this.channel],\n includeUUIDs: true,\n includeState: true\n }, this.onHereNow.bind(this));\n\n }\n\n /**\n * Connect to PubNub servers to initialize the chat.\n * @example\n * // create a new chatroom, but don't connect to it automatically\n * let chat = new Chat('some-chat', false)\n *\n * // connect to the chat when we feel like it\n * chat.connect();\n */\n connect() {\n\n async.waterfall([\n (next) => {\n if (!this.chatEngine.pubnub) {\n next('You must call ChatEngine.connect() and wait for the $.ready event before creating new Chats.');\n } else {\n next();\n }\n },\n (next) => {\n\n this.chatEngine.request('post', 'grant', { chat: this.objectify() })\n .then(() => {\n next();\n })\n .catch(next);\n\n },\n (next) => {\n\n this.chatEngine.request('post', 'join', { chat: this.objectify() })\n .then(() => {\n next();\n })\n .catch(next);\n\n },\n (next) => {\n\n this.chatEngine.request('get', 'chat', {}, { channel: this.channel })\n .then((response) => {\n\n if (response.data.found) {\n this.meta = response.data.chat.meta;\n } else {\n this.update(this.meta);\n }\n\n this.onConnectionReady();\n\n })\n .catch(next);\n\n }\n ], (error) => {\n this.chatEngine.throwError(this, 'trigger', 'auth', new Error('Something went wrong while making a request to authentication server.'), { error });\n });\n\n }\n\n}\n\nmodule.exports = Chat;\n"},{"id":60,"identifier":"/Users/max/Desktop/CLIENT/chat-engine/src/components/search.js","name":"./src/components/search.js","index":52,"index2":83,"size":6596,"cacheable":true,"built":true,"optional":false,"prefetched":false,"chunks":[0],"assets":[],"issuer":"/Users/max/Desktop/CLIENT/chat-engine/src/components/chat.js","issuerId":54,"issuerName":"./src/components/chat.js","profile":{"factory":15,"building":96,"dependencies":0},"failed":false,"errors":0,"warnings":0,"reasons":[{"moduleId":54,"moduleIdentifier":"/Users/max/Desktop/CLIENT/chat-engine/src/components/chat.js","module":"./src/components/chat.js","moduleName":"./src/components/chat.js","type":"cjs require","userRequest":"../components/search","loc":"4:15-46"}],"usedExports":true,"providedExports":null,"optimizationBailout":[],"depth":3,"source":"const Emitter = require('../modules/emitter');\nconst eachSeries = require('async/eachSeries');\n/**\nReturned by {@link Chat#search}. This is our Search class which allows one to search the backlog of messages.\n\n\n Powered by [PubNub History](https://www.pubnub.com/docs/web-javascript/storage-and-history).\n\n @class Search\n @extends Emitter\n @extends RootEmitter\n @param chatEngine\n @param chat\n @param config\n */\nclass Search extends Emitter {\n\n constructor(chatEngine, chat, config = {}) {\n\n super();\n\n this.chatEngine = chatEngine;\n\n /**\n Handy property to identify what this class is.\n @type String\n */\n this.name = 'Search';\n\n /**\n The {@link Chat} used for searching.\n @type Chat\n */\n this.chat = chat;\n\n /**\n An object containing configuration parameters supplied by {@link Chat#search}. See {@link Chat#search} for possible parameters.\n @type {Object}\n */\n this.config = config;\n this.config.event = config.event;\n this.config.limit = config.limit || 20;\n this.config.channel = this.chat.channel;\n this.config.includeTimetoken = true;\n this.config.stringifiedTimeToken = true;\n this.config.count = this.config.count || 100;\n\n this.config.pages = this.config.pages || 10;\n\n this.needleCount = 0;\n\n this.firstTT = 0;\n this.lastTT = 0;\n\n this.firstPage = true;\n\n /**\n * @private\n */\n this.sortHistory = (messages, desc) => {\n\n messages.sort((a, b) => {\n let e1 = desc ? b : a;\n let e2 = desc ? a : b;\n return parseInt(e1.timetoken, 10) - parseInt(e2.timetoken, 10);\n });\n\n return messages;\n\n };\n\n /**\n * Call PubNub history in a loop.\n * Unapologetically stolen from https://www.pubnub.com/docs/web-javascript/storage-and-history\n * @private\n */\n this.page = (pageDone) => {\n\n /**\n * Requesting another page from PubNub History.\n * @event Search#$\".\"page\".\"request\n */\n this._emit('$.search.page.request');\n\n // only set start if this is the first call and the user hasn't set it themselves\n this.config.start = this.config.reverse ? this.lastTT : this.firstTT;\n\n this.firstPage = false;\n\n this.chatEngine.pubnub.history(this.config, (status, response) => {\n\n /**\n * PubNub History returned a response.\n * @event Search#$\".\"page\".\"response\n */\n this._emit('$.search.page.response');\n\n if (status.error) {\n\n /**\n * There was a problem fetching the history of this chat\n * @event Chat#$\".\"error\".\"history\n */\n this.chatEngine.throwError(this, 'trigger', 'search', new Error('There was a problem searching history. Make sure your request parameters are valid and history is enabled for this PubNub key.'), status);\n\n } else {\n\n // timetoken of the first message in response\n this.firstTT = response.startTimeToken;\n // timetoken of the last message in response\n this.lastTT = response.endTimeToken;\n\n response.messages = this.sortHistory(response.messages);\n\n pageDone(response);\n\n }\n\n });\n };\n\n let eventFilter = (event) => {\n return {\n middleware: {\n on: {\n '*': (payload, next) => {\n let matches = payload && payload.event && payload.event === event;\n next(!matches, payload);\n }\n }\n }\n };\n };\n\n let senderFilter = (user) => {\n return {\n middleware: {\n on: {\n '*': (payload, next) => {\n let matches = payload && payload.sender && payload.sender.uuid === user.uuid;\n next(!matches, payload);\n }\n }\n }\n };\n };\n\n this.needleCount = 0;\n\n /**\n * @private\n */\n this.triggerHistory = (message, cb) => {\n\n if (this.needleCount < this.config.limit) {\n\n this.trigger(message.entry.event, message.entry, (reject) => {\n\n if (!reject) {\n this.needleCount += 1;\n }\n cb();\n\n });\n\n } else {\n cb();\n }\n\n };\n\n this.maxPage = 10;\n this.numPage = 0;\n\n this.next = () => {\n\n this.maxPage = this.maxPage + this.config.pages;\n\n this.find();\n\n };\n\n /**\n * @private\n */\n this.find = () => {\n\n this.page((response) => {\n\n if (!this.config.reverse) {\n response.messages.reverse();\n }\n\n eachSeries(response.messages, this.triggerHistory, () => {\n\n if (this.numPage === this.maxPage) {\n this._emit('$.search.pause');\n } else if (\n response.messages &&\n response.messages.length === this.config.count &&\n this.needleCount < this.config.limit) {\n this.numPage += 1;\n this.find();\n } else {\n\n /**\n * Search has returned all results or reached the end of history.\n * @event Search#$\".\"search\".\"finish\n */\n this._emit('$.search.finish');\n }\n\n });\n\n });\n\n return this;\n\n };\n\n if (this.config.event) {\n this.plugin(eventFilter(this.config.event));\n }\n\n if (this.config.sender) {\n this.plugin(senderFilter(this.config.sender));\n }\n\n /**\n * Search has started.\n * @event Search#$\".\"search\".\"start\n */\n this._emit('$.search.start');\n this.find();\n\n }\n\n}\n\nmodule.exports = Search;\n"},{"id":88,"identifier":"/Users/max/Desktop/CLIENT/chat-engine/src/components/me.js","name":"./src/components/me.js","index":87,"index2":86,"size":4890,"cacheable":true,"built":true,"optional":false,"prefetched":false,"chunks":[0],"assets":[],"issuer":"/Users/max/Desktop/CLIENT/chat-engine/src/bootstrap.js","issuerId":31,"issuerName":"./src/bootstrap.js","profile":{"factory":12,"building":15,"dependencies":2},"failed":false,"errors":0,"warnings":0,"reasons":[{"moduleId":31,"moduleIdentifier":"/Users/max/Desktop/CLIENT/chat-engine/src/bootstrap.js","module":"./src/bootstrap.js","moduleName":"./src/bootstrap.js","type":"cjs require","userRequest":"./components/me","loc":"7:11-37"}],"usedExports":true,"providedExports":null,"optimizationBailout":[],"depth":2,"source":"const User = require('./user');\n\n/**\n Represents the client connection as a special {@link User} with write permissions.\n Has the ability to update it's state on the network. An instance of\n {@link Me} is returned by the ```ChatEngine.connect()```\n method.\n\n @class Me\n @extends User\n @extends Emitter\n @extends RootEmitter\n @param {String} uuid The uuid of this user\n */\nclass Me extends User {\n\n constructor(chatEngine, uuid, authData) {\n\n // call the User constructor\n super(chatEngine, uuid);\n\n this.name = 'Me';\n\n this.authData = authData;\n this.chatEngine = chatEngine;\n\n /**\n * Stores a map of {@link Chat} objects that this {@link Me} has joined across all clients.\n * @type {Object}\n */\n this.session = {};\n\n this.sync = new this.chatEngine.Chat([chatEngine.global.channel, 'user', uuid, 'me.', 'sync'].join('#'), false, true, {}, 'system');\n\n this.sync.on('$.session.chat.join', (payload) => {\n this.addChatToSession(payload.data.subject);\n });\n\n this.sync.on('$.session.chat.leave', (payload) => {\n this.removeChatFromSession(payload.data.subject);\n });\n\n return this;\n\n }\n\n // assign updates from network\n assign(state) {\n // we call \"update\" because calling \"super.assign\"\n // will direct back to \"this.update\" which creates\n // a loop of network updates\n super.update(state);\n }\n\n /**\n * Update {@link Me}'s state in a {@link Chat}. All other {@link User}s\n * will be notified of this change via ```$.state```.\n * Retrieve state at any time with {@link User#state}.\n * @param {Object} state The new state for {@link Me}\n * @param {Chat} chat An instance of the {@link Chat} where state will be updated.\n * Defaults to ```ChatEngine.global```.\n * @fires Chat#event:$\".\"state\n * @example\n * // update state\n * me.update({value: true});\n */\n update(state) {\n\n // run the root update function\n super.update(state);\n\n // publish the update over the global channel\n this.chatEngine.global.setState(state);\n\n }\n\n /**\n Stores {@link Chat} within ```ChatEngine.session``` keyed based on the ```chat.group``` property.\n @param {Object} chat JSON object representing {@link Chat}. Originally supplied via {@link Chat#objectify}.\n @private\n */\n addChatToSession(chat) {\n\n // create the chat group if it doesn't exist\n this.session[chat.group] = this.session[chat.group] || {};\n\n // check the chat exists within the global list but is not grouped\n let existingChat = this.chatEngine.chats[chat.channel];\n\n // if it exists\n if (existingChat) {\n // assign it to the group\n this.session[chat.group][chat.channel] = existingChat;\n } else {\n\n // otherwise, try to recreate it with the server information\n this.session[chat.group][chat.channel] = new this.chatEngine.Chat(chat.channel, chat.private, false, chat.meta, chat.group);\n\n /**\n Fired when another identical instance of {@link ChatEngine} and {@link Me} joins a {@link Chat} that this instance of {@link ChatEngine} is unaware of.\n Used to synchronize ChatEngine sessions between desktop and mobile, duplicate windows, etc.\n ChatEngine stores sessions on the server side identified by {@link User#uuid}.\n @event Me#$\".\"session\".\"chat\".\"join\n @example\n *\n * // Logged in as \"Ian\" in first window\n * ChatEngine.me.on('$.session.chat.join', (data) => {\n * console.log('I joined a new chat in a second window!', data.chat);\n * });\n *\n * // Logged in as \"Ian\" in second window\n * new ChatEngine.Chat('another-chat');\n */\n // this.trigger('$.session.chat.join', {\n // chat: this.session[chat.group][chat.channel]\n // });\n //\n this.trigger('$.session.chat.join', { chat: this.session[chat.group][chat.channel] });\n\n }\n\n }\n\n /**\n Removes {@link Chat} within this.session\n @private\n */\n removeChatFromSession(chat) {\n\n if (this.session[chat.group] && this.session[chat.group][chat.channel]) {\n\n chat = this.session[chat.group][chat.channel] || chat;\n\n /**\n * Fired when another identical instance of {@link ChatEngine} with an identical {@link Me} leaves a {@link Chat} via {@link Chat#leave}.\n * @event Me#$\".\"session\".\"chat\".\"leave\n */\n\n delete this.chatEngine.chats[chat.channel];\n delete this.session[chat.group][chat.channel];\n\n this.trigger('$.session.chat.leave', { chat });\n\n }\n\n }\n\n}\n\nmodule.exports = Me;\n"}],"filteredModules":77,"children":[]} \ No newline at end of file +{"errors":[],"warnings":[],"version":"3.8.1","hash":"8b5e0d6b772712becd21","publicPath":"","assetsByChunkName":{"main":"chat-engine.js"},"assets":[{"name":"chat-engine.js","size":459359,"chunks":[0],"chunkNames":["main"],"emitted":true},{"name":"stats.json","size":0,"chunks":[],"chunkNames":[]}],"filteredAssets":0,"entrypoints":{"main":{"chunks":[0],"assets":["chat-engine.js"]}},"chunks":[{"id":0,"rendered":true,"initial":true,"entry":true,"extraAsync":false,"size":449004,"names":["main"],"files":["chat-engine.js"],"hash":"81cd263be429b31d3a16","parents":[],"modules":[{"id":3,"identifier":"/Users/ian/Development/chat-engine/node_modules/webpack/buildin/global.js","name":"(webpack)/buildin/global.js","index":37,"index2":31,"size":488,"cacheable":true,"built":true,"optional":false,"prefetched":false,"chunks":[0],"assets":[],"issuer":"/Users/ian/Development/chat-engine/node_modules/async/dist/async.js","issuerId":15,"issuerName":"./node_modules/async/dist/async.js","profile":{"factory":143,"building":18},"failed":false,"errors":0,"warnings":0,"reasons":[{"moduleId":15,"moduleIdentifier":"/Users/ian/Development/chat-engine/node_modules/async/dist/async.js","module":"./node_modules/async/dist/async.js","moduleName":"./node_modules/async/dist/async.js","type":"cjs require","userRequest":"global","loc":"1:0-44"},{"moduleId":27,"moduleIdentifier":"/Users/ian/Development/chat-engine/node_modules/lodash/_freeGlobal.js","module":"./node_modules/lodash/_freeGlobal.js","moduleName":"./node_modules/lodash/_freeGlobal.js","type":"cjs require","userRequest":"global","loc":"1:0-41"},{"moduleId":55,"moduleIdentifier":"/Users/ian/Development/chat-engine/node_modules/setimmediate/setImmediate.js","module":"./node_modules/setimmediate/setImmediate.js","moduleName":"./node_modules/setimmediate/setImmediate.js","type":"cjs require","userRequest":"global","loc":"1:0-41"}],"usedExports":true,"providedExports":null,"optimizationBailout":[],"depth":3,"source":"var g;\n\n// This works in non-strict mode\ng = (function() {\n\treturn this;\n})();\n\ntry {\n\t// This works if eval is allowed (see CSP)\n\tg = g || Function(\"return this\")() || (1,eval)(\"this\");\n} catch(e) {\n\t// This works if the window reference is available\n\tif(typeof window === \"object\")\n\t\tg = window;\n}\n\n// g can still be undefined, but nothing to do about it...\n// We return undefined, instead of nothing here, so it's\n// easier to handle this case. if(!global) { ...}\n\nmodule.exports = g;\n"},{"id":4,"identifier":"/Users/ian/Development/chat-engine/node_modules/webpack/buildin/module.js","name":"(webpack)/buildin/module.js","index":38,"index2":34,"size":495,"cacheable":true,"built":true,"optional":false,"prefetched":false,"chunks":[0],"assets":[],"issuer":"/Users/ian/Development/chat-engine/node_modules/async/dist/async.js","issuerId":15,"issuerName":"./node_modules/async/dist/async.js","profile":{"factory":143,"building":19},"failed":false,"errors":0,"warnings":0,"reasons":[{"moduleId":15,"moduleIdentifier":"/Users/ian/Development/chat-engine/node_modules/async/dist/async.js","module":"./node_modules/async/dist/async.js","moduleName":"./node_modules/async/dist/async.js","type":"cjs require","userRequest":"module","loc":"1:0-44"},{"moduleId":74,"moduleIdentifier":"/Users/ian/Development/chat-engine/node_modules/lodash/isBuffer.js","module":"./node_modules/lodash/isBuffer.js","moduleName":"./node_modules/lodash/isBuffer.js","type":"cjs require","userRequest":"module","loc":"1:0-41"},{"moduleId":80,"moduleIdentifier":"/Users/ian/Development/chat-engine/node_modules/lodash/_nodeUtil.js","module":"./node_modules/lodash/_nodeUtil.js","moduleName":"./node_modules/lodash/_nodeUtil.js","type":"cjs require","userRequest":"module","loc":"1:0-41"}],"usedExports":true,"providedExports":null,"optimizationBailout":[],"depth":3,"source":"module.exports = function(module) {\n\tif(!module.webpackPolyfill) {\n\t\tmodule.deprecate = function() {};\n\t\tmodule.paths = [];\n\t\t// module.parent = undefined by default\n\t\tif(!module.children) module.children = [];\n\t\tObject.defineProperty(module, \"loaded\", {\n\t\t\tenumerable: true,\n\t\t\tget: function() {\n\t\t\t\treturn module.l;\n\t\t\t}\n\t\t});\n\t\tObject.defineProperty(module, \"id\", {\n\t\t\tenumerable: true,\n\t\t\tget: function() {\n\t\t\t\treturn module.i;\n\t\t\t}\n\t\t});\n\t\tmodule.webpackPolyfill = 1;\n\t}\n\treturn module;\n};\n"},{"id":5,"identifier":"/Users/ian/Development/chat-engine/src/modules/emitter.js","name":"./src/modules/emitter.js","index":39,"index2":48,"size":7500,"cacheable":true,"built":true,"optional":false,"prefetched":false,"chunks":[0],"assets":[],"issuer":"/Users/ian/Development/chat-engine/src/components/user.js","issuerId":29,"issuerName":"./src/components/user.js","profile":{"factory":43,"building":13,"dependencies":4},"failed":false,"errors":0,"warnings":0,"reasons":[{"moduleId":29,"moduleIdentifier":"/Users/ian/Development/chat-engine/src/components/user.js","module":"./src/components/user.js","moduleName":"./src/components/user.js","type":"cjs require","userRequest":"../modules/emitter","loc":"1:16-45"},{"moduleId":54,"moduleIdentifier":"/Users/ian/Development/chat-engine/src/components/chat.js","module":"./src/components/chat.js","moduleName":"./src/components/chat.js","type":"cjs require","userRequest":"../modules/emitter","loc":"2:16-45"},{"moduleId":60,"moduleIdentifier":"/Users/ian/Development/chat-engine/src/components/search.js","module":"./src/components/search.js","moduleName":"./src/components/search.js","type":"cjs require","userRequest":"../modules/emitter","loc":"1:16-45"}],"usedExports":true,"providedExports":null,"optimizationBailout":[],"depth":3,"source":"const waterfall = require('async/waterfall');\nconst RootEmitter = require('./root_emitter');\nconst Event = require('../components/event');\n\n/**\n An ChatEngine generic emitter that supports plugins and forwards\n events to the root emitter.\n @class Emitter\n @extends RootEmitter\n */\nclass Emitter extends RootEmitter {\n\n constructor(chatEngine) {\n\n super();\n\n this.chatEngine = chatEngine;\n\n this.name = 'Emitter';\n\n /**\n Stores a list of plugins bound to this object\n @private\n */\n this.plugins = [];\n\n /**\n Stores in memory keys and values\n @private\n */\n this._dataset = {};\n\n /**\n Emit events locally.\n\n @private\n @param {String} event The event payload object\n */\n this._emit = (event, data = {}) => {\n\n // all events are forwarded to ChatEngine object\n // so you can globally bind to events with ChatEngine.on()\n this.chatEngine._emit(event, data, this);\n\n // emit the event from the object that created it\n this.emitter.emit(event, data);\n\n return this;\n\n };\n\n /**\n * Listen for a specific event and fire a callback when it's emitted. Supports wildcard matching.\n * @method\n * @param {String} event The event name\n * @param {Function} cb The function to run when the event is emitted\n * @example\n *\n * // Get notified whenever someone joins the room\n * object.on('event', (payload) => {\n * console.log('event was fired').\n * })\n *\n * // Get notified of event.a and event.b\n * object.on('event.*', (payload) => {\n * console.log('event.a or event.b was fired').;\n * })\n */\n this.on = (event, cb) => {\n\n // keep track of all events on this emitter\n this.events[event] = this.events[event] || new Event(this.chatEngine, this, event);\n\n // call the private _on property\n this._on(event, cb);\n\n return this;\n\n };\n\n }\n\n // add an object as a subobject under a namespoace\n addChild(childName, childOb) {\n // assign the new child object as a property of parent under the\n // given namespace\n this[childName] = childOb;\n\n // assign a data set for the namespace if it doesn't exist\n if (!this._dataset[childName]) {\n this._dataset[childName] = {};\n }\n\n // the new object can use ```this.parent``` to access\n // the root class\n childOb.parent = this;\n\n // bind get() and set() to the data set\n childOb.get = this.get.bind(this._dataset[childName]);\n childOb.set = this.set.bind(this._dataset[childName]);\n }\n\n get(key) {\n return this[key];\n }\n\n set(key, value) {\n if (this[key] && !value) {\n delete this[key];\n } else {\n this[key] = value;\n }\n }\n\n /**\n Binds a plugin to this object\n @param {Object} module The plugin module\n @tutorial using\n */\n plugin(module) {\n\n // add this plugin to a list of plugins for this object\n this.plugins.push(module);\n\n // see if there are plugins to attach to this class\n if (module.extends && module.extends[this.name]) {\n // attach the plugins to this class\n // under their namespace\n this.addChild(module.namespace, new module.extends[this.name]());\n\n this[module.namespace].ChatEngine = this.chatEngine;\n\n // if the plugin has a special construct function\n // run it\n if (this[module.namespace].construct) {\n this[module.namespace].construct();\n }\n\n }\n\n return this;\n\n }\n\n bindProtoPlugins() {\n\n if (this.chatEngine.protoPlugins[this.name]) {\n\n this.chatEngine.protoPlugins[this.name].forEach((module) => {\n this.plugin(module);\n });\n\n }\n\n }\n\n /**\n Broadcasts an event locally to all listeners.\n @private\n @param {String} event The event name\n @param {Object} payload The event payload object\n */\n trigger(event, payload = {}, done = () => {}) {\n\n let complete = () => {\n\n // let plugins modify the event\n this.runPluginQueue('on', event, (next) => {\n next(null, payload);\n }, (reject, pluginResponse) => {\n\n if (reject) {\n done(reject);\n } else {\n // emit this event to any listener\n this._emit(event, pluginResponse);\n done(null, event, pluginResponse);\n }\n\n });\n\n };\n\n // this can be made into plugin\n if (typeof payload === 'object') {\n\n // restore chat in payload\n if (!payload.chat) {\n payload.chat = this;\n }\n\n // if we should try to restore the sender property\n if (payload.sender) {\n\n // the user doesn't exist, create it\n payload.sender = new this.chatEngine.User(payload.sender);\n\n payload.sender._getState(() => {\n complete();\n });\n\n } else {\n // there's no \"sender\" in this object, move on\n complete();\n }\n\n } else {\n // payload is not an object, we want nothing to do with it.\n complete();\n }\n }\n\n /**\n Load plugins and attach a queue of functions to execute before and\n after events are trigger or received.\n\n @private\n @param {String} location Where in the middleeware the event should run (emit, trigger)\n @param {String} event The event name\n @param {String} first The first function to run before the plugins have run\n @param {String} last The last function to run after the plugins have run\n */\n runPluginQueue(location, event, first, last) {\n\n // this assembles a queue of functions to run as middleware\n // event is a triggered event key\n let pluginQueue = [];\n\n // the first function is always required\n pluginQueue.push(first);\n\n // look through the configured plugins\n this.plugins.forEach((pluginItem) => {\n\n // if they have defined a function to run specifically\n // for this event\n if (pluginItem.middleware && pluginItem.middleware[location]) {\n\n if (pluginItem.middleware[location][event]) {\n // add the function to the queue\n pluginQueue.push(pluginItem.middleware[location][event]);\n }\n\n if (pluginItem.middleware[location]['*']) {\n // add the function to the queue\n pluginQueue.push(pluginItem.middleware[location]['*']);\n }\n\n }\n\n });\n\n // waterfall runs the functions in assigned order\n // waiting for one to complete before moving to the next\n // when it's done, the ```last``` parameter is called\n waterfall(pluginQueue, last);\n\n }\n\n onConstructed() {\n\n this.bindProtoPlugins();\n this.trigger(['$', 'created', this.name.toLowerCase()].join('.'));\n\n }\n\n}\n\nmodule.exports = Emitter;\n"},{"id":14,"identifier":"/Users/ian/Development/chat-engine/src/modules/root_emitter.js","name":"./src/modules/root_emitter.js","index":31,"index2":30,"size":4109,"cacheable":true,"built":true,"optional":false,"prefetched":false,"chunks":[0],"assets":[],"issuer":"/Users/ian/Development/chat-engine/src/bootstrap.js","issuerId":31,"issuerName":"./src/bootstrap.js","profile":{"factory":15,"building":15},"failed":false,"errors":0,"warnings":0,"reasons":[{"moduleId":5,"moduleIdentifier":"/Users/ian/Development/chat-engine/src/modules/emitter.js","module":"./src/modules/emitter.js","moduleName":"./src/modules/emitter.js","type":"cjs require","userRequest":"./root_emitter","loc":"2:20-45"},{"moduleId":31,"moduleIdentifier":"/Users/ian/Development/chat-engine/src/bootstrap.js","module":"./src/bootstrap.js","moduleName":"./src/bootstrap.js","type":"cjs require","userRequest":"./modules/root_emitter","loc":"5:20-53"}],"usedExports":true,"providedExports":null,"optimizationBailout":[],"depth":2,"source":"\n// Allows us to create and bind to events. Everything in ChatEngine is an event\n// emitter\nconst EventEmitter2 = require('eventemitter2').EventEmitter2;\n\n/**\n* The {@link ChatEngine} object is a RootEmitter. Configures an event emitter that other ChatEngine objects inherit. Adds shortcut methods for\n* ```this.on()```, ```this.emit()```, etc.\n* @class RootEmitter\n*/\nclass RootEmitter {\n\n constructor() {\n\n /**\n * @private\n */\n this.events = {};\n\n this.name = 'RootEmitter';\n\n /**\n Create a new EventEmitter2 object for this class.\n\n @private\n */\n this.emitter = new EventEmitter2({\n wildcard: true,\n newListener: true,\n maxListeners: 50,\n verboseMemoryLeak: true\n });\n\n // we bind to make sure wildcards work\n // https://github.com/asyncly/EventEmitter2/issues/186\n\n /**\n Private emit method that broadcasts the event to listeners on this page.\n\n @private\n @param {String} event The event name\n @param {Object} the event payload\n */\n this._emit = this.emitter.emit.bind(this.emitter);\n\n /**\n Listen for a specific event and fire a callback when it's emitted. This is reserved in case ```this.on``` is overwritten.\n\n @private\n @param {String} event The event name\n @param {Function} callback The function to run when the event is emitted\n */\n\n this._on = this.emitter.on.bind(this.emitter);\n\n /**\n * Listen for a specific event and fire a callback when it's emitted. Supports wildcard matching.\n * @method\n * @param {String} event The event name\n * @param {Function} cb The function to run when the event is emitted\n * @example\n *\n * // Get notified whenever someone joins the room\n * object.on('event', (payload) => {\n * console.log('event was fired').\n * })\n *\n * // Get notified of event.a and event.b\n * object.on('event.*', (payload) => {\n * console.log('event.a or event.b was fired').;\n * })\n */\n this.on = (event, callback) => {\n\n // emit the event from the object that created it\n this.emitter.on(event, callback);\n\n return this;\n\n };\n\n /**\n * Stop a callback from listening to an event.\n * @method\n * @param {String} event The event name\n * @example\n * let callback = function(payload;) {\n * console.log('something happend!');\n * };\n * object.on('event', callback);\n * // ...\n * object.off('event', callback);\n */\n this.off = (event, callback) => {\n\n // emit the event from the object that created it\n this.emitter.off(event, callback);\n\n return this;\n\n };\n\n /**\n * Listen for any event on this object and fire a callback when it's emitted\n * @method\n * @param {Function} callback The function to run when any event is emitted. First parameter is the event name and second is the payload.\n * @example\n * object.onAny((event, payload) => {\n * console.log('All events trigger this.');\n * });\n */\n this.onAny = (event, callback) => {\n\n // emit the event from the object that created it\n this.emitter.onAny(event, callback);\n\n return this;\n\n };\n\n /**\n * Listen for an event and only fire the callback a single time\n * @method\n * @param {String} event The event name\n * @param {Function} callback The function to run once\n * @example\n * object.once('message', => (event, payload) {\n * console.log('This is only fired once!');\n * });\n */\n this.once = (event, callback) => {\n\n // emit the event from the object that created it\n this.emitter.once(event, callback);\n\n return this;\n\n };\n\n }\n\n}\n\nmodule.exports = RootEmitter;\n"},{"id":23,"identifier":"/Users/ian/Development/chat-engine/src/components/event.js","name":"./src/components/event.js","index":51,"index2":47,"size":2220,"cacheable":true,"built":true,"optional":false,"prefetched":false,"chunks":[0],"assets":[],"issuer":"/Users/ian/Development/chat-engine/src/components/chat.js","issuerId":54,"issuerName":"./src/components/chat.js","profile":{"factory":16,"building":23},"failed":false,"errors":0,"warnings":0,"reasons":[{"moduleId":5,"moduleIdentifier":"/Users/ian/Development/chat-engine/src/modules/emitter.js","module":"./src/modules/emitter.js","moduleName":"./src/modules/emitter.js","type":"cjs require","userRequest":"../components/event","loc":"3:14-44"},{"moduleId":54,"moduleIdentifier":"/Users/ian/Development/chat-engine/src/components/chat.js","module":"./src/components/chat.js","moduleName":"./src/components/chat.js","type":"cjs require","userRequest":"../components/event","loc":"3:14-44"}],"usedExports":true,"providedExports":null,"optimizationBailout":[],"depth":3,"source":"/**\n * @class Event\n * Represents an event that may be emitted or subscribed to.\n */\nclass Event {\n\n constructor(chatEngine, chat, event) {\n\n /**\n Events are always a property of a {@link Chat}. Responsible for\n listening to specific events and firing events when they occur.\n @readonly\n @type String\n @see [PubNub Channels](https://support.pubnub.com/support/solutions/articles/14000045182-what-is-a-channel-)\n */\n this.channel = chat.channel;\n\n this.chatEngine = chatEngine;\n\n this.chat = chat;\n\n this.event = event;\n\n this.name = 'Event';\n\n /**\n Forwards events to the Chat that registered the event {@link Chat}\n\n @private\n @param {Object} data The event payload object\n */\n\n // call onMessage when PubNub receives an event\n this.chatEngine.pubnub.addListener({\n message: this.onMessage.bind(this)\n });\n\n return this;\n\n }\n\n onMessage(m) {\n\n if (this.channel === m.channel && m.message.event === this.event) {\n this.chat.trigger(m.message.event, m.message);\n }\n\n }\n\n /**\n Publishes the event over the PubNub network to the {@link Event} channel\n\n @private\n @param {Object} data The event payload object\n */\n publish(m) {\n\n m.event = this.event;\n\n this.chatEngine.pubnub.publish({\n message: m,\n channel: this.channel\n }, (status) => {\n\n if (status.statusCode === 200) {\n\n /**\n * Message successfully published\n * @event Chat#$\".\"publish\".\"success\n * @param {Object} data The message object\n */\n this.chat.trigger('$.publish.success', m);\n } else {\n\n /**\n * There was a problem publishing over the PubNub network.\n * @event Chat#$\".\"error\".\"publish\n */\n this.chatEngine.throwError(this.chat, 'trigger', 'publish', new Error('There was a problem publishing over the PubNub network.'), status);\n }\n\n });\n\n }\n\n}\n\nmodule.exports = Event;\n"},{"id":29,"identifier":"/Users/ian/Development/chat-engine/src/components/user.js","name":"./src/components/user.js","index":88,"index2":85,"size":5484,"cacheable":true,"built":true,"optional":false,"prefetched":false,"chunks":[0],"assets":[],"issuer":"/Users/ian/Development/chat-engine/src/bootstrap.js","issuerId":31,"issuerName":"./src/bootstrap.js","profile":{"factory":15,"building":26},"failed":false,"errors":0,"warnings":0,"reasons":[{"moduleId":31,"moduleIdentifier":"/Users/ian/Development/chat-engine/src/bootstrap.js","module":"./src/bootstrap.js","moduleName":"./src/bootstrap.js","type":"cjs require","userRequest":"./components/user","loc":"8:13-41"},{"moduleId":88,"moduleIdentifier":"/Users/ian/Development/chat-engine/src/components/me.js","module":"./src/components/me.js","moduleName":"./src/components/me.js","type":"cjs require","userRequest":"./user","loc":"1:13-30"}],"usedExports":true,"providedExports":null,"optimizationBailout":[],"depth":2,"source":"const Emitter = require('../modules/emitter');\n\n/**\n This is our User class which represents a connected client. User's are automatically created and managed by {@link Chat}s, but you can also instantiate them yourself.\n If a User has been created but has never been authenticated, you will recieve 403s when connecting to their feed or direct Chats.\n @class User\n @extends Emitter\n @extends RootEmitter\n @param uuid\n @param state\n */\nclass User extends Emitter {\n\n constructor(chatEngine, uuid, state = {}) {\n\n super();\n\n this.chatEngine = chatEngine;\n\n this.name = 'User';\n\n /**\n The User's unique identifier, usually a device uuid. This helps ChatEngine identify the user between events. This is public id exposed to the network.\n Check out [the wikipedia page on UUIDs](https://en.wikipedia.org/wiki/Universally_unique_identifier).\n\n @readonly\n @type String\n */\n this.uuid = uuid;\n\n /**\n * Gets the user state. See {@link Me#update} for how to assign state values.\n * @return {Object} Returns a generic JSON object containing state information.\n * @example\n *\n * // State\n * let state = user.state;\n */\n this.state = {};\n\n this._stateFetched = false;\n\n /**\n * Feed is a Chat that only streams things a User does, like\n * 'startTyping' or 'idle' events for example. Anybody can subscribe\n * to a User's feed, but only the User can publish to it. Users will\n * not be able to converse in this channel.\n *\n * @type Chat\n * @example\n * // me\n * me.feed.emit('update', 'I may be away from my computer right now');\n *\n * // another instance\n * them.feed.connect();\n * them.feed.on('update', (payload) => {})\n */\n\n // grants for these chats are done on auth. Even though they're marked private, they are locked down via the server\n this.feed = new this.chatEngine.Chat([chatEngine.global.channel, 'user', uuid, 'read.', 'feed'].join('#'), false, this.constructor.name === 'Me', {}, 'system');\n\n /**\n * Direct is a private channel that anybody can publish to but only\n * the user can subscribe to. Great for pushing notifications or\n * inviting to other chats. Users will not be able to communicate\n * with one another inside of this chat. Check out the\n * {@link Chat#invite} method for private chats utilizing\n * {@link User#direct}.\n *\n * @type Chat\n * @example\n * // me\n * me.direct.on('private-message', (payload) -> {\n * console.log(payload.sender.uuid, 'sent your a direct message');\n * });\n *\n * // another instance\n * them.direct.connect();\n * them.direct.emit('private-message', {secret: 42});\n */\n this.direct = new this.chatEngine.Chat([chatEngine.global.channel, 'user', uuid, 'write.', 'direct'].join('#'), false, this.constructor.name === 'Me', {}, 'system');\n\n // if the user does not exist at all and we get enough\n // information to build the user\n if (!chatEngine.users[uuid]) {\n chatEngine.users[uuid] = this;\n }\n\n // update this user's state in it's created context\n this.assign(state);\n\n return this;\n\n }\n\n /**\n * @private\n * @param {Object} state The new state for the user\n * @param {Chat} chat Chatroom to retrieve state from\n */\n update(state) {\n let oldState = this.state || {};\n this.state = Object.assign(oldState, state);\n }\n\n /**\n this is only called from network updates\n\n @private\n */\n assign(state) {\n this.update(state);\n }\n\n /**\n Get stored user state from remote server.\n @private\n */\n _getState(callback) {\n\n if (!this._stateFetched) {\n\n this.chatEngine.pubnub.getState({\n uuid: this.uuid,\n channels: [this.chatEngine.global.channel]\n }, (status, response) => {\n\n if (status.statusCode === 200) {\n\n let pnState = response.channels[this.chatEngine.global.channel];\n if (Object.keys(pnState).length) {\n\n this.assign(response.data);\n\n this._stateFetched = true;\n callback(this.state);\n\n } else {\n\n this.chatEngine.request('get', 'user_state', {\n user: this.uuid\n })\n .then((res) => {\n\n this.assign(res.data);\n\n this._stateFetched = true;\n callback(this.state);\n\n })\n .catch((err) => {\n // console.log('this is hte err', err);\n this.chatEngine.throwError(this, 'trigger', 'getState', err);\n });\n\n }\n\n } else {\n this.chatEngine.throwError(this, 'trigger', 'getState', new Error('There was a problem getting state from the PubNub network.'));\n }\n\n });\n\n } else {\n callback(this.state);\n }\n\n }\n\n}\n\nmodule.exports = User;\n"},{"id":30,"identifier":"/Users/ian/Development/chat-engine/src/index.js","name":"./src/index.js","index":0,"index2":88,"size":1425,"cacheable":true,"built":true,"optional":false,"prefetched":false,"chunks":[0],"assets":[],"issuer":null,"issuerId":null,"issuerName":null,"profile":{"factory":25,"building":20},"failed":false,"errors":0,"warnings":0,"reasons":[],"usedExports":true,"providedExports":null,"optimizationBailout":[],"depth":0,"source":"// allows asynchronous execution flow.\nconst init = require('./bootstrap');\n\n/**\nGlobal object used to create an instance of {@link ChatEngine}.\n\n@alias ChatEngineCore\n@param pnConfig {Object} ChatEngine is based off PubNub. Supply your PubNub configuration parameters here. See the getting started tutorial and [the PubNub docs](https://www.pubnub.com/docs/java-se-java/api-reference-configuration).\n@param ceConfig {Object} A list of chat engine specific config options.\n@param [ceConfig.globalChannel=chat-engine] {String} The root channel. See {@link ChatEngine.global}\n@param [ceConfig.throwErrors=true] {Boolean} Throws errors in JS console.\n@param [ceConfig.endpoint] {String} The root URL used to manage permissions for private channels.\n@return {ChatEngine} Returns an instance of {@link ChatEngine}\n@example\nChatEngine = ChatEngineCore.create({\n publishKey: 'demo',\n subscribeKey: 'demo'\n});\n*/\n\nconst create = (pnConfig, ceConfig = {}) => {\n\n if (ceConfig.globalChannel) {\n ceConfig.globalChannel = ceConfig.globalChannel.toString();\n } else {\n ceConfig.globalChannel = 'chat-engine';\n }\n\n if (typeof ceConfig.throwErrors === 'undefined') {\n ceConfig.throwErrors = true;\n }\n\n // return an instance of ChatEngine\n return init(ceConfig, pnConfig);\n\n};\n\n// export the ChatEngine api\nmodule.exports = {\n plugin: {}, // leave a spot for plugins to exist\n create\n};\n"},{"id":31,"identifier":"/Users/ian/Development/chat-engine/src/bootstrap.js","name":"./src/bootstrap.js","index":1,"index2":87,"size":16020,"cacheable":true,"built":true,"optional":false,"prefetched":false,"chunks":[0],"assets":[],"issuer":"/Users/ian/Development/chat-engine/src/index.js","issuerId":30,"issuerName":"./src/index.js","profile":{"factory":10,"building":37},"failed":false,"errors":0,"warnings":0,"reasons":[{"moduleId":30,"moduleIdentifier":"/Users/ian/Development/chat-engine/src/index.js","module":"./src/index.js","moduleName":"./src/index.js","type":"cjs require","userRequest":"./bootstrap","loc":"2:13-35"}],"usedExports":true,"providedExports":null,"optimizationBailout":[],"depth":1,"source":"const axios = require('axios');\nconst PubNub = require('pubnub');\nconst pack = require('../package.json');\n\nconst RootEmitter = require('./modules/root_emitter');\nconst Chat = require('./components/chat');\nconst Me = require('./components/me');\nconst User = require('./components/user');\nconst async = require('async');\n\n/**\n @class ChatEngine\n @extends RootEmitter\n @return {ChatEngine} Returns an instance of {@link ChatEngine}\n */\nmodule.exports = (ceConfig = {}, pnConfig = {}) => {\n\n // Create the root ChatEngine object\n let ChatEngine = new RootEmitter();\n\n ChatEngine.ceConfig = ceConfig;\n ChatEngine.pnConfig = pnConfig;\n\n ChatEngine.pnConfig.heartbeatInterval = ChatEngine.pnConfig.heartbeatInterval || 30;\n ChatEngine.pnConfig.presenceTimeout = ChatEngine.pnConfig.presenceTimeout || 60;\n\n ChatEngine.ceConfig.endpoint = ChatEngine.ceConfig.endpoint || 'https://pubsub.pubnub.com/v1/blocks/sub-key/' + ChatEngine.pnConfig.subscribeKey + '/chat-engine-server';\n ChatEngine.ceConfig.globalChannel = ChatEngine.ceConfig.globalChannel || 'chat-engine-global';\n\n /**\n * A map of all known {@link User}s in this instance of ChatEngine.\n * @type {Object}\n * @memberof ChatEngine\n */\n ChatEngine.users = {};\n\n /**\n * A map of all known {@link Chat}s in this instance of ChatEngine.\n * @memberof ChatEngine\n * @type {Object}\n */\n ChatEngine.chats = {};\n\n /**\n * A global {@link Chat} that all {@link User}s join when they connect to ChatEngine. Useful for announcements, alerts, and global events.\n * @member {Chat} global\n * @memberof ChatEngine\n */\n ChatEngine.global = false;\n\n /**\n * This instance of ChatEngine represented as a special {@link User} know as {@link Me}.\n * @member {Me} me\n * @memberof ChatEngine\n */\n ChatEngine.me = false;\n\n /**\n * An instance of PubNub, the networking infrastructure that powers the realtime communication between {@link User}s in {@link Chats}.\n * @member {Object} pubnub\n * @memberof ChatEngine\n */\n ChatEngine.pubnub = false;\n\n /**\n * Indicates if ChatEngine has fired the {@link ChatEngine#$\".\"ready} event.\n * @member {Object} ready\n * @memberof ChatEngine\n */\n ChatEngine.ready = false;\n\n /**\n * The package.json for ChatEngine. Used mainly for detecting package version.\n * @type {Object}\n */\n ChatEngine.package = pack;\n\n ChatEngine.throwError = (self, cb, key, ceError, payload = {}) => {\n\n if (ceConfig.throwErrors) {\n // throw ceError;\n console.error(payload);\n throw ceError;\n }\n\n payload.ceError = ceError.toString();\n\n self[cb](['$', 'error', key].join('.'), payload);\n\n };\n\n if (ceConfig.debug) {\n ChatEngine.onAny((event, payload) => {\n console.info('debug:', event, payload);\n });\n }\n\n ChatEngine.protoPlugins = {};\n\n /**\n * Bind a plugin to all future instances of a Class.\n * @method ChatEngine#proto\n * @param {String} className The string representation of a class to bind to\n * @param {Class} plugin The plugin function.\n */\n ChatEngine.proto = (className, plugin) => {\n ChatEngine.protoPlugins[className] = ChatEngine.protoPlugins[className] || [];\n ChatEngine.protoPlugins[className].push(plugin);\n };\n\n ChatEngine.request = (method, route, inputBody = {}, inputParams = {}) => {\n\n let body = {\n uuid: pnConfig.uuid,\n global: ceConfig.globalChannel,\n authData: ChatEngine.me.authData,\n authKey: pnConfig.authKey\n };\n\n let params = {\n route\n };\n\n body = Object.assign(body, inputBody);\n params = Object.assign(params, inputParams);\n\n if (method === 'get' || method === 'delete') {\n params = Object.assign(params, body);\n return axios[method](ceConfig.endpoint, { params });\n } else {\n return axios[method](ceConfig.endpoint, body, { params });\n }\n\n\n };\n\n ChatEngine.parseChannel = (channel) => {\n\n let info = channel.split('#');\n\n return {\n global: info[0],\n type: info[1],\n private: info[2] === 'private.'\n };\n\n };\n\n /**\n * Get the internal channel name of supplied string\n * @private\n * @param {[type]} original [description]\n * @param {Boolean} isPrivate [description]\n * @return {[type]} [description]\n */\n ChatEngine.augmentChannel = (original = new Date().getTime(), isPrivate = true) => {\n\n let channel = original.toString();\n\n // public.* has PubNub permissions for everyone to read and write\n // private.* is totally locked down and users must be granted access one by one\n let chanPrivString = 'public.';\n\n if (isPrivate) {\n chanPrivString = 'private.';\n }\n\n if (channel.indexOf(ChatEngine.ceConfig.globalChannel) === -1) {\n channel = [ChatEngine.ceConfig.globalChannel, 'chat', chanPrivString, channel].join('#');\n }\n\n return channel;\n\n };\n\n /**\n * Connect to realtime service and create instance of {@link Me}\n * @method ChatEngine#connect\n * @param {String} uuid A unique string for {@link Me}. It can be a device id, username, user id, email, etc.\n * @param {Object} state An object containing information about this client ({@link Me}). This JSON object is sent to all other clients on the network, so no passwords!\n * @param {String} [authKey] A authentication secret. Will be sent to authentication backend for validation. This is usually an access token or password. This is different from UUID as a user can have a single UUID but multiple auth keys.\n * @param {Object} [authData] Additional data to send to the authentication endpoint to help verify a valid session. ChatEngine SDK does not make use of this, but you might!\n * @fires $\".\"connected\n */\n ChatEngine.connect = (uuid, state = {}, authKey = false, authData) => {\n\n // this creates a user known as Me and\n // connects to the global chatroom\n\n pnConfig.uuid = uuid;\n\n pnConfig.authKey = authKey || pnConfig.uuid;\n\n let restoreSession = () => {\n\n let groups = ['custom', 'rooms', 'system'];\n\n groups.forEach((group) => {\n\n let channelGroup = [ceConfig.globalChannel, pnConfig.uuid, group].join('#');\n\n ChatEngine.pubnub.channelGroups.listChannels({\n channelGroup\n }, (status, response) => {\n\n if (status.error) {\n console.log('operation failed w/ error:', status);\n return;\n }\n\n response.channels.forEach((channel) => {\n\n ChatEngine.me.addChatToSession({\n channel,\n private: ChatEngine.parseChannel(channel).private,\n group\n });\n\n });\n\n });\n\n });\n\n };\n\n let complete = () => {\n\n ChatEngine.pubnub = new PubNub(pnConfig);\n\n // create a new chat to use as global chat\n // we don't do auth on this one because it's assumed to be done with the /auth request below\n ChatEngine.global = new ChatEngine.Chat(ceConfig.globalChannel, false, true, {}, 'system');\n\n // build the current user\n ChatEngine.me = new Me(ChatEngine, pnConfig.uuid, authData);\n ChatEngine.me.update(state);\n\n /**\n * Fired when a {@link Me} has been created within ChatEngine.\n * @event ChatEngine#$\".\"created\".\"me\n * @example\n * ChatEngine.on('$.created.me', (data, me) => {\n * console.log('Me was created', me);\n * });\n */\n ChatEngine.me.onConstructed();\n\n ChatEngine.global.on('$.connected', () => {\n\n /**\n * Fired when ChatEngine is connected to the internet and ready to go!\n * @event ChatEngine#$\".\"ready\n * @example\n * ChatEngine.on('$.ready', (data) => {\n * let me = data.me;\n * })\n */\n ChatEngine._emit('$.ready', {\n me: ChatEngine.me\n });\n\n ChatEngine.global.getUserUpdates();\n\n let chanGroups = [\n ceConfig.globalChannel + '#' + ChatEngine.me.uuid + '#rooms',\n ceConfig.globalChannel + '#' + ChatEngine.me.uuid + '#system',\n ceConfig.globalChannel + '#' + ChatEngine.me.uuid + '#custom'\n ];\n\n // listen to all PubNub events for this Chat\n ChatEngine.pubnub.addListener({\n presence: (payload) => {\n\n if (ChatEngine.chats[payload.channel]) {\n ChatEngine.chats[payload.channel].onPresence(payload);\n }\n\n }\n });\n\n ChatEngine.pubnub.subscribe({\n channelGroups: chanGroups,\n withPresence: true\n });\n\n ChatEngine.ready = true;\n\n restoreSession();\n\n });\n\n /**\n Fires when PubNub network connection changes.\n\n @private\n @param {Object} statusEvent The response status\n */\n ChatEngine.pubnub.addListener({\n status: (statusEvent) => {\n\n /**\n * SDK detected that network is online.\n * @event ChatEngine#$\".\"network\".\"up\".\"online\n */\n\n /**\n * SDK detected that network is down.\n * @event ChatEngine#$\".\"network\".\"down\".\"offline\n */\n\n /**\n * A subscribe event experienced an exception when running.\n * @event ChatEngine#$\".\"network\".\"down\".\"issue\n */\n\n /**\n * SDK was able to reconnect to pubnub.\n * @event ChatEngine#$\".\"network\".\"up\".\"reconnected\n */\n\n /**\n * SDK subscribed with a new mix of channels.\n * @event ChatEngine#$\".\"network\".\"up\".\"connected\n */\n\n /**\n * JSON parsing crashed.\n * @event ChatEngine#$\".\"network\".\"down\".\"malformed\n */\n\n /**\n * Server rejected the request.\n * @event ChatEngine#$\".\"network\".\"down\".\"badrequest\n */\n\n /**\n * If using decryption strategies and the decryption fails.\n * @event ChatEngine#$\".\"network\".\"down\".\"decryption\n */\n\n /**\n * Request timed out.\n * @event ChatEngine#$\".\"network\".\"down\".\"timeout\n */\n\n /**\n * PAM permission failure.\n * @event ChatEngine#$\".\"network\".\"down\".\"denied\n */\n\n // map the pubnub events into chat engine events\n let categories = {\n PNNetworkUpCategory: 'up.online',\n PNNetworkDownCategory: 'down.offline',\n PNNetworkIssuesCategory: 'down.issue',\n PNReconnectedCategory: 'up.reconnected',\n PNConnectedCategory: 'up.connected',\n PNAccessDeniedCategory: 'down.denied',\n PNMalformedResponseCategory: 'down.malformed',\n PNBadRequestCategory: 'down.badrequest',\n PNDecryptionErrorCategory: 'down.decryption',\n PNTimeoutCategory: 'down.timeout'\n };\n\n let eventName = ['$', 'network', categories[statusEvent.category] || 'other'].join('.');\n\n if (statusEvent.affectedChannels) {\n statusEvent.affectedChannels.forEach((channel) => {\n\n let chat = ChatEngine.chats[channel];\n\n if (chat) {\n // connected category tells us the chat is ready\n if (statusEvent.category === 'PNConnectedCategory') {\n chat.onConnectionReady();\n }\n\n // trigger the network events\n chat.trigger(eventName, statusEvent);\n\n } else {\n ChatEngine._emit(eventName, statusEvent);\n }\n });\n } else {\n ChatEngine._emit(eventName, statusEvent);\n }\n }\n });\n };\n\n async.parallel([\n (next) => {\n ChatEngine.request('post', 'bootstrap').then(() => {\n next(null);\n }).catch(next);\n },\n (next) => {\n ChatEngine.request('post', 'user_read').then(() => {\n next(null);\n }).catch(next);\n },\n (next) => {\n ChatEngine.request('post', 'user_write').then(() => {\n next(null);\n }).catch(next);\n },\n (next) => {\n ChatEngine.request('post', 'group').then(complete).catch(next);\n }\n ], (error) => {\n if (error) {\n ChatEngine.throwError(ChatEngine, '_emit', 'auth', new Error('There was a problem logging into the auth server (' + ceConfig.endpoint + ').'), { error });\n }\n });\n\n };\n\n /**\n * The {@link Chat} class.\n * @member {Chat} Chat\n * @memberof ChatEngine\n * @see {@link Chat}\n */\n ChatEngine.Chat = function (...args) {\n\n let internalChannel = ChatEngine.augmentChannel(args[0], args[1]);\n\n if (ChatEngine.chats[internalChannel]) {\n return ChatEngine.chats[internalChannel];\n } else {\n\n let newChat = new Chat(ChatEngine, ...args);\n\n /**\n * Fired when a {@link Chat} has been created within ChatEngine.\n * @event ChatEngine#$\".\"created\".\"chat\n * @example\n * ChatEngine.on('$.created.chat', (data, chat) => {\n * console.log('Chat was created', chat);\n * });\n */\n newChat.onConstructed();\n\n return newChat;\n\n }\n\n };\n\n /**\n * The {@link User} class.\n * @member {User} User\n * @memberof ChatEngine\n * @see {@link User}\n */\n ChatEngine.User = function (...args) {\n\n if (ChatEngine.me.uuid === args[0]) {\n return ChatEngine.me;\n } else if (ChatEngine.users[args[0]]) {\n return ChatEngine.users[args[0]];\n } else {\n\n let newUser = new User(ChatEngine, ...args);\n\n /**\n * Fired when a {@link User} has been created within ChatEngine.\n * @event ChatEngine#$\".\"created\".\"user\n * @example\n * ChatEngine.on('$.created.user', (data, user) => {\n * console.log('Chat was created', user);\n * });\n */\n newUser.onConstructed();\n\n return newUser;\n\n }\n\n };\n\n return ChatEngine;\n\n};\n"},{"id":52,"identifier":"/Users/ian/Development/chat-engine/node_modules/json-loader/index.js!/Users/ian/Development/chat-engine/package.json","name":"./package.json","index":30,"index2":28,"size":1344,"cacheable":true,"built":true,"optional":false,"prefetched":false,"chunks":[0],"assets":[],"issuer":"/Users/ian/Development/chat-engine/src/bootstrap.js","issuerId":31,"issuerName":"./src/bootstrap.js","profile":{"factory":87,"building":4},"failed":false,"errors":0,"warnings":0,"reasons":[{"moduleId":31,"moduleIdentifier":"/Users/ian/Development/chat-engine/src/bootstrap.js","module":"./src/bootstrap.js","moduleName":"./src/bootstrap.js","type":"cjs require","userRequest":"../package.json","loc":"3:13-39"}],"usedExports":true,"providedExports":null,"optimizationBailout":[],"depth":2,"source":"module.exports = {\"author\":\"PubNub\",\"name\":\"chat-engine\",\"version\":\"0.8.4\",\"description\":\"ChatEngine\",\"main\":\"src/index.js\",\"scripts\":{\"deploy\":\"gulp; npm publish;\",\"docs\":\"jsdoc src/index.js -c jsdoc.json\"},\"repository\":{\"type\":\"git\",\"url\":\"git+https://github.com/pubnub/chat-engine.git\"},\"keywords\":[\"pubnub\",\"chat\",\"sdk\",\"realtime\"],\"bugs\":{\"url\":\"https://github.com/pubnub/chat-engine/issues\"},\"homepage\":\"https://github.com/pubnub/chat-engine#readme\",\"devDependencies\":{\"body-parser\":\"^1.17.2\",\"chai\":\"^3.5.0\",\"chat-engine-typing-indicator\":\"0.0.x\",\"docdash\":\"^0.4.0\",\"es6-promise\":\"^4.1.1\",\"eslint\":\"^4.7.1\",\"eslint-config-airbnb\":\"^15.1.0\",\"eslint-plugin-import\":\"^2.7.0\",\"express\":\"^4.15.3\",\"gulp\":\"^3.9.1\",\"gulp-clean\":\"^0.3.2\",\"gulp-eslint\":\"^4.0.0\",\"gulp-istanbul\":\"^1.1.2\",\"gulp-jsdoc3\":\"^1.0.1\",\"gulp-mocha\":\"^3.0.1\",\"gulp-rename\":\"^1.2.2\",\"gulp-surge\":\"^0.1.0\",\"gulp-uglify\":\"^2.0.0\",\"gulp-uglify-es\":\"^0.1.3\",\"http-server\":\"^0.10.0\",\"isparta\":\"^4.0.0\",\"jsdoc\":\"^3.5.5\",\"mocha\":\"^3.1.2\",\"proxyquire\":\"^1.8.0\",\"pubnub-functions-mock\":\"^0.0.6\",\"request\":\"^2.82.0\",\"run-sequence\":\"^2.2.0\",\"sinon\":\"^4.0.0\",\"stats-webpack-plugin\":\"^0.6.1\",\"surge\":\"^0.19.0\",\"uglifyjs-webpack-plugin\":\"^1.0.1\",\"webpack\":\"^3.6.0\",\"webpack-stream\":\"^4.0.0\"},\"dependencies\":{\"async\":\"^2.1.2\",\"axios\":\"^0.16.2\",\"eventemitter2\":\"^2.2.1\",\"pubnub\":\"^4.17.0\"}}"},{"id":54,"identifier":"/Users/ian/Development/chat-engine/src/components/chat.js","name":"./src/components/chat.js","index":33,"index2":84,"size":21105,"cacheable":true,"built":true,"optional":false,"prefetched":false,"chunks":[0],"assets":[],"issuer":"/Users/ian/Development/chat-engine/src/bootstrap.js","issuerId":31,"issuerName":"./src/bootstrap.js","profile":{"factory":15,"building":54,"dependencies":16},"failed":false,"errors":0,"warnings":0,"reasons":[{"moduleId":31,"moduleIdentifier":"/Users/ian/Development/chat-engine/src/bootstrap.js","module":"./src/bootstrap.js","moduleName":"./src/bootstrap.js","type":"cjs require","userRequest":"./components/chat","loc":"6:13-41"}],"usedExports":true,"providedExports":null,"optimizationBailout":[],"depth":2,"source":"const async = require('async');\nconst Emitter = require('../modules/emitter');\nconst Event = require('../components/event');\nconst Search = require('../components/search');\n\n/**\n This is the root {@link Chat} class that represents a chat room\n\n @param {String} [channel=new Date().getTime()] A unique identifier for this chat {@link Chat}. The channel is the unique name of a {@link Chat}, and is usually something like \"The Watercooler\", \"Support\", or \"Off Topic\". See [PubNub Channels](https://support.pubnub.com/support/solutions/articles/14000045182-what-is-a-channel-).\n @param {Boolean} [isPrivate=true] Attempt to authenticate ourselves before connecting to this {@link Chat}.\n @param {Boolean} [autoConnect=true] Connect to this chat as soon as its initiated. If set to ```false```, call the {@link Chat#connect} method to connect to this {@link Chat}.\n @param {String} [group='default'] Groups chat into a \"type\". This is the key which chats will be grouped into within {@link ChatEngine.session} object.\n @class Chat\n @extends Emitter\n @extends RootEmitter\n @fires Chat#$\".\"ready\n @fires Chat#$\".\"state\n @fires Chat#$\".\"online\".\"*\n @fires Chat#$\".\"offline\".\"*\n */\nclass Chat extends Emitter {\n\n constructor(chatEngine, channel = new Date().getTime(), isPrivate = false, autoConnect = true, meta = {}, group = 'custom') {\n\n super(chatEngine);\n\n this.chatEngine = chatEngine;\n\n this.name = 'Chat';\n\n this.meta = meta;\n\n this.group = group;\n\n /**\n * Excludes all users from reading or writing to the {@link chat} unless they have been explicitly invited via {@link Chat#invite};\n * @type Boolean\n * @readonly\n */\n this.isPrivate = isPrivate;\n\n /**\n * A string identifier for the Chat room. Any chat with an identical channel will be able to communicate with one another.\n * @type String\n * @readonly\n * @see [PubNub Channels](https://support.pubnub.com/support/solutions/articles/14000045182-what-is-a-channel-)\n */\n\n this.meta = {};\n\n /**\n * Excludes all users from reading or writing to the {@link chat} unless they have been explicitly invited via {@link Chat#invite};\n * @type Boolean\n * @readonly\n */\n this.isPrivate = isPrivate;\n\n this.channel = this.chatEngine.augmentChannel(channel, this.isPrivate);\n\n /**\n A list of users in this {@link Chat}. Automatically kept in sync as users join and leave the chat.\n Use [$.join](/Chat.html#event:$%2522.%2522join) and related events to get notified when this changes\n\n @type Object\n @readonly\n */\n this.users = {};\n\n /**\n * Boolean value that indicates of the Chat is connected to the network\n * @type {Boolean}\n */\n this.connected = false;\n\n this.chatEngine.chats[this.channel] = this;\n\n if (autoConnect) {\n this.connect();\n }\n\n return this;\n\n }\n\n /**\n Updates list of {@link User}s in this {@link Chat}\n based on who is online now.\n\n @private\n @param {Object} status The response status\n @param {Object} response The response payload object\n */\n onHereNow(status, response) {\n\n if (status.error) {\n\n /**\n * There was a problem fetching the presence of this chat\n * @event Chat#$\".\"error\".\"presence\n */\n this.chatEngine.throwError(this, 'trigger', 'presence', new Error('Getting presence of this Chat. Make sure PubNub presence is enabled for this key'), status);\n\n } else {\n\n // get the list of occupants in this channel\n let occupants = response.channels[this.channel].occupants;\n\n // format the userList for rltm.js standard\n occupants.forEach((occupant) => {\n this.userUpdate(occupant.uuid, occupant.state);\n });\n\n }\n\n }\n\n /**\n * Turns a {@link Chat} into a JSON representation.\n * @return {Object}\n */\n objectify() {\n\n return {\n channel: this.channel,\n group: this.group,\n private: this.isPrivate,\n meta: this.meta\n };\n\n }\n\n /**\n * Invite a user to this Chat. Authorizes the invited user in the Chat and sends them an invite via {@link User#direct}.\n * @param {User} user The {@link User} to invite to this chatroom.\n * @fires Me#event:$\".\"invite\n * @example\n * // one user running ChatEngine\n * let secretChat = new ChatEngine.Chat('secret-channel');\n * secretChat.invite(someoneElse);\n *\n * // someoneElse in another instance of ChatEngine\n * me.direct.on('$.invite', (payload) => {\n * let secretChat = new ChatEngine.Chat(payload.data.channel);\n * });\n */\n invite(user) {\n\n this.chatEngine.request('post', 'invite', {\n to: user.uuid,\n chat: this.objectify()\n })\n .then(() => {\n\n let send = () => {\n\n /**\n * Notifies {@link Me} that they've been invited to a new private {@link Chat}.\n * Fired by the {@link Chat#invite} method.\n * @event Me#$\".\"invite\n * @tutorial private\n * @example\n * me.direct.on('$.invite', (payload) => {\n * let privChat = new ChatEngine.Chat(payload.data.channel));\n * });\n */\n user.direct.emit('$.invite', {\n channel: this.channel\n });\n\n };\n\n if (!user.direct.connected) {\n user.direct.connect();\n user.direct.on('$.connected', send);\n } else {\n send();\n }\n\n })\n .catch((error) => {\n this.chatEngine.throwError(this, 'trigger', 'auth', new Error('Something went wrong while making a request to authentication server.'), { error });\n });\n\n }\n\n /**\n Keep track of {@link User}s in the room by subscribing to PubNub presence events.\n\n @private\n @param {Object} data The PubNub presence response for this event\n */\n onPresence(presenceEvent) {\n\n // make sure channel matches this channel\n\n // someone joins channel\n if (presenceEvent.action === 'join') {\n\n let user = this.createUser(presenceEvent.uuid, presenceEvent.state);\n\n /**\n * Fired when a {@link User} has joined the room.\n *\n * @event Chat#$\".\"online\".\"join\n * @param {Object} data The payload returned by the event\n * @param {User} data.user The {@link User} that came online\n * @example\n * chat.on('$.join', (data) => {\n * console.log('User has joined the room!', data.user);\n * });\n */\n\n // It's possible for PubNub to send us both a join and have the user appear in here_now\n // Avoid firing duplicate $.online events.\n if (!this.users[user.uuid]) {\n this.trigger('$.online.join', { user });\n }\n\n }\n\n // someone leaves channel\n if (presenceEvent.action === 'leave') {\n this.userLeave(presenceEvent.uuid);\n }\n\n // someone timesout\n if (presenceEvent.action === 'timeout') {\n this.userDisconnect(presenceEvent.uuid);\n }\n\n // someone's state is updated\n if (presenceEvent.action === 'state-change') {\n this.userUpdate(presenceEvent.uuid, presenceEvent.state);\n }\n\n\n }\n\n update(data) {\n\n let oldMeta = this.meta || {};\n this.meta = Object.assign(oldMeta, data);\n\n this.chatEngine.request('post', 'chat', {\n chat: this.objectify()\n }).then(() => {\n }).catch((error) => {\n this.chatEngine.throwError(this, 'trigger', 'auth', new Error('Something went wrong while making a request to authentication server.'), { error });\n });\n\n }\n\n /**\n * Send events to other clients in this {@link User}.\n * Events are trigger over the network and all events are made\n * on behalf of {@link Me}\n *\n * @param {String} event The event name\n * @param {Object} data The event payload object\n * @example\n * chat.emit('custom-event', {value: true});\n * chat.on('custom-event', (payload) => {\n * console.log(payload.sender.uuid, 'emitted the value', payload.data.value);\n * });\n */\n emit(event, data) {\n if (event === 'message' && typeof data !== 'object') {\n throw new Error('the payload has to be an object');\n }\n\n // create a standardized payload object\n let payload = {\n data, // the data supplied from params\n sender: this.chatEngine.me.uuid, // my own uuid\n chat: this, // an instance of this chat\n event,\n chatengineSDK: this.chatEngine.package.version\n };\n\n // run the plugin queue to modify the event\n this.runPluginQueue('emit', event, (next) => {\n next(null, payload);\n }, (err, pluginResponse) => {\n\n // remove chat otherwise it would be serialized\n // instead, it's rebuilt on the other end.\n // see this.trigger\n delete pluginResponse.chat;\n\n // publish the event and data over the configured channel\n\n // ensure the event exists within the global space\n this.events[event] = this.events[event] || new Event(this.chatEngine, this, event);\n\n this.events[event].publish(pluginResponse);\n\n });\n\n }\n\n /**\n Add a user to the {@link Chat}, creating it if it doesn't already exist.\n\n @private\n @param {String} uuid The user uuid\n @param {Object} state The user initial state\n @param {Boolean} trigger Force a trigger that this user is online\n */\n createUser(uuid, state) {\n\n // Ensure that this user exists in the global list\n // so we can reference it from here out\n this.chatEngine.users[uuid] = this.chatEngine.users[uuid] || new this.chatEngine.User(uuid);\n this.chatEngine.users[uuid].assign(state);\n\n // trigger the join event over this chatroom\n if (!this.users[uuid]) {\n\n /**\n * Broadcast that a {@link User} has come online. This is when\n * the framework firsts learn of a user. This can be triggered\n * by, ```$.join```, or other network events that\n * notify the framework of a new user.\n *\n * @event Chat#$\".\"online\".\"here\n * @param {Object} data The payload returned by the event\n * @param {User} data.user The {@link User} that came online\n * @example\n * chat.on('$.online.here', (data) => {\n * console.log('User has come online:', data.user);\n * });\n */\n\n this.trigger('$.online.here', {\n user: this.chatEngine.users[uuid]\n });\n\n }\n\n // store this user in the chatroom\n this.users[uuid] = this.chatEngine.users[uuid];\n\n // return the instance of this user\n return this.chatEngine.users[uuid];\n\n }\n\n /**\n * Update a user's state.\n * @private\n * @param {String} uuid The {@link User} uuid\n * @param {Object} state State to update for the user\n */\n userUpdate(uuid, state) {\n\n // ensure the user exists within the global space\n this.chatEngine.users[uuid] = this.chatEngine.users[uuid] || new this.chatEngine.User(uuid);\n\n // if we don't know about this user\n if (!this.users[uuid]) {\n // do the whole join thing\n this.createUser(uuid, state);\n }\n\n // update this user's state in this chatroom\n this.users[uuid].assign(state);\n\n /**\n * Broadcast that a {@link User} has changed state.\n * @event ChatEngine#$\".\"state\n * @param {Object} data The payload returned by the event\n * @param {User} data.user The {@link User} that changed state\n * @param {Object} data.state The new user state\n * @example\n * ChatEngine.on('$.state', (data) => {\n * console.log('User has changed state:', data.user, 'new state:', data.state);\n * });\n */\n this.chatEngine._emit('$.state', {\n user: this.users[uuid],\n state: this.users[uuid].state\n });\n\n }\n\n /**\n * Leave from the {@link Chat} on behalf of {@link Me}. Disconnects from the {@link Chat} and will stop\n * receiving events.\n * @fires Chat#event:$\".\"offline\".\"leave\n * @example\n * chat.leave();\n */\n leave() {\n\n // unsubscribe from the channel locally\n this.chatEngine.pubnub.unsubscribe({\n channels: [this.channel]\n });\n\n this.chatEngine.request('post', 'leave', { chat: this.objectify() })\n .then(() => {\n\n this.connected = false;\n\n this.trigger('$.disconnected');\n\n this.chatEngine.me.sync.emit('$.session.chat.leave', { subject: this.objectify() });\n\n })\n .catch((error) => {\n this.chatEngine.throwError(this, 'trigger', 'auth', new Error('Something went wrong while making a request to chat server.'), { error });\n });\n\n }\n\n /**\n Perform updates when a user has left the {@link Chat}.\n\n @private\n */\n userLeave(uuid) {\n\n // make sure this event is real, user may have already left\n if (this.users[uuid]) {\n\n // if a user leaves, trigger the event\n\n /**\n * Fired when a {@link User} intentionally leaves a {@link Chat}.\n *\n * @event Chat#$\".\"offline\".\"leave\n * @param {Object} data The data payload from the event\n * @param {User} user The {@link User} that has left the room\n * @example\n * chat.on('$.offline.leave', (data) => {\n * console.log('User left the room manually:', data.user);\n * });\n */\n this.trigger('$.offline.leave', {\n user: this.users[uuid]\n });\n\n // remove the user from the local list of users\n delete this.users[uuid];\n\n // we don't remove the user from the global list,\n // because they may be online in other channels\n\n } else {\n\n // that user isn't in the user list\n // we never knew about this user or they already left\n\n // console.log('user already left');\n }\n }\n\n /**\n Fired when a user disconnects from the {@link Chat}\n\n @private\n @param {String} uuid The uuid of the {@link Chat} that left\n */\n userDisconnect(uuid) {\n\n // make sure this event is real, user may have already left\n if (this.users[uuid]) {\n\n /**\n * Fired specifically when a {@link User} looses network connection\n * to the {@link Chat} involuntarily.\n *\n * @event Chat#$\".\"offline\".\"disconnect\n * @param {Object} data The {@link User} that disconnected\n * @param {Object} data.user The {@link User} that disconnected\n * @example\n * chat.on('$.offline.disconnect', (data) => {\n * console.log('User disconnected from the network:', data.user);\n * });\n */\n\n this.trigger('$.offline.disconnect', { user: this.users[uuid] });\n }\n\n }\n\n /**\n Set the state for {@link Me} within this {@link User}.\n Broadcasts the ```$.state``` event on other clients\n\n @private\n @param {Object} state The new state {@link Me} will have within this {@link User}\n */\n setState(state) {\n this.chatEngine.pubnub.setState({ state, channels: [this.chatEngine.global.channel] }, () => {\n // handle status, response\n });\n }\n\n /**\n Search through previously emitted events. Parameters act as AND operators. Returns an instance of the emitter based {@link History}. Will\n which will emit all old events unless ```config.event``` is supplied.\n @param {Object} [config] Our configuration for the PubNub history request. See the [PubNub History](https://www.pubnub.com/docs/web-javascript/storage-and-history) docs for more information on these parameters.\n @param {Event} [config.event] The {@link Event} to search for.\n @param {User} [config.sender] The {@link User} who sent the message.\n @param {Number} [config.limit=20] The maximum number of results to return that match search criteria. Search will continue operating until it returns this number of results or it reached the end of history.\n @param {Number} [config.start=0] The timetoken to begin searching between.\n @param {Number} [config.end=0] The timetoken to end searching between.\n @param {Boolean} [config.reverse=false] Search oldest messages first.\n @return {Search}\n @example\n chat.search({\n event: 'my-custom-event',\n sender: ChatEngine.me,\n limit: 20\n }).on('my-custom-event', (event) => {\n console.log('this is an old event!', event);\n }).on('$.search.finish', () => {\n console.log('we have all our results!')\n });\n */\n search(config) {\n return new Search(this.chatEngine, this, config);\n }\n\n onConnectionReady() {\n\n /**\n * Broadcast that the {@link Chat} is connected to the network.\n * @event Chat#$\".\"connected\n * @example\n * chat.on('$.connected', () => {\n * console.log('chat is ready to go!');\n * });\n */\n this.trigger('$.connected');\n\n this.chatEngine.me.sync.emit('$.session.chat.join', { subject: this.objectify() });\n\n this.connected = true;\n\n // add self to list of users\n this.users[this.chatEngine.me.uuid] = this.chatEngine.me;\n\n // trigger my own online event\n this.trigger('$.online.join', {\n user: this.chatEngine.me\n });\n\n // global channel updates are triggered manually, only get presence on custom chats\n if (this.channel !== this.chatEngine.global.channel && this.group === 'custom') {\n\n this.getUserUpdates();\n\n // we may miss updates, so call this again 5 seconds later\n setTimeout(() => {\n this.getUserUpdates();\n }, 5000);\n\n }\n\n }\n\n getUserUpdates() {\n\n // get a list of users online now\n // ask PubNub for information about connected users in this channel\n this.chatEngine.pubnub.hereNow({\n channels: [this.channel],\n includeUUIDs: true,\n includeState: true\n }, this.onHereNow.bind(this));\n\n }\n\n /**\n * Connect to PubNub servers to initialize the chat.\n * @example\n * // create a new chatroom, but don't connect to it automatically\n * let chat = new Chat('some-chat', false)\n *\n * // connect to the chat when we feel like it\n * chat.connect();\n */\n connect() {\n\n async.waterfall([\n (next) => {\n if (!this.chatEngine.pubnub) {\n next('You must call ChatEngine.connect() and wait for the $.ready event before creating new Chats.');\n } else {\n next();\n }\n },\n (next) => {\n\n this.chatEngine.request('post', 'grant', { chat: this.objectify() })\n .then(() => {\n next();\n })\n .catch(next);\n\n },\n (next) => {\n\n this.chatEngine.request('post', 'join', { chat: this.objectify() })\n .then(() => {\n next();\n })\n .catch(next);\n\n },\n (next) => {\n\n this.chatEngine.request('get', 'chat', {}, { channel: this.channel })\n .then((response) => {\n\n if (response.data.found) {\n this.meta = response.data.chat.meta;\n } else {\n this.update(this.meta);\n }\n\n this.onConnectionReady();\n\n })\n .catch(next);\n\n }\n ], (error) => {\n this.chatEngine.throwError(this, 'trigger', 'auth', new Error('Something went wrong while making a request to authentication server.'), { error });\n });\n\n }\n\n}\n\nmodule.exports = Chat;\n"},{"id":60,"identifier":"/Users/ian/Development/chat-engine/src/components/search.js","name":"./src/components/search.js","index":52,"index2":83,"size":6596,"cacheable":true,"built":true,"optional":false,"prefetched":false,"chunks":[0],"assets":[],"issuer":"/Users/ian/Development/chat-engine/src/components/chat.js","issuerId":54,"issuerName":"./src/components/chat.js","profile":{"factory":16,"building":20,"dependencies":0},"failed":false,"errors":0,"warnings":0,"reasons":[{"moduleId":54,"moduleIdentifier":"/Users/ian/Development/chat-engine/src/components/chat.js","module":"./src/components/chat.js","moduleName":"./src/components/chat.js","type":"cjs require","userRequest":"../components/search","loc":"4:15-46"}],"usedExports":true,"providedExports":null,"optimizationBailout":[],"depth":3,"source":"const Emitter = require('../modules/emitter');\nconst eachSeries = require('async/eachSeries');\n/**\nReturned by {@link Chat#search}. This is our Search class which allows one to search the backlog of messages.\n\n\n Powered by [PubNub History](https://www.pubnub.com/docs/web-javascript/storage-and-history).\n\n @class Search\n @extends Emitter\n @extends RootEmitter\n @param chatEngine\n @param chat\n @param config\n */\nclass Search extends Emitter {\n\n constructor(chatEngine, chat, config = {}) {\n\n super();\n\n this.chatEngine = chatEngine;\n\n /**\n Handy property to identify what this class is.\n @type String\n */\n this.name = 'Search';\n\n /**\n The {@link Chat} used for searching.\n @type Chat\n */\n this.chat = chat;\n\n /**\n An object containing configuration parameters supplied by {@link Chat#search}. See {@link Chat#search} for possible parameters.\n @type {Object}\n */\n this.config = config;\n this.config.event = config.event;\n this.config.limit = config.limit || 20;\n this.config.channel = this.chat.channel;\n this.config.includeTimetoken = true;\n this.config.stringifiedTimeToken = true;\n this.config.count = this.config.count || 100;\n\n this.config.pages = this.config.pages || 10;\n\n this.needleCount = 0;\n\n this.firstTT = 0;\n this.lastTT = 0;\n\n this.firstPage = true;\n\n /**\n * @private\n */\n this.sortHistory = (messages, desc) => {\n\n messages.sort((a, b) => {\n let e1 = desc ? b : a;\n let e2 = desc ? a : b;\n return parseInt(e1.timetoken, 10) - parseInt(e2.timetoken, 10);\n });\n\n return messages;\n\n };\n\n /**\n * Call PubNub history in a loop.\n * Unapologetically stolen from https://www.pubnub.com/docs/web-javascript/storage-and-history\n * @private\n */\n this.page = (pageDone) => {\n\n /**\n * Requesting another page from PubNub History.\n * @event Search#$\".\"page\".\"request\n */\n this._emit('$.search.page.request');\n\n // only set start if this is the first call and the user hasn't set it themselves\n this.config.start = this.config.reverse ? this.lastTT : this.firstTT;\n\n this.firstPage = false;\n\n this.chatEngine.pubnub.history(this.config, (status, response) => {\n\n /**\n * PubNub History returned a response.\n * @event Search#$\".\"page\".\"response\n */\n this._emit('$.search.page.response');\n\n if (status.error) {\n\n /**\n * There was a problem fetching the history of this chat\n * @event Chat#$\".\"error\".\"history\n */\n this.chatEngine.throwError(this, 'trigger', 'search', new Error('There was a problem searching history. Make sure your request parameters are valid and history is enabled for this PubNub key.'), status);\n\n } else {\n\n // timetoken of the first message in response\n this.firstTT = response.startTimeToken;\n // timetoken of the last message in response\n this.lastTT = response.endTimeToken;\n\n response.messages = this.sortHistory(response.messages);\n\n pageDone(response);\n\n }\n\n });\n };\n\n let eventFilter = (event) => {\n return {\n middleware: {\n on: {\n '*': (payload, next) => {\n let matches = payload && payload.event && payload.event === event;\n next(!matches, payload);\n }\n }\n }\n };\n };\n\n let senderFilter = (user) => {\n return {\n middleware: {\n on: {\n '*': (payload, next) => {\n let matches = payload && payload.sender && payload.sender.uuid === user.uuid;\n next(!matches, payload);\n }\n }\n }\n };\n };\n\n this.needleCount = 0;\n\n /**\n * @private\n */\n this.triggerHistory = (message, cb) => {\n\n if (this.needleCount < this.config.limit) {\n\n this.trigger(message.entry.event, message.entry, (reject) => {\n\n if (!reject) {\n this.needleCount += 1;\n }\n cb();\n\n });\n\n } else {\n cb();\n }\n\n };\n\n this.maxPage = 10;\n this.numPage = 0;\n\n this.next = () => {\n\n this.maxPage = this.maxPage + this.config.pages;\n\n this.find();\n\n };\n\n /**\n * @private\n */\n this.find = () => {\n\n this.page((response) => {\n\n if (!this.config.reverse) {\n response.messages.reverse();\n }\n\n eachSeries(response.messages, this.triggerHistory, () => {\n\n if (this.numPage === this.maxPage) {\n this._emit('$.search.pause');\n } else if (\n response.messages &&\n response.messages.length === this.config.count &&\n this.needleCount < this.config.limit) {\n this.numPage += 1;\n this.find();\n } else {\n\n /**\n * Search has returned all results or reached the end of history.\n * @event Search#$\".\"search\".\"finish\n */\n this._emit('$.search.finish');\n }\n\n });\n\n });\n\n return this;\n\n };\n\n if (this.config.event) {\n this.plugin(eventFilter(this.config.event));\n }\n\n if (this.config.sender) {\n this.plugin(senderFilter(this.config.sender));\n }\n\n /**\n * Search has started.\n * @event Search#$\".\"search\".\"start\n */\n this._emit('$.search.start');\n this.find();\n\n }\n\n}\n\nmodule.exports = Search;\n"},{"id":88,"identifier":"/Users/ian/Development/chat-engine/src/components/me.js","name":"./src/components/me.js","index":87,"index2":86,"size":4890,"cacheable":true,"built":true,"optional":false,"prefetched":false,"chunks":[0],"assets":[],"issuer":"/Users/ian/Development/chat-engine/src/bootstrap.js","issuerId":31,"issuerName":"./src/bootstrap.js","profile":{"factory":15,"building":60,"dependencies":1},"failed":false,"errors":0,"warnings":0,"reasons":[{"moduleId":31,"moduleIdentifier":"/Users/ian/Development/chat-engine/src/bootstrap.js","module":"./src/bootstrap.js","moduleName":"./src/bootstrap.js","type":"cjs require","userRequest":"./components/me","loc":"7:11-37"}],"usedExports":true,"providedExports":null,"optimizationBailout":[],"depth":2,"source":"const User = require('./user');\n\n/**\n Represents the client connection as a special {@link User} with write permissions.\n Has the ability to update it's state on the network. An instance of\n {@link Me} is returned by the ```ChatEngine.connect()```\n method.\n\n @class Me\n @extends User\n @extends Emitter\n @extends RootEmitter\n @param {String} uuid The uuid of this user\n */\nclass Me extends User {\n\n constructor(chatEngine, uuid, authData) {\n\n // call the User constructor\n super(chatEngine, uuid);\n\n this.name = 'Me';\n\n this.authData = authData;\n this.chatEngine = chatEngine;\n\n /**\n * Stores a map of {@link Chat} objects that this {@link Me} has joined across all clients.\n * @type {Object}\n */\n this.session = {};\n\n this.sync = new this.chatEngine.Chat([chatEngine.global.channel, 'user', uuid, 'me.', 'sync'].join('#'), false, true, {}, 'system');\n\n this.sync.on('$.session.chat.join', (payload) => {\n this.addChatToSession(payload.data.subject);\n });\n\n this.sync.on('$.session.chat.leave', (payload) => {\n this.removeChatFromSession(payload.data.subject);\n });\n\n return this;\n\n }\n\n // assign updates from network\n assign(state) {\n // we call \"update\" because calling \"super.assign\"\n // will direct back to \"this.update\" which creates\n // a loop of network updates\n super.update(state);\n }\n\n /**\n * Update {@link Me}'s state in a {@link Chat}. All other {@link User}s\n * will be notified of this change via ```$.state```.\n * Retrieve state at any time with {@link User#state}.\n * @param {Object} state The new state for {@link Me}\n * @param {Chat} chat An instance of the {@link Chat} where state will be updated.\n * Defaults to ```ChatEngine.global```.\n * @fires Chat#event:$\".\"state\n * @example\n * // update state\n * me.update({value: true});\n */\n update(state) {\n\n // run the root update function\n super.update(state);\n\n // publish the update over the global channel\n this.chatEngine.global.setState(state);\n\n }\n\n /**\n Stores {@link Chat} within ```ChatEngine.session``` keyed based on the ```chat.group``` property.\n @param {Object} chat JSON object representing {@link Chat}. Originally supplied via {@link Chat#objectify}.\n @private\n */\n addChatToSession(chat) {\n\n // create the chat group if it doesn't exist\n this.session[chat.group] = this.session[chat.group] || {};\n\n // check the chat exists within the global list but is not grouped\n let existingChat = this.chatEngine.chats[chat.channel];\n\n // if it exists\n if (existingChat) {\n // assign it to the group\n this.session[chat.group][chat.channel] = existingChat;\n } else {\n\n // otherwise, try to recreate it with the server information\n this.session[chat.group][chat.channel] = new this.chatEngine.Chat(chat.channel, chat.private, false, chat.meta, chat.group);\n\n /**\n Fired when another identical instance of {@link ChatEngine} and {@link Me} joins a {@link Chat} that this instance of {@link ChatEngine} is unaware of.\n Used to synchronize ChatEngine sessions between desktop and mobile, duplicate windows, etc.\n ChatEngine stores sessions on the server side identified by {@link User#uuid}.\n @event Me#$\".\"session\".\"chat\".\"join\n @example\n *\n * // Logged in as \"Ian\" in first window\n * ChatEngine.me.on('$.session.chat.join', (data) => {\n * console.log('I joined a new chat in a second window!', data.chat);\n * });\n *\n * // Logged in as \"Ian\" in second window\n * new ChatEngine.Chat('another-chat');\n */\n // this.trigger('$.session.chat.join', {\n // chat: this.session[chat.group][chat.channel]\n // });\n //\n this.trigger('$.session.chat.join', { chat: this.session[chat.group][chat.channel] });\n\n }\n\n }\n\n /**\n Removes {@link Chat} within this.session\n @private\n */\n removeChatFromSession(chat) {\n\n if (this.session[chat.group] && this.session[chat.group][chat.channel]) {\n\n chat = this.session[chat.group][chat.channel] || chat;\n\n /**\n * Fired when another identical instance of {@link ChatEngine} with an identical {@link Me} leaves a {@link Chat} via {@link Chat#leave}.\n * @event Me#$\".\"session\".\"chat\".\"leave\n */\n\n delete this.chatEngine.chats[chat.channel];\n delete this.session[chat.group][chat.channel];\n\n this.trigger('$.session.chat.leave', { chat });\n\n }\n\n }\n\n}\n\nmodule.exports = Me;\n"}],"filteredModules":77,"origins":[{"moduleId":30,"module":"/Users/ian/Development/chat-engine/src/index.js","moduleIdentifier":"/Users/ian/Development/chat-engine/src/index.js","moduleName":"./src/index.js","loc":"","name":"main","reasons":[]}]}],"modules":[{"id":3,"identifier":"/Users/ian/Development/chat-engine/node_modules/webpack/buildin/global.js","name":"(webpack)/buildin/global.js","index":37,"index2":31,"size":488,"cacheable":true,"built":true,"optional":false,"prefetched":false,"chunks":[0],"assets":[],"issuer":"/Users/ian/Development/chat-engine/node_modules/async/dist/async.js","issuerId":15,"issuerName":"./node_modules/async/dist/async.js","profile":{"factory":143,"building":18},"failed":false,"errors":0,"warnings":0,"reasons":[{"moduleId":15,"moduleIdentifier":"/Users/ian/Development/chat-engine/node_modules/async/dist/async.js","module":"./node_modules/async/dist/async.js","moduleName":"./node_modules/async/dist/async.js","type":"cjs require","userRequest":"global","loc":"1:0-44"},{"moduleId":27,"moduleIdentifier":"/Users/ian/Development/chat-engine/node_modules/lodash/_freeGlobal.js","module":"./node_modules/lodash/_freeGlobal.js","moduleName":"./node_modules/lodash/_freeGlobal.js","type":"cjs require","userRequest":"global","loc":"1:0-41"},{"moduleId":55,"moduleIdentifier":"/Users/ian/Development/chat-engine/node_modules/setimmediate/setImmediate.js","module":"./node_modules/setimmediate/setImmediate.js","moduleName":"./node_modules/setimmediate/setImmediate.js","type":"cjs require","userRequest":"global","loc":"1:0-41"}],"usedExports":true,"providedExports":null,"optimizationBailout":[],"depth":3,"source":"var g;\n\n// This works in non-strict mode\ng = (function() {\n\treturn this;\n})();\n\ntry {\n\t// This works if eval is allowed (see CSP)\n\tg = g || Function(\"return this\")() || (1,eval)(\"this\");\n} catch(e) {\n\t// This works if the window reference is available\n\tif(typeof window === \"object\")\n\t\tg = window;\n}\n\n// g can still be undefined, but nothing to do about it...\n// We return undefined, instead of nothing here, so it's\n// easier to handle this case. if(!global) { ...}\n\nmodule.exports = g;\n"},{"id":4,"identifier":"/Users/ian/Development/chat-engine/node_modules/webpack/buildin/module.js","name":"(webpack)/buildin/module.js","index":38,"index2":34,"size":495,"cacheable":true,"built":true,"optional":false,"prefetched":false,"chunks":[0],"assets":[],"issuer":"/Users/ian/Development/chat-engine/node_modules/async/dist/async.js","issuerId":15,"issuerName":"./node_modules/async/dist/async.js","profile":{"factory":143,"building":19},"failed":false,"errors":0,"warnings":0,"reasons":[{"moduleId":15,"moduleIdentifier":"/Users/ian/Development/chat-engine/node_modules/async/dist/async.js","module":"./node_modules/async/dist/async.js","moduleName":"./node_modules/async/dist/async.js","type":"cjs require","userRequest":"module","loc":"1:0-44"},{"moduleId":74,"moduleIdentifier":"/Users/ian/Development/chat-engine/node_modules/lodash/isBuffer.js","module":"./node_modules/lodash/isBuffer.js","moduleName":"./node_modules/lodash/isBuffer.js","type":"cjs require","userRequest":"module","loc":"1:0-41"},{"moduleId":80,"moduleIdentifier":"/Users/ian/Development/chat-engine/node_modules/lodash/_nodeUtil.js","module":"./node_modules/lodash/_nodeUtil.js","moduleName":"./node_modules/lodash/_nodeUtil.js","type":"cjs require","userRequest":"module","loc":"1:0-41"}],"usedExports":true,"providedExports":null,"optimizationBailout":[],"depth":3,"source":"module.exports = function(module) {\n\tif(!module.webpackPolyfill) {\n\t\tmodule.deprecate = function() {};\n\t\tmodule.paths = [];\n\t\t// module.parent = undefined by default\n\t\tif(!module.children) module.children = [];\n\t\tObject.defineProperty(module, \"loaded\", {\n\t\t\tenumerable: true,\n\t\t\tget: function() {\n\t\t\t\treturn module.l;\n\t\t\t}\n\t\t});\n\t\tObject.defineProperty(module, \"id\", {\n\t\t\tenumerable: true,\n\t\t\tget: function() {\n\t\t\t\treturn module.i;\n\t\t\t}\n\t\t});\n\t\tmodule.webpackPolyfill = 1;\n\t}\n\treturn module;\n};\n"},{"id":5,"identifier":"/Users/ian/Development/chat-engine/src/modules/emitter.js","name":"./src/modules/emitter.js","index":39,"index2":48,"size":7500,"cacheable":true,"built":true,"optional":false,"prefetched":false,"chunks":[0],"assets":[],"issuer":"/Users/ian/Development/chat-engine/src/components/user.js","issuerId":29,"issuerName":"./src/components/user.js","profile":{"factory":43,"building":13,"dependencies":4},"failed":false,"errors":0,"warnings":0,"reasons":[{"moduleId":29,"moduleIdentifier":"/Users/ian/Development/chat-engine/src/components/user.js","module":"./src/components/user.js","moduleName":"./src/components/user.js","type":"cjs require","userRequest":"../modules/emitter","loc":"1:16-45"},{"moduleId":54,"moduleIdentifier":"/Users/ian/Development/chat-engine/src/components/chat.js","module":"./src/components/chat.js","moduleName":"./src/components/chat.js","type":"cjs require","userRequest":"../modules/emitter","loc":"2:16-45"},{"moduleId":60,"moduleIdentifier":"/Users/ian/Development/chat-engine/src/components/search.js","module":"./src/components/search.js","moduleName":"./src/components/search.js","type":"cjs require","userRequest":"../modules/emitter","loc":"1:16-45"}],"usedExports":true,"providedExports":null,"optimizationBailout":[],"depth":3,"source":"const waterfall = require('async/waterfall');\nconst RootEmitter = require('./root_emitter');\nconst Event = require('../components/event');\n\n/**\n An ChatEngine generic emitter that supports plugins and forwards\n events to the root emitter.\n @class Emitter\n @extends RootEmitter\n */\nclass Emitter extends RootEmitter {\n\n constructor(chatEngine) {\n\n super();\n\n this.chatEngine = chatEngine;\n\n this.name = 'Emitter';\n\n /**\n Stores a list of plugins bound to this object\n @private\n */\n this.plugins = [];\n\n /**\n Stores in memory keys and values\n @private\n */\n this._dataset = {};\n\n /**\n Emit events locally.\n\n @private\n @param {String} event The event payload object\n */\n this._emit = (event, data = {}) => {\n\n // all events are forwarded to ChatEngine object\n // so you can globally bind to events with ChatEngine.on()\n this.chatEngine._emit(event, data, this);\n\n // emit the event from the object that created it\n this.emitter.emit(event, data);\n\n return this;\n\n };\n\n /**\n * Listen for a specific event and fire a callback when it's emitted. Supports wildcard matching.\n * @method\n * @param {String} event The event name\n * @param {Function} cb The function to run when the event is emitted\n * @example\n *\n * // Get notified whenever someone joins the room\n * object.on('event', (payload) => {\n * console.log('event was fired').\n * })\n *\n * // Get notified of event.a and event.b\n * object.on('event.*', (payload) => {\n * console.log('event.a or event.b was fired').;\n * })\n */\n this.on = (event, cb) => {\n\n // keep track of all events on this emitter\n this.events[event] = this.events[event] || new Event(this.chatEngine, this, event);\n\n // call the private _on property\n this._on(event, cb);\n\n return this;\n\n };\n\n }\n\n // add an object as a subobject under a namespoace\n addChild(childName, childOb) {\n // assign the new child object as a property of parent under the\n // given namespace\n this[childName] = childOb;\n\n // assign a data set for the namespace if it doesn't exist\n if (!this._dataset[childName]) {\n this._dataset[childName] = {};\n }\n\n // the new object can use ```this.parent``` to access\n // the root class\n childOb.parent = this;\n\n // bind get() and set() to the data set\n childOb.get = this.get.bind(this._dataset[childName]);\n childOb.set = this.set.bind(this._dataset[childName]);\n }\n\n get(key) {\n return this[key];\n }\n\n set(key, value) {\n if (this[key] && !value) {\n delete this[key];\n } else {\n this[key] = value;\n }\n }\n\n /**\n Binds a plugin to this object\n @param {Object} module The plugin module\n @tutorial using\n */\n plugin(module) {\n\n // add this plugin to a list of plugins for this object\n this.plugins.push(module);\n\n // see if there are plugins to attach to this class\n if (module.extends && module.extends[this.name]) {\n // attach the plugins to this class\n // under their namespace\n this.addChild(module.namespace, new module.extends[this.name]());\n\n this[module.namespace].ChatEngine = this.chatEngine;\n\n // if the plugin has a special construct function\n // run it\n if (this[module.namespace].construct) {\n this[module.namespace].construct();\n }\n\n }\n\n return this;\n\n }\n\n bindProtoPlugins() {\n\n if (this.chatEngine.protoPlugins[this.name]) {\n\n this.chatEngine.protoPlugins[this.name].forEach((module) => {\n this.plugin(module);\n });\n\n }\n\n }\n\n /**\n Broadcasts an event locally to all listeners.\n @private\n @param {String} event The event name\n @param {Object} payload The event payload object\n */\n trigger(event, payload = {}, done = () => {}) {\n\n let complete = () => {\n\n // let plugins modify the event\n this.runPluginQueue('on', event, (next) => {\n next(null, payload);\n }, (reject, pluginResponse) => {\n\n if (reject) {\n done(reject);\n } else {\n // emit this event to any listener\n this._emit(event, pluginResponse);\n done(null, event, pluginResponse);\n }\n\n });\n\n };\n\n // this can be made into plugin\n if (typeof payload === 'object') {\n\n // restore chat in payload\n if (!payload.chat) {\n payload.chat = this;\n }\n\n // if we should try to restore the sender property\n if (payload.sender) {\n\n // the user doesn't exist, create it\n payload.sender = new this.chatEngine.User(payload.sender);\n\n payload.sender._getState(() => {\n complete();\n });\n\n } else {\n // there's no \"sender\" in this object, move on\n complete();\n }\n\n } else {\n // payload is not an object, we want nothing to do with it.\n complete();\n }\n }\n\n /**\n Load plugins and attach a queue of functions to execute before and\n after events are trigger or received.\n\n @private\n @param {String} location Where in the middleeware the event should run (emit, trigger)\n @param {String} event The event name\n @param {String} first The first function to run before the plugins have run\n @param {String} last The last function to run after the plugins have run\n */\n runPluginQueue(location, event, first, last) {\n\n // this assembles a queue of functions to run as middleware\n // event is a triggered event key\n let pluginQueue = [];\n\n // the first function is always required\n pluginQueue.push(first);\n\n // look through the configured plugins\n this.plugins.forEach((pluginItem) => {\n\n // if they have defined a function to run specifically\n // for this event\n if (pluginItem.middleware && pluginItem.middleware[location]) {\n\n if (pluginItem.middleware[location][event]) {\n // add the function to the queue\n pluginQueue.push(pluginItem.middleware[location][event]);\n }\n\n if (pluginItem.middleware[location]['*']) {\n // add the function to the queue\n pluginQueue.push(pluginItem.middleware[location]['*']);\n }\n\n }\n\n });\n\n // waterfall runs the functions in assigned order\n // waiting for one to complete before moving to the next\n // when it's done, the ```last``` parameter is called\n waterfall(pluginQueue, last);\n\n }\n\n onConstructed() {\n\n this.bindProtoPlugins();\n this.trigger(['$', 'created', this.name.toLowerCase()].join('.'));\n\n }\n\n}\n\nmodule.exports = Emitter;\n"},{"id":14,"identifier":"/Users/ian/Development/chat-engine/src/modules/root_emitter.js","name":"./src/modules/root_emitter.js","index":31,"index2":30,"size":4109,"cacheable":true,"built":true,"optional":false,"prefetched":false,"chunks":[0],"assets":[],"issuer":"/Users/ian/Development/chat-engine/src/bootstrap.js","issuerId":31,"issuerName":"./src/bootstrap.js","profile":{"factory":15,"building":15},"failed":false,"errors":0,"warnings":0,"reasons":[{"moduleId":5,"moduleIdentifier":"/Users/ian/Development/chat-engine/src/modules/emitter.js","module":"./src/modules/emitter.js","moduleName":"./src/modules/emitter.js","type":"cjs require","userRequest":"./root_emitter","loc":"2:20-45"},{"moduleId":31,"moduleIdentifier":"/Users/ian/Development/chat-engine/src/bootstrap.js","module":"./src/bootstrap.js","moduleName":"./src/bootstrap.js","type":"cjs require","userRequest":"./modules/root_emitter","loc":"5:20-53"}],"usedExports":true,"providedExports":null,"optimizationBailout":[],"depth":2,"source":"\n// Allows us to create and bind to events. Everything in ChatEngine is an event\n// emitter\nconst EventEmitter2 = require('eventemitter2').EventEmitter2;\n\n/**\n* The {@link ChatEngine} object is a RootEmitter. Configures an event emitter that other ChatEngine objects inherit. Adds shortcut methods for\n* ```this.on()```, ```this.emit()```, etc.\n* @class RootEmitter\n*/\nclass RootEmitter {\n\n constructor() {\n\n /**\n * @private\n */\n this.events = {};\n\n this.name = 'RootEmitter';\n\n /**\n Create a new EventEmitter2 object for this class.\n\n @private\n */\n this.emitter = new EventEmitter2({\n wildcard: true,\n newListener: true,\n maxListeners: 50,\n verboseMemoryLeak: true\n });\n\n // we bind to make sure wildcards work\n // https://github.com/asyncly/EventEmitter2/issues/186\n\n /**\n Private emit method that broadcasts the event to listeners on this page.\n\n @private\n @param {String} event The event name\n @param {Object} the event payload\n */\n this._emit = this.emitter.emit.bind(this.emitter);\n\n /**\n Listen for a specific event and fire a callback when it's emitted. This is reserved in case ```this.on``` is overwritten.\n\n @private\n @param {String} event The event name\n @param {Function} callback The function to run when the event is emitted\n */\n\n this._on = this.emitter.on.bind(this.emitter);\n\n /**\n * Listen for a specific event and fire a callback when it's emitted. Supports wildcard matching.\n * @method\n * @param {String} event The event name\n * @param {Function} cb The function to run when the event is emitted\n * @example\n *\n * // Get notified whenever someone joins the room\n * object.on('event', (payload) => {\n * console.log('event was fired').\n * })\n *\n * // Get notified of event.a and event.b\n * object.on('event.*', (payload) => {\n * console.log('event.a or event.b was fired').;\n * })\n */\n this.on = (event, callback) => {\n\n // emit the event from the object that created it\n this.emitter.on(event, callback);\n\n return this;\n\n };\n\n /**\n * Stop a callback from listening to an event.\n * @method\n * @param {String} event The event name\n * @example\n * let callback = function(payload;) {\n * console.log('something happend!');\n * };\n * object.on('event', callback);\n * // ...\n * object.off('event', callback);\n */\n this.off = (event, callback) => {\n\n // emit the event from the object that created it\n this.emitter.off(event, callback);\n\n return this;\n\n };\n\n /**\n * Listen for any event on this object and fire a callback when it's emitted\n * @method\n * @param {Function} callback The function to run when any event is emitted. First parameter is the event name and second is the payload.\n * @example\n * object.onAny((event, payload) => {\n * console.log('All events trigger this.');\n * });\n */\n this.onAny = (event, callback) => {\n\n // emit the event from the object that created it\n this.emitter.onAny(event, callback);\n\n return this;\n\n };\n\n /**\n * Listen for an event and only fire the callback a single time\n * @method\n * @param {String} event The event name\n * @param {Function} callback The function to run once\n * @example\n * object.once('message', => (event, payload) {\n * console.log('This is only fired once!');\n * });\n */\n this.once = (event, callback) => {\n\n // emit the event from the object that created it\n this.emitter.once(event, callback);\n\n return this;\n\n };\n\n }\n\n}\n\nmodule.exports = RootEmitter;\n"},{"id":23,"identifier":"/Users/ian/Development/chat-engine/src/components/event.js","name":"./src/components/event.js","index":51,"index2":47,"size":2220,"cacheable":true,"built":true,"optional":false,"prefetched":false,"chunks":[0],"assets":[],"issuer":"/Users/ian/Development/chat-engine/src/components/chat.js","issuerId":54,"issuerName":"./src/components/chat.js","profile":{"factory":16,"building":23},"failed":false,"errors":0,"warnings":0,"reasons":[{"moduleId":5,"moduleIdentifier":"/Users/ian/Development/chat-engine/src/modules/emitter.js","module":"./src/modules/emitter.js","moduleName":"./src/modules/emitter.js","type":"cjs require","userRequest":"../components/event","loc":"3:14-44"},{"moduleId":54,"moduleIdentifier":"/Users/ian/Development/chat-engine/src/components/chat.js","module":"./src/components/chat.js","moduleName":"./src/components/chat.js","type":"cjs require","userRequest":"../components/event","loc":"3:14-44"}],"usedExports":true,"providedExports":null,"optimizationBailout":[],"depth":3,"source":"/**\n * @class Event\n * Represents an event that may be emitted or subscribed to.\n */\nclass Event {\n\n constructor(chatEngine, chat, event) {\n\n /**\n Events are always a property of a {@link Chat}. Responsible for\n listening to specific events and firing events when they occur.\n @readonly\n @type String\n @see [PubNub Channels](https://support.pubnub.com/support/solutions/articles/14000045182-what-is-a-channel-)\n */\n this.channel = chat.channel;\n\n this.chatEngine = chatEngine;\n\n this.chat = chat;\n\n this.event = event;\n\n this.name = 'Event';\n\n /**\n Forwards events to the Chat that registered the event {@link Chat}\n\n @private\n @param {Object} data The event payload object\n */\n\n // call onMessage when PubNub receives an event\n this.chatEngine.pubnub.addListener({\n message: this.onMessage.bind(this)\n });\n\n return this;\n\n }\n\n onMessage(m) {\n\n if (this.channel === m.channel && m.message.event === this.event) {\n this.chat.trigger(m.message.event, m.message);\n }\n\n }\n\n /**\n Publishes the event over the PubNub network to the {@link Event} channel\n\n @private\n @param {Object} data The event payload object\n */\n publish(m) {\n\n m.event = this.event;\n\n this.chatEngine.pubnub.publish({\n message: m,\n channel: this.channel\n }, (status) => {\n\n if (status.statusCode === 200) {\n\n /**\n * Message successfully published\n * @event Chat#$\".\"publish\".\"success\n * @param {Object} data The message object\n */\n this.chat.trigger('$.publish.success', m);\n } else {\n\n /**\n * There was a problem publishing over the PubNub network.\n * @event Chat#$\".\"error\".\"publish\n */\n this.chatEngine.throwError(this.chat, 'trigger', 'publish', new Error('There was a problem publishing over the PubNub network.'), status);\n }\n\n });\n\n }\n\n}\n\nmodule.exports = Event;\n"},{"id":29,"identifier":"/Users/ian/Development/chat-engine/src/components/user.js","name":"./src/components/user.js","index":88,"index2":85,"size":5484,"cacheable":true,"built":true,"optional":false,"prefetched":false,"chunks":[0],"assets":[],"issuer":"/Users/ian/Development/chat-engine/src/bootstrap.js","issuerId":31,"issuerName":"./src/bootstrap.js","profile":{"factory":15,"building":26},"failed":false,"errors":0,"warnings":0,"reasons":[{"moduleId":31,"moduleIdentifier":"/Users/ian/Development/chat-engine/src/bootstrap.js","module":"./src/bootstrap.js","moduleName":"./src/bootstrap.js","type":"cjs require","userRequest":"./components/user","loc":"8:13-41"},{"moduleId":88,"moduleIdentifier":"/Users/ian/Development/chat-engine/src/components/me.js","module":"./src/components/me.js","moduleName":"./src/components/me.js","type":"cjs require","userRequest":"./user","loc":"1:13-30"}],"usedExports":true,"providedExports":null,"optimizationBailout":[],"depth":2,"source":"const Emitter = require('../modules/emitter');\n\n/**\n This is our User class which represents a connected client. User's are automatically created and managed by {@link Chat}s, but you can also instantiate them yourself.\n If a User has been created but has never been authenticated, you will recieve 403s when connecting to their feed or direct Chats.\n @class User\n @extends Emitter\n @extends RootEmitter\n @param uuid\n @param state\n */\nclass User extends Emitter {\n\n constructor(chatEngine, uuid, state = {}) {\n\n super();\n\n this.chatEngine = chatEngine;\n\n this.name = 'User';\n\n /**\n The User's unique identifier, usually a device uuid. This helps ChatEngine identify the user between events. This is public id exposed to the network.\n Check out [the wikipedia page on UUIDs](https://en.wikipedia.org/wiki/Universally_unique_identifier).\n\n @readonly\n @type String\n */\n this.uuid = uuid;\n\n /**\n * Gets the user state. See {@link Me#update} for how to assign state values.\n * @return {Object} Returns a generic JSON object containing state information.\n * @example\n *\n * // State\n * let state = user.state;\n */\n this.state = {};\n\n this._stateFetched = false;\n\n /**\n * Feed is a Chat that only streams things a User does, like\n * 'startTyping' or 'idle' events for example. Anybody can subscribe\n * to a User's feed, but only the User can publish to it. Users will\n * not be able to converse in this channel.\n *\n * @type Chat\n * @example\n * // me\n * me.feed.emit('update', 'I may be away from my computer right now');\n *\n * // another instance\n * them.feed.connect();\n * them.feed.on('update', (payload) => {})\n */\n\n // grants for these chats are done on auth. Even though they're marked private, they are locked down via the server\n this.feed = new this.chatEngine.Chat([chatEngine.global.channel, 'user', uuid, 'read.', 'feed'].join('#'), false, this.constructor.name === 'Me', {}, 'system');\n\n /**\n * Direct is a private channel that anybody can publish to but only\n * the user can subscribe to. Great for pushing notifications or\n * inviting to other chats. Users will not be able to communicate\n * with one another inside of this chat. Check out the\n * {@link Chat#invite} method for private chats utilizing\n * {@link User#direct}.\n *\n * @type Chat\n * @example\n * // me\n * me.direct.on('private-message', (payload) -> {\n * console.log(payload.sender.uuid, 'sent your a direct message');\n * });\n *\n * // another instance\n * them.direct.connect();\n * them.direct.emit('private-message', {secret: 42});\n */\n this.direct = new this.chatEngine.Chat([chatEngine.global.channel, 'user', uuid, 'write.', 'direct'].join('#'), false, this.constructor.name === 'Me', {}, 'system');\n\n // if the user does not exist at all and we get enough\n // information to build the user\n if (!chatEngine.users[uuid]) {\n chatEngine.users[uuid] = this;\n }\n\n // update this user's state in it's created context\n this.assign(state);\n\n return this;\n\n }\n\n /**\n * @private\n * @param {Object} state The new state for the user\n * @param {Chat} chat Chatroom to retrieve state from\n */\n update(state) {\n let oldState = this.state || {};\n this.state = Object.assign(oldState, state);\n }\n\n /**\n this is only called from network updates\n\n @private\n */\n assign(state) {\n this.update(state);\n }\n\n /**\n Get stored user state from remote server.\n @private\n */\n _getState(callback) {\n\n if (!this._stateFetched) {\n\n this.chatEngine.pubnub.getState({\n uuid: this.uuid,\n channels: [this.chatEngine.global.channel]\n }, (status, response) => {\n\n if (status.statusCode === 200) {\n\n let pnState = response.channels[this.chatEngine.global.channel];\n if (Object.keys(pnState).length) {\n\n this.assign(response.data);\n\n this._stateFetched = true;\n callback(this.state);\n\n } else {\n\n this.chatEngine.request('get', 'user_state', {\n user: this.uuid\n })\n .then((res) => {\n\n this.assign(res.data);\n\n this._stateFetched = true;\n callback(this.state);\n\n })\n .catch((err) => {\n // console.log('this is hte err', err);\n this.chatEngine.throwError(this, 'trigger', 'getState', err);\n });\n\n }\n\n } else {\n this.chatEngine.throwError(this, 'trigger', 'getState', new Error('There was a problem getting state from the PubNub network.'));\n }\n\n });\n\n } else {\n callback(this.state);\n }\n\n }\n\n}\n\nmodule.exports = User;\n"},{"id":30,"identifier":"/Users/ian/Development/chat-engine/src/index.js","name":"./src/index.js","index":0,"index2":88,"size":1425,"cacheable":true,"built":true,"optional":false,"prefetched":false,"chunks":[0],"assets":[],"issuer":null,"issuerId":null,"issuerName":null,"profile":{"factory":25,"building":20},"failed":false,"errors":0,"warnings":0,"reasons":[],"usedExports":true,"providedExports":null,"optimizationBailout":[],"depth":0,"source":"// allows asynchronous execution flow.\nconst init = require('./bootstrap');\n\n/**\nGlobal object used to create an instance of {@link ChatEngine}.\n\n@alias ChatEngineCore\n@param pnConfig {Object} ChatEngine is based off PubNub. Supply your PubNub configuration parameters here. See the getting started tutorial and [the PubNub docs](https://www.pubnub.com/docs/java-se-java/api-reference-configuration).\n@param ceConfig {Object} A list of chat engine specific config options.\n@param [ceConfig.globalChannel=chat-engine] {String} The root channel. See {@link ChatEngine.global}\n@param [ceConfig.throwErrors=true] {Boolean} Throws errors in JS console.\n@param [ceConfig.endpoint] {String} The root URL used to manage permissions for private channels.\n@return {ChatEngine} Returns an instance of {@link ChatEngine}\n@example\nChatEngine = ChatEngineCore.create({\n publishKey: 'demo',\n subscribeKey: 'demo'\n});\n*/\n\nconst create = (pnConfig, ceConfig = {}) => {\n\n if (ceConfig.globalChannel) {\n ceConfig.globalChannel = ceConfig.globalChannel.toString();\n } else {\n ceConfig.globalChannel = 'chat-engine';\n }\n\n if (typeof ceConfig.throwErrors === 'undefined') {\n ceConfig.throwErrors = true;\n }\n\n // return an instance of ChatEngine\n return init(ceConfig, pnConfig);\n\n};\n\n// export the ChatEngine api\nmodule.exports = {\n plugin: {}, // leave a spot for plugins to exist\n create\n};\n"},{"id":31,"identifier":"/Users/ian/Development/chat-engine/src/bootstrap.js","name":"./src/bootstrap.js","index":1,"index2":87,"size":16020,"cacheable":true,"built":true,"optional":false,"prefetched":false,"chunks":[0],"assets":[],"issuer":"/Users/ian/Development/chat-engine/src/index.js","issuerId":30,"issuerName":"./src/index.js","profile":{"factory":10,"building":37},"failed":false,"errors":0,"warnings":0,"reasons":[{"moduleId":30,"moduleIdentifier":"/Users/ian/Development/chat-engine/src/index.js","module":"./src/index.js","moduleName":"./src/index.js","type":"cjs require","userRequest":"./bootstrap","loc":"2:13-35"}],"usedExports":true,"providedExports":null,"optimizationBailout":[],"depth":1,"source":"const axios = require('axios');\nconst PubNub = require('pubnub');\nconst pack = require('../package.json');\n\nconst RootEmitter = require('./modules/root_emitter');\nconst Chat = require('./components/chat');\nconst Me = require('./components/me');\nconst User = require('./components/user');\nconst async = require('async');\n\n/**\n @class ChatEngine\n @extends RootEmitter\n @return {ChatEngine} Returns an instance of {@link ChatEngine}\n */\nmodule.exports = (ceConfig = {}, pnConfig = {}) => {\n\n // Create the root ChatEngine object\n let ChatEngine = new RootEmitter();\n\n ChatEngine.ceConfig = ceConfig;\n ChatEngine.pnConfig = pnConfig;\n\n ChatEngine.pnConfig.heartbeatInterval = ChatEngine.pnConfig.heartbeatInterval || 30;\n ChatEngine.pnConfig.presenceTimeout = ChatEngine.pnConfig.presenceTimeout || 60;\n\n ChatEngine.ceConfig.endpoint = ChatEngine.ceConfig.endpoint || 'https://pubsub.pubnub.com/v1/blocks/sub-key/' + ChatEngine.pnConfig.subscribeKey + '/chat-engine-server';\n ChatEngine.ceConfig.globalChannel = ChatEngine.ceConfig.globalChannel || 'chat-engine-global';\n\n /**\n * A map of all known {@link User}s in this instance of ChatEngine.\n * @type {Object}\n * @memberof ChatEngine\n */\n ChatEngine.users = {};\n\n /**\n * A map of all known {@link Chat}s in this instance of ChatEngine.\n * @memberof ChatEngine\n * @type {Object}\n */\n ChatEngine.chats = {};\n\n /**\n * A global {@link Chat} that all {@link User}s join when they connect to ChatEngine. Useful for announcements, alerts, and global events.\n * @member {Chat} global\n * @memberof ChatEngine\n */\n ChatEngine.global = false;\n\n /**\n * This instance of ChatEngine represented as a special {@link User} know as {@link Me}.\n * @member {Me} me\n * @memberof ChatEngine\n */\n ChatEngine.me = false;\n\n /**\n * An instance of PubNub, the networking infrastructure that powers the realtime communication between {@link User}s in {@link Chats}.\n * @member {Object} pubnub\n * @memberof ChatEngine\n */\n ChatEngine.pubnub = false;\n\n /**\n * Indicates if ChatEngine has fired the {@link ChatEngine#$\".\"ready} event.\n * @member {Object} ready\n * @memberof ChatEngine\n */\n ChatEngine.ready = false;\n\n /**\n * The package.json for ChatEngine. Used mainly for detecting package version.\n * @type {Object}\n */\n ChatEngine.package = pack;\n\n ChatEngine.throwError = (self, cb, key, ceError, payload = {}) => {\n\n if (ceConfig.throwErrors) {\n // throw ceError;\n console.error(payload);\n throw ceError;\n }\n\n payload.ceError = ceError.toString();\n\n self[cb](['$', 'error', key].join('.'), payload);\n\n };\n\n if (ceConfig.debug) {\n ChatEngine.onAny((event, payload) => {\n console.info('debug:', event, payload);\n });\n }\n\n ChatEngine.protoPlugins = {};\n\n /**\n * Bind a plugin to all future instances of a Class.\n * @method ChatEngine#proto\n * @param {String} className The string representation of a class to bind to\n * @param {Class} plugin The plugin function.\n */\n ChatEngine.proto = (className, plugin) => {\n ChatEngine.protoPlugins[className] = ChatEngine.protoPlugins[className] || [];\n ChatEngine.protoPlugins[className].push(plugin);\n };\n\n ChatEngine.request = (method, route, inputBody = {}, inputParams = {}) => {\n\n let body = {\n uuid: pnConfig.uuid,\n global: ceConfig.globalChannel,\n authData: ChatEngine.me.authData,\n authKey: pnConfig.authKey\n };\n\n let params = {\n route\n };\n\n body = Object.assign(body, inputBody);\n params = Object.assign(params, inputParams);\n\n if (method === 'get' || method === 'delete') {\n params = Object.assign(params, body);\n return axios[method](ceConfig.endpoint, { params });\n } else {\n return axios[method](ceConfig.endpoint, body, { params });\n }\n\n\n };\n\n ChatEngine.parseChannel = (channel) => {\n\n let info = channel.split('#');\n\n return {\n global: info[0],\n type: info[1],\n private: info[2] === 'private.'\n };\n\n };\n\n /**\n * Get the internal channel name of supplied string\n * @private\n * @param {[type]} original [description]\n * @param {Boolean} isPrivate [description]\n * @return {[type]} [description]\n */\n ChatEngine.augmentChannel = (original = new Date().getTime(), isPrivate = true) => {\n\n let channel = original.toString();\n\n // public.* has PubNub permissions for everyone to read and write\n // private.* is totally locked down and users must be granted access one by one\n let chanPrivString = 'public.';\n\n if (isPrivate) {\n chanPrivString = 'private.';\n }\n\n if (channel.indexOf(ChatEngine.ceConfig.globalChannel) === -1) {\n channel = [ChatEngine.ceConfig.globalChannel, 'chat', chanPrivString, channel].join('#');\n }\n\n return channel;\n\n };\n\n /**\n * Connect to realtime service and create instance of {@link Me}\n * @method ChatEngine#connect\n * @param {String} uuid A unique string for {@link Me}. It can be a device id, username, user id, email, etc.\n * @param {Object} state An object containing information about this client ({@link Me}). This JSON object is sent to all other clients on the network, so no passwords!\n * @param {String} [authKey] A authentication secret. Will be sent to authentication backend for validation. This is usually an access token or password. This is different from UUID as a user can have a single UUID but multiple auth keys.\n * @param {Object} [authData] Additional data to send to the authentication endpoint to help verify a valid session. ChatEngine SDK does not make use of this, but you might!\n * @fires $\".\"connected\n */\n ChatEngine.connect = (uuid, state = {}, authKey = false, authData) => {\n\n // this creates a user known as Me and\n // connects to the global chatroom\n\n pnConfig.uuid = uuid;\n\n pnConfig.authKey = authKey || pnConfig.uuid;\n\n let restoreSession = () => {\n\n let groups = ['custom', 'rooms', 'system'];\n\n groups.forEach((group) => {\n\n let channelGroup = [ceConfig.globalChannel, pnConfig.uuid, group].join('#');\n\n ChatEngine.pubnub.channelGroups.listChannels({\n channelGroup\n }, (status, response) => {\n\n if (status.error) {\n console.log('operation failed w/ error:', status);\n return;\n }\n\n response.channels.forEach((channel) => {\n\n ChatEngine.me.addChatToSession({\n channel,\n private: ChatEngine.parseChannel(channel).private,\n group\n });\n\n });\n\n });\n\n });\n\n };\n\n let complete = () => {\n\n ChatEngine.pubnub = new PubNub(pnConfig);\n\n // create a new chat to use as global chat\n // we don't do auth on this one because it's assumed to be done with the /auth request below\n ChatEngine.global = new ChatEngine.Chat(ceConfig.globalChannel, false, true, {}, 'system');\n\n // build the current user\n ChatEngine.me = new Me(ChatEngine, pnConfig.uuid, authData);\n ChatEngine.me.update(state);\n\n /**\n * Fired when a {@link Me} has been created within ChatEngine.\n * @event ChatEngine#$\".\"created\".\"me\n * @example\n * ChatEngine.on('$.created.me', (data, me) => {\n * console.log('Me was created', me);\n * });\n */\n ChatEngine.me.onConstructed();\n\n ChatEngine.global.on('$.connected', () => {\n\n /**\n * Fired when ChatEngine is connected to the internet and ready to go!\n * @event ChatEngine#$\".\"ready\n * @example\n * ChatEngine.on('$.ready', (data) => {\n * let me = data.me;\n * })\n */\n ChatEngine._emit('$.ready', {\n me: ChatEngine.me\n });\n\n ChatEngine.global.getUserUpdates();\n\n let chanGroups = [\n ceConfig.globalChannel + '#' + ChatEngine.me.uuid + '#rooms',\n ceConfig.globalChannel + '#' + ChatEngine.me.uuid + '#system',\n ceConfig.globalChannel + '#' + ChatEngine.me.uuid + '#custom'\n ];\n\n // listen to all PubNub events for this Chat\n ChatEngine.pubnub.addListener({\n presence: (payload) => {\n\n if (ChatEngine.chats[payload.channel]) {\n ChatEngine.chats[payload.channel].onPresence(payload);\n }\n\n }\n });\n\n ChatEngine.pubnub.subscribe({\n channelGroups: chanGroups,\n withPresence: true\n });\n\n ChatEngine.ready = true;\n\n restoreSession();\n\n });\n\n /**\n Fires when PubNub network connection changes.\n\n @private\n @param {Object} statusEvent The response status\n */\n ChatEngine.pubnub.addListener({\n status: (statusEvent) => {\n\n /**\n * SDK detected that network is online.\n * @event ChatEngine#$\".\"network\".\"up\".\"online\n */\n\n /**\n * SDK detected that network is down.\n * @event ChatEngine#$\".\"network\".\"down\".\"offline\n */\n\n /**\n * A subscribe event experienced an exception when running.\n * @event ChatEngine#$\".\"network\".\"down\".\"issue\n */\n\n /**\n * SDK was able to reconnect to pubnub.\n * @event ChatEngine#$\".\"network\".\"up\".\"reconnected\n */\n\n /**\n * SDK subscribed with a new mix of channels.\n * @event ChatEngine#$\".\"network\".\"up\".\"connected\n */\n\n /**\n * JSON parsing crashed.\n * @event ChatEngine#$\".\"network\".\"down\".\"malformed\n */\n\n /**\n * Server rejected the request.\n * @event ChatEngine#$\".\"network\".\"down\".\"badrequest\n */\n\n /**\n * If using decryption strategies and the decryption fails.\n * @event ChatEngine#$\".\"network\".\"down\".\"decryption\n */\n\n /**\n * Request timed out.\n * @event ChatEngine#$\".\"network\".\"down\".\"timeout\n */\n\n /**\n * PAM permission failure.\n * @event ChatEngine#$\".\"network\".\"down\".\"denied\n */\n\n // map the pubnub events into chat engine events\n let categories = {\n PNNetworkUpCategory: 'up.online',\n PNNetworkDownCategory: 'down.offline',\n PNNetworkIssuesCategory: 'down.issue',\n PNReconnectedCategory: 'up.reconnected',\n PNConnectedCategory: 'up.connected',\n PNAccessDeniedCategory: 'down.denied',\n PNMalformedResponseCategory: 'down.malformed',\n PNBadRequestCategory: 'down.badrequest',\n PNDecryptionErrorCategory: 'down.decryption',\n PNTimeoutCategory: 'down.timeout'\n };\n\n let eventName = ['$', 'network', categories[statusEvent.category] || 'other'].join('.');\n\n if (statusEvent.affectedChannels) {\n statusEvent.affectedChannels.forEach((channel) => {\n\n let chat = ChatEngine.chats[channel];\n\n if (chat) {\n // connected category tells us the chat is ready\n if (statusEvent.category === 'PNConnectedCategory') {\n chat.onConnectionReady();\n }\n\n // trigger the network events\n chat.trigger(eventName, statusEvent);\n\n } else {\n ChatEngine._emit(eventName, statusEvent);\n }\n });\n } else {\n ChatEngine._emit(eventName, statusEvent);\n }\n }\n });\n };\n\n async.parallel([\n (next) => {\n ChatEngine.request('post', 'bootstrap').then(() => {\n next(null);\n }).catch(next);\n },\n (next) => {\n ChatEngine.request('post', 'user_read').then(() => {\n next(null);\n }).catch(next);\n },\n (next) => {\n ChatEngine.request('post', 'user_write').then(() => {\n next(null);\n }).catch(next);\n },\n (next) => {\n ChatEngine.request('post', 'group').then(complete).catch(next);\n }\n ], (error) => {\n if (error) {\n ChatEngine.throwError(ChatEngine, '_emit', 'auth', new Error('There was a problem logging into the auth server (' + ceConfig.endpoint + ').'), { error });\n }\n });\n\n };\n\n /**\n * The {@link Chat} class.\n * @member {Chat} Chat\n * @memberof ChatEngine\n * @see {@link Chat}\n */\n ChatEngine.Chat = function (...args) {\n\n let internalChannel = ChatEngine.augmentChannel(args[0], args[1]);\n\n if (ChatEngine.chats[internalChannel]) {\n return ChatEngine.chats[internalChannel];\n } else {\n\n let newChat = new Chat(ChatEngine, ...args);\n\n /**\n * Fired when a {@link Chat} has been created within ChatEngine.\n * @event ChatEngine#$\".\"created\".\"chat\n * @example\n * ChatEngine.on('$.created.chat', (data, chat) => {\n * console.log('Chat was created', chat);\n * });\n */\n newChat.onConstructed();\n\n return newChat;\n\n }\n\n };\n\n /**\n * The {@link User} class.\n * @member {User} User\n * @memberof ChatEngine\n * @see {@link User}\n */\n ChatEngine.User = function (...args) {\n\n if (ChatEngine.me.uuid === args[0]) {\n return ChatEngine.me;\n } else if (ChatEngine.users[args[0]]) {\n return ChatEngine.users[args[0]];\n } else {\n\n let newUser = new User(ChatEngine, ...args);\n\n /**\n * Fired when a {@link User} has been created within ChatEngine.\n * @event ChatEngine#$\".\"created\".\"user\n * @example\n * ChatEngine.on('$.created.user', (data, user) => {\n * console.log('Chat was created', user);\n * });\n */\n newUser.onConstructed();\n\n return newUser;\n\n }\n\n };\n\n return ChatEngine;\n\n};\n"},{"id":52,"identifier":"/Users/ian/Development/chat-engine/node_modules/json-loader/index.js!/Users/ian/Development/chat-engine/package.json","name":"./package.json","index":30,"index2":28,"size":1344,"cacheable":true,"built":true,"optional":false,"prefetched":false,"chunks":[0],"assets":[],"issuer":"/Users/ian/Development/chat-engine/src/bootstrap.js","issuerId":31,"issuerName":"./src/bootstrap.js","profile":{"factory":87,"building":4},"failed":false,"errors":0,"warnings":0,"reasons":[{"moduleId":31,"moduleIdentifier":"/Users/ian/Development/chat-engine/src/bootstrap.js","module":"./src/bootstrap.js","moduleName":"./src/bootstrap.js","type":"cjs require","userRequest":"../package.json","loc":"3:13-39"}],"usedExports":true,"providedExports":null,"optimizationBailout":[],"depth":2,"source":"module.exports = {\"author\":\"PubNub\",\"name\":\"chat-engine\",\"version\":\"0.8.4\",\"description\":\"ChatEngine\",\"main\":\"src/index.js\",\"scripts\":{\"deploy\":\"gulp; npm publish;\",\"docs\":\"jsdoc src/index.js -c jsdoc.json\"},\"repository\":{\"type\":\"git\",\"url\":\"git+https://github.com/pubnub/chat-engine.git\"},\"keywords\":[\"pubnub\",\"chat\",\"sdk\",\"realtime\"],\"bugs\":{\"url\":\"https://github.com/pubnub/chat-engine/issues\"},\"homepage\":\"https://github.com/pubnub/chat-engine#readme\",\"devDependencies\":{\"body-parser\":\"^1.17.2\",\"chai\":\"^3.5.0\",\"chat-engine-typing-indicator\":\"0.0.x\",\"docdash\":\"^0.4.0\",\"es6-promise\":\"^4.1.1\",\"eslint\":\"^4.7.1\",\"eslint-config-airbnb\":\"^15.1.0\",\"eslint-plugin-import\":\"^2.7.0\",\"express\":\"^4.15.3\",\"gulp\":\"^3.9.1\",\"gulp-clean\":\"^0.3.2\",\"gulp-eslint\":\"^4.0.0\",\"gulp-istanbul\":\"^1.1.2\",\"gulp-jsdoc3\":\"^1.0.1\",\"gulp-mocha\":\"^3.0.1\",\"gulp-rename\":\"^1.2.2\",\"gulp-surge\":\"^0.1.0\",\"gulp-uglify\":\"^2.0.0\",\"gulp-uglify-es\":\"^0.1.3\",\"http-server\":\"^0.10.0\",\"isparta\":\"^4.0.0\",\"jsdoc\":\"^3.5.5\",\"mocha\":\"^3.1.2\",\"proxyquire\":\"^1.8.0\",\"pubnub-functions-mock\":\"^0.0.6\",\"request\":\"^2.82.0\",\"run-sequence\":\"^2.2.0\",\"sinon\":\"^4.0.0\",\"stats-webpack-plugin\":\"^0.6.1\",\"surge\":\"^0.19.0\",\"uglifyjs-webpack-plugin\":\"^1.0.1\",\"webpack\":\"^3.6.0\",\"webpack-stream\":\"^4.0.0\"},\"dependencies\":{\"async\":\"^2.1.2\",\"axios\":\"^0.16.2\",\"eventemitter2\":\"^2.2.1\",\"pubnub\":\"^4.17.0\"}}"},{"id":54,"identifier":"/Users/ian/Development/chat-engine/src/components/chat.js","name":"./src/components/chat.js","index":33,"index2":84,"size":21105,"cacheable":true,"built":true,"optional":false,"prefetched":false,"chunks":[0],"assets":[],"issuer":"/Users/ian/Development/chat-engine/src/bootstrap.js","issuerId":31,"issuerName":"./src/bootstrap.js","profile":{"factory":15,"building":54,"dependencies":16},"failed":false,"errors":0,"warnings":0,"reasons":[{"moduleId":31,"moduleIdentifier":"/Users/ian/Development/chat-engine/src/bootstrap.js","module":"./src/bootstrap.js","moduleName":"./src/bootstrap.js","type":"cjs require","userRequest":"./components/chat","loc":"6:13-41"}],"usedExports":true,"providedExports":null,"optimizationBailout":[],"depth":2,"source":"const async = require('async');\nconst Emitter = require('../modules/emitter');\nconst Event = require('../components/event');\nconst Search = require('../components/search');\n\n/**\n This is the root {@link Chat} class that represents a chat room\n\n @param {String} [channel=new Date().getTime()] A unique identifier for this chat {@link Chat}. The channel is the unique name of a {@link Chat}, and is usually something like \"The Watercooler\", \"Support\", or \"Off Topic\". See [PubNub Channels](https://support.pubnub.com/support/solutions/articles/14000045182-what-is-a-channel-).\n @param {Boolean} [isPrivate=true] Attempt to authenticate ourselves before connecting to this {@link Chat}.\n @param {Boolean} [autoConnect=true] Connect to this chat as soon as its initiated. If set to ```false```, call the {@link Chat#connect} method to connect to this {@link Chat}.\n @param {String} [group='default'] Groups chat into a \"type\". This is the key which chats will be grouped into within {@link ChatEngine.session} object.\n @class Chat\n @extends Emitter\n @extends RootEmitter\n @fires Chat#$\".\"ready\n @fires Chat#$\".\"state\n @fires Chat#$\".\"online\".\"*\n @fires Chat#$\".\"offline\".\"*\n */\nclass Chat extends Emitter {\n\n constructor(chatEngine, channel = new Date().getTime(), isPrivate = false, autoConnect = true, meta = {}, group = 'custom') {\n\n super(chatEngine);\n\n this.chatEngine = chatEngine;\n\n this.name = 'Chat';\n\n this.meta = meta;\n\n this.group = group;\n\n /**\n * Excludes all users from reading or writing to the {@link chat} unless they have been explicitly invited via {@link Chat#invite};\n * @type Boolean\n * @readonly\n */\n this.isPrivate = isPrivate;\n\n /**\n * A string identifier for the Chat room. Any chat with an identical channel will be able to communicate with one another.\n * @type String\n * @readonly\n * @see [PubNub Channels](https://support.pubnub.com/support/solutions/articles/14000045182-what-is-a-channel-)\n */\n\n this.meta = {};\n\n /**\n * Excludes all users from reading or writing to the {@link chat} unless they have been explicitly invited via {@link Chat#invite};\n * @type Boolean\n * @readonly\n */\n this.isPrivate = isPrivate;\n\n this.channel = this.chatEngine.augmentChannel(channel, this.isPrivate);\n\n /**\n A list of users in this {@link Chat}. Automatically kept in sync as users join and leave the chat.\n Use [$.join](/Chat.html#event:$%2522.%2522join) and related events to get notified when this changes\n\n @type Object\n @readonly\n */\n this.users = {};\n\n /**\n * Boolean value that indicates of the Chat is connected to the network\n * @type {Boolean}\n */\n this.connected = false;\n\n this.chatEngine.chats[this.channel] = this;\n\n if (autoConnect) {\n this.connect();\n }\n\n return this;\n\n }\n\n /**\n Updates list of {@link User}s in this {@link Chat}\n based on who is online now.\n\n @private\n @param {Object} status The response status\n @param {Object} response The response payload object\n */\n onHereNow(status, response) {\n\n if (status.error) {\n\n /**\n * There was a problem fetching the presence of this chat\n * @event Chat#$\".\"error\".\"presence\n */\n this.chatEngine.throwError(this, 'trigger', 'presence', new Error('Getting presence of this Chat. Make sure PubNub presence is enabled for this key'), status);\n\n } else {\n\n // get the list of occupants in this channel\n let occupants = response.channels[this.channel].occupants;\n\n // format the userList for rltm.js standard\n occupants.forEach((occupant) => {\n this.userUpdate(occupant.uuid, occupant.state);\n });\n\n }\n\n }\n\n /**\n * Turns a {@link Chat} into a JSON representation.\n * @return {Object}\n */\n objectify() {\n\n return {\n channel: this.channel,\n group: this.group,\n private: this.isPrivate,\n meta: this.meta\n };\n\n }\n\n /**\n * Invite a user to this Chat. Authorizes the invited user in the Chat and sends them an invite via {@link User#direct}.\n * @param {User} user The {@link User} to invite to this chatroom.\n * @fires Me#event:$\".\"invite\n * @example\n * // one user running ChatEngine\n * let secretChat = new ChatEngine.Chat('secret-channel');\n * secretChat.invite(someoneElse);\n *\n * // someoneElse in another instance of ChatEngine\n * me.direct.on('$.invite', (payload) => {\n * let secretChat = new ChatEngine.Chat(payload.data.channel);\n * });\n */\n invite(user) {\n\n this.chatEngine.request('post', 'invite', {\n to: user.uuid,\n chat: this.objectify()\n })\n .then(() => {\n\n let send = () => {\n\n /**\n * Notifies {@link Me} that they've been invited to a new private {@link Chat}.\n * Fired by the {@link Chat#invite} method.\n * @event Me#$\".\"invite\n * @tutorial private\n * @example\n * me.direct.on('$.invite', (payload) => {\n * let privChat = new ChatEngine.Chat(payload.data.channel));\n * });\n */\n user.direct.emit('$.invite', {\n channel: this.channel\n });\n\n };\n\n if (!user.direct.connected) {\n user.direct.connect();\n user.direct.on('$.connected', send);\n } else {\n send();\n }\n\n })\n .catch((error) => {\n this.chatEngine.throwError(this, 'trigger', 'auth', new Error('Something went wrong while making a request to authentication server.'), { error });\n });\n\n }\n\n /**\n Keep track of {@link User}s in the room by subscribing to PubNub presence events.\n\n @private\n @param {Object} data The PubNub presence response for this event\n */\n onPresence(presenceEvent) {\n\n // make sure channel matches this channel\n\n // someone joins channel\n if (presenceEvent.action === 'join') {\n\n let user = this.createUser(presenceEvent.uuid, presenceEvent.state);\n\n /**\n * Fired when a {@link User} has joined the room.\n *\n * @event Chat#$\".\"online\".\"join\n * @param {Object} data The payload returned by the event\n * @param {User} data.user The {@link User} that came online\n * @example\n * chat.on('$.join', (data) => {\n * console.log('User has joined the room!', data.user);\n * });\n */\n\n // It's possible for PubNub to send us both a join and have the user appear in here_now\n // Avoid firing duplicate $.online events.\n if (!this.users[user.uuid]) {\n this.trigger('$.online.join', { user });\n }\n\n }\n\n // someone leaves channel\n if (presenceEvent.action === 'leave') {\n this.userLeave(presenceEvent.uuid);\n }\n\n // someone timesout\n if (presenceEvent.action === 'timeout') {\n this.userDisconnect(presenceEvent.uuid);\n }\n\n // someone's state is updated\n if (presenceEvent.action === 'state-change') {\n this.userUpdate(presenceEvent.uuid, presenceEvent.state);\n }\n\n\n }\n\n update(data) {\n\n let oldMeta = this.meta || {};\n this.meta = Object.assign(oldMeta, data);\n\n this.chatEngine.request('post', 'chat', {\n chat: this.objectify()\n }).then(() => {\n }).catch((error) => {\n this.chatEngine.throwError(this, 'trigger', 'auth', new Error('Something went wrong while making a request to authentication server.'), { error });\n });\n\n }\n\n /**\n * Send events to other clients in this {@link User}.\n * Events are trigger over the network and all events are made\n * on behalf of {@link Me}\n *\n * @param {String} event The event name\n * @param {Object} data The event payload object\n * @example\n * chat.emit('custom-event', {value: true});\n * chat.on('custom-event', (payload) => {\n * console.log(payload.sender.uuid, 'emitted the value', payload.data.value);\n * });\n */\n emit(event, data) {\n if (event === 'message' && typeof data !== 'object') {\n throw new Error('the payload has to be an object');\n }\n\n // create a standardized payload object\n let payload = {\n data, // the data supplied from params\n sender: this.chatEngine.me.uuid, // my own uuid\n chat: this, // an instance of this chat\n event,\n chatengineSDK: this.chatEngine.package.version\n };\n\n // run the plugin queue to modify the event\n this.runPluginQueue('emit', event, (next) => {\n next(null, payload);\n }, (err, pluginResponse) => {\n\n // remove chat otherwise it would be serialized\n // instead, it's rebuilt on the other end.\n // see this.trigger\n delete pluginResponse.chat;\n\n // publish the event and data over the configured channel\n\n // ensure the event exists within the global space\n this.events[event] = this.events[event] || new Event(this.chatEngine, this, event);\n\n this.events[event].publish(pluginResponse);\n\n });\n\n }\n\n /**\n Add a user to the {@link Chat}, creating it if it doesn't already exist.\n\n @private\n @param {String} uuid The user uuid\n @param {Object} state The user initial state\n @param {Boolean} trigger Force a trigger that this user is online\n */\n createUser(uuid, state) {\n\n // Ensure that this user exists in the global list\n // so we can reference it from here out\n this.chatEngine.users[uuid] = this.chatEngine.users[uuid] || new this.chatEngine.User(uuid);\n this.chatEngine.users[uuid].assign(state);\n\n // trigger the join event over this chatroom\n if (!this.users[uuid]) {\n\n /**\n * Broadcast that a {@link User} has come online. This is when\n * the framework firsts learn of a user. This can be triggered\n * by, ```$.join```, or other network events that\n * notify the framework of a new user.\n *\n * @event Chat#$\".\"online\".\"here\n * @param {Object} data The payload returned by the event\n * @param {User} data.user The {@link User} that came online\n * @example\n * chat.on('$.online.here', (data) => {\n * console.log('User has come online:', data.user);\n * });\n */\n\n this.trigger('$.online.here', {\n user: this.chatEngine.users[uuid]\n });\n\n }\n\n // store this user in the chatroom\n this.users[uuid] = this.chatEngine.users[uuid];\n\n // return the instance of this user\n return this.chatEngine.users[uuid];\n\n }\n\n /**\n * Update a user's state.\n * @private\n * @param {String} uuid The {@link User} uuid\n * @param {Object} state State to update for the user\n */\n userUpdate(uuid, state) {\n\n // ensure the user exists within the global space\n this.chatEngine.users[uuid] = this.chatEngine.users[uuid] || new this.chatEngine.User(uuid);\n\n // if we don't know about this user\n if (!this.users[uuid]) {\n // do the whole join thing\n this.createUser(uuid, state);\n }\n\n // update this user's state in this chatroom\n this.users[uuid].assign(state);\n\n /**\n * Broadcast that a {@link User} has changed state.\n * @event ChatEngine#$\".\"state\n * @param {Object} data The payload returned by the event\n * @param {User} data.user The {@link User} that changed state\n * @param {Object} data.state The new user state\n * @example\n * ChatEngine.on('$.state', (data) => {\n * console.log('User has changed state:', data.user, 'new state:', data.state);\n * });\n */\n this.chatEngine._emit('$.state', {\n user: this.users[uuid],\n state: this.users[uuid].state\n });\n\n }\n\n /**\n * Leave from the {@link Chat} on behalf of {@link Me}. Disconnects from the {@link Chat} and will stop\n * receiving events.\n * @fires Chat#event:$\".\"offline\".\"leave\n * @example\n * chat.leave();\n */\n leave() {\n\n // unsubscribe from the channel locally\n this.chatEngine.pubnub.unsubscribe({\n channels: [this.channel]\n });\n\n this.chatEngine.request('post', 'leave', { chat: this.objectify() })\n .then(() => {\n\n this.connected = false;\n\n this.trigger('$.disconnected');\n\n this.chatEngine.me.sync.emit('$.session.chat.leave', { subject: this.objectify() });\n\n })\n .catch((error) => {\n this.chatEngine.throwError(this, 'trigger', 'auth', new Error('Something went wrong while making a request to chat server.'), { error });\n });\n\n }\n\n /**\n Perform updates when a user has left the {@link Chat}.\n\n @private\n */\n userLeave(uuid) {\n\n // make sure this event is real, user may have already left\n if (this.users[uuid]) {\n\n // if a user leaves, trigger the event\n\n /**\n * Fired when a {@link User} intentionally leaves a {@link Chat}.\n *\n * @event Chat#$\".\"offline\".\"leave\n * @param {Object} data The data payload from the event\n * @param {User} user The {@link User} that has left the room\n * @example\n * chat.on('$.offline.leave', (data) => {\n * console.log('User left the room manually:', data.user);\n * });\n */\n this.trigger('$.offline.leave', {\n user: this.users[uuid]\n });\n\n // remove the user from the local list of users\n delete this.users[uuid];\n\n // we don't remove the user from the global list,\n // because they may be online in other channels\n\n } else {\n\n // that user isn't in the user list\n // we never knew about this user or they already left\n\n // console.log('user already left');\n }\n }\n\n /**\n Fired when a user disconnects from the {@link Chat}\n\n @private\n @param {String} uuid The uuid of the {@link Chat} that left\n */\n userDisconnect(uuid) {\n\n // make sure this event is real, user may have already left\n if (this.users[uuid]) {\n\n /**\n * Fired specifically when a {@link User} looses network connection\n * to the {@link Chat} involuntarily.\n *\n * @event Chat#$\".\"offline\".\"disconnect\n * @param {Object} data The {@link User} that disconnected\n * @param {Object} data.user The {@link User} that disconnected\n * @example\n * chat.on('$.offline.disconnect', (data) => {\n * console.log('User disconnected from the network:', data.user);\n * });\n */\n\n this.trigger('$.offline.disconnect', { user: this.users[uuid] });\n }\n\n }\n\n /**\n Set the state for {@link Me} within this {@link User}.\n Broadcasts the ```$.state``` event on other clients\n\n @private\n @param {Object} state The new state {@link Me} will have within this {@link User}\n */\n setState(state) {\n this.chatEngine.pubnub.setState({ state, channels: [this.chatEngine.global.channel] }, () => {\n // handle status, response\n });\n }\n\n /**\n Search through previously emitted events. Parameters act as AND operators. Returns an instance of the emitter based {@link History}. Will\n which will emit all old events unless ```config.event``` is supplied.\n @param {Object} [config] Our configuration for the PubNub history request. See the [PubNub History](https://www.pubnub.com/docs/web-javascript/storage-and-history) docs for more information on these parameters.\n @param {Event} [config.event] The {@link Event} to search for.\n @param {User} [config.sender] The {@link User} who sent the message.\n @param {Number} [config.limit=20] The maximum number of results to return that match search criteria. Search will continue operating until it returns this number of results or it reached the end of history.\n @param {Number} [config.start=0] The timetoken to begin searching between.\n @param {Number} [config.end=0] The timetoken to end searching between.\n @param {Boolean} [config.reverse=false] Search oldest messages first.\n @return {Search}\n @example\n chat.search({\n event: 'my-custom-event',\n sender: ChatEngine.me,\n limit: 20\n }).on('my-custom-event', (event) => {\n console.log('this is an old event!', event);\n }).on('$.search.finish', () => {\n console.log('we have all our results!')\n });\n */\n search(config) {\n return new Search(this.chatEngine, this, config);\n }\n\n onConnectionReady() {\n\n /**\n * Broadcast that the {@link Chat} is connected to the network.\n * @event Chat#$\".\"connected\n * @example\n * chat.on('$.connected', () => {\n * console.log('chat is ready to go!');\n * });\n */\n this.trigger('$.connected');\n\n this.chatEngine.me.sync.emit('$.session.chat.join', { subject: this.objectify() });\n\n this.connected = true;\n\n // add self to list of users\n this.users[this.chatEngine.me.uuid] = this.chatEngine.me;\n\n // trigger my own online event\n this.trigger('$.online.join', {\n user: this.chatEngine.me\n });\n\n // global channel updates are triggered manually, only get presence on custom chats\n if (this.channel !== this.chatEngine.global.channel && this.group === 'custom') {\n\n this.getUserUpdates();\n\n // we may miss updates, so call this again 5 seconds later\n setTimeout(() => {\n this.getUserUpdates();\n }, 5000);\n\n }\n\n }\n\n getUserUpdates() {\n\n // get a list of users online now\n // ask PubNub for information about connected users in this channel\n this.chatEngine.pubnub.hereNow({\n channels: [this.channel],\n includeUUIDs: true,\n includeState: true\n }, this.onHereNow.bind(this));\n\n }\n\n /**\n * Connect to PubNub servers to initialize the chat.\n * @example\n * // create a new chatroom, but don't connect to it automatically\n * let chat = new Chat('some-chat', false)\n *\n * // connect to the chat when we feel like it\n * chat.connect();\n */\n connect() {\n\n async.waterfall([\n (next) => {\n if (!this.chatEngine.pubnub) {\n next('You must call ChatEngine.connect() and wait for the $.ready event before creating new Chats.');\n } else {\n next();\n }\n },\n (next) => {\n\n this.chatEngine.request('post', 'grant', { chat: this.objectify() })\n .then(() => {\n next();\n })\n .catch(next);\n\n },\n (next) => {\n\n this.chatEngine.request('post', 'join', { chat: this.objectify() })\n .then(() => {\n next();\n })\n .catch(next);\n\n },\n (next) => {\n\n this.chatEngine.request('get', 'chat', {}, { channel: this.channel })\n .then((response) => {\n\n if (response.data.found) {\n this.meta = response.data.chat.meta;\n } else {\n this.update(this.meta);\n }\n\n this.onConnectionReady();\n\n })\n .catch(next);\n\n }\n ], (error) => {\n this.chatEngine.throwError(this, 'trigger', 'auth', new Error('Something went wrong while making a request to authentication server.'), { error });\n });\n\n }\n\n}\n\nmodule.exports = Chat;\n"},{"id":60,"identifier":"/Users/ian/Development/chat-engine/src/components/search.js","name":"./src/components/search.js","index":52,"index2":83,"size":6596,"cacheable":true,"built":true,"optional":false,"prefetched":false,"chunks":[0],"assets":[],"issuer":"/Users/ian/Development/chat-engine/src/components/chat.js","issuerId":54,"issuerName":"./src/components/chat.js","profile":{"factory":16,"building":20,"dependencies":0},"failed":false,"errors":0,"warnings":0,"reasons":[{"moduleId":54,"moduleIdentifier":"/Users/ian/Development/chat-engine/src/components/chat.js","module":"./src/components/chat.js","moduleName":"./src/components/chat.js","type":"cjs require","userRequest":"../components/search","loc":"4:15-46"}],"usedExports":true,"providedExports":null,"optimizationBailout":[],"depth":3,"source":"const Emitter = require('../modules/emitter');\nconst eachSeries = require('async/eachSeries');\n/**\nReturned by {@link Chat#search}. This is our Search class which allows one to search the backlog of messages.\n\n\n Powered by [PubNub History](https://www.pubnub.com/docs/web-javascript/storage-and-history).\n\n @class Search\n @extends Emitter\n @extends RootEmitter\n @param chatEngine\n @param chat\n @param config\n */\nclass Search extends Emitter {\n\n constructor(chatEngine, chat, config = {}) {\n\n super();\n\n this.chatEngine = chatEngine;\n\n /**\n Handy property to identify what this class is.\n @type String\n */\n this.name = 'Search';\n\n /**\n The {@link Chat} used for searching.\n @type Chat\n */\n this.chat = chat;\n\n /**\n An object containing configuration parameters supplied by {@link Chat#search}. See {@link Chat#search} for possible parameters.\n @type {Object}\n */\n this.config = config;\n this.config.event = config.event;\n this.config.limit = config.limit || 20;\n this.config.channel = this.chat.channel;\n this.config.includeTimetoken = true;\n this.config.stringifiedTimeToken = true;\n this.config.count = this.config.count || 100;\n\n this.config.pages = this.config.pages || 10;\n\n this.needleCount = 0;\n\n this.firstTT = 0;\n this.lastTT = 0;\n\n this.firstPage = true;\n\n /**\n * @private\n */\n this.sortHistory = (messages, desc) => {\n\n messages.sort((a, b) => {\n let e1 = desc ? b : a;\n let e2 = desc ? a : b;\n return parseInt(e1.timetoken, 10) - parseInt(e2.timetoken, 10);\n });\n\n return messages;\n\n };\n\n /**\n * Call PubNub history in a loop.\n * Unapologetically stolen from https://www.pubnub.com/docs/web-javascript/storage-and-history\n * @private\n */\n this.page = (pageDone) => {\n\n /**\n * Requesting another page from PubNub History.\n * @event Search#$\".\"page\".\"request\n */\n this._emit('$.search.page.request');\n\n // only set start if this is the first call and the user hasn't set it themselves\n this.config.start = this.config.reverse ? this.lastTT : this.firstTT;\n\n this.firstPage = false;\n\n this.chatEngine.pubnub.history(this.config, (status, response) => {\n\n /**\n * PubNub History returned a response.\n * @event Search#$\".\"page\".\"response\n */\n this._emit('$.search.page.response');\n\n if (status.error) {\n\n /**\n * There was a problem fetching the history of this chat\n * @event Chat#$\".\"error\".\"history\n */\n this.chatEngine.throwError(this, 'trigger', 'search', new Error('There was a problem searching history. Make sure your request parameters are valid and history is enabled for this PubNub key.'), status);\n\n } else {\n\n // timetoken of the first message in response\n this.firstTT = response.startTimeToken;\n // timetoken of the last message in response\n this.lastTT = response.endTimeToken;\n\n response.messages = this.sortHistory(response.messages);\n\n pageDone(response);\n\n }\n\n });\n };\n\n let eventFilter = (event) => {\n return {\n middleware: {\n on: {\n '*': (payload, next) => {\n let matches = payload && payload.event && payload.event === event;\n next(!matches, payload);\n }\n }\n }\n };\n };\n\n let senderFilter = (user) => {\n return {\n middleware: {\n on: {\n '*': (payload, next) => {\n let matches = payload && payload.sender && payload.sender.uuid === user.uuid;\n next(!matches, payload);\n }\n }\n }\n };\n };\n\n this.needleCount = 0;\n\n /**\n * @private\n */\n this.triggerHistory = (message, cb) => {\n\n if (this.needleCount < this.config.limit) {\n\n this.trigger(message.entry.event, message.entry, (reject) => {\n\n if (!reject) {\n this.needleCount += 1;\n }\n cb();\n\n });\n\n } else {\n cb();\n }\n\n };\n\n this.maxPage = 10;\n this.numPage = 0;\n\n this.next = () => {\n\n this.maxPage = this.maxPage + this.config.pages;\n\n this.find();\n\n };\n\n /**\n * @private\n */\n this.find = () => {\n\n this.page((response) => {\n\n if (!this.config.reverse) {\n response.messages.reverse();\n }\n\n eachSeries(response.messages, this.triggerHistory, () => {\n\n if (this.numPage === this.maxPage) {\n this._emit('$.search.pause');\n } else if (\n response.messages &&\n response.messages.length === this.config.count &&\n this.needleCount < this.config.limit) {\n this.numPage += 1;\n this.find();\n } else {\n\n /**\n * Search has returned all results or reached the end of history.\n * @event Search#$\".\"search\".\"finish\n */\n this._emit('$.search.finish');\n }\n\n });\n\n });\n\n return this;\n\n };\n\n if (this.config.event) {\n this.plugin(eventFilter(this.config.event));\n }\n\n if (this.config.sender) {\n this.plugin(senderFilter(this.config.sender));\n }\n\n /**\n * Search has started.\n * @event Search#$\".\"search\".\"start\n */\n this._emit('$.search.start');\n this.find();\n\n }\n\n}\n\nmodule.exports = Search;\n"},{"id":88,"identifier":"/Users/ian/Development/chat-engine/src/components/me.js","name":"./src/components/me.js","index":87,"index2":86,"size":4890,"cacheable":true,"built":true,"optional":false,"prefetched":false,"chunks":[0],"assets":[],"issuer":"/Users/ian/Development/chat-engine/src/bootstrap.js","issuerId":31,"issuerName":"./src/bootstrap.js","profile":{"factory":15,"building":60,"dependencies":1},"failed":false,"errors":0,"warnings":0,"reasons":[{"moduleId":31,"moduleIdentifier":"/Users/ian/Development/chat-engine/src/bootstrap.js","module":"./src/bootstrap.js","moduleName":"./src/bootstrap.js","type":"cjs require","userRequest":"./components/me","loc":"7:11-37"}],"usedExports":true,"providedExports":null,"optimizationBailout":[],"depth":2,"source":"const User = require('./user');\n\n/**\n Represents the client connection as a special {@link User} with write permissions.\n Has the ability to update it's state on the network. An instance of\n {@link Me} is returned by the ```ChatEngine.connect()```\n method.\n\n @class Me\n @extends User\n @extends Emitter\n @extends RootEmitter\n @param {String} uuid The uuid of this user\n */\nclass Me extends User {\n\n constructor(chatEngine, uuid, authData) {\n\n // call the User constructor\n super(chatEngine, uuid);\n\n this.name = 'Me';\n\n this.authData = authData;\n this.chatEngine = chatEngine;\n\n /**\n * Stores a map of {@link Chat} objects that this {@link Me} has joined across all clients.\n * @type {Object}\n */\n this.session = {};\n\n this.sync = new this.chatEngine.Chat([chatEngine.global.channel, 'user', uuid, 'me.', 'sync'].join('#'), false, true, {}, 'system');\n\n this.sync.on('$.session.chat.join', (payload) => {\n this.addChatToSession(payload.data.subject);\n });\n\n this.sync.on('$.session.chat.leave', (payload) => {\n this.removeChatFromSession(payload.data.subject);\n });\n\n return this;\n\n }\n\n // assign updates from network\n assign(state) {\n // we call \"update\" because calling \"super.assign\"\n // will direct back to \"this.update\" which creates\n // a loop of network updates\n super.update(state);\n }\n\n /**\n * Update {@link Me}'s state in a {@link Chat}. All other {@link User}s\n * will be notified of this change via ```$.state```.\n * Retrieve state at any time with {@link User#state}.\n * @param {Object} state The new state for {@link Me}\n * @param {Chat} chat An instance of the {@link Chat} where state will be updated.\n * Defaults to ```ChatEngine.global```.\n * @fires Chat#event:$\".\"state\n * @example\n * // update state\n * me.update({value: true});\n */\n update(state) {\n\n // run the root update function\n super.update(state);\n\n // publish the update over the global channel\n this.chatEngine.global.setState(state);\n\n }\n\n /**\n Stores {@link Chat} within ```ChatEngine.session``` keyed based on the ```chat.group``` property.\n @param {Object} chat JSON object representing {@link Chat}. Originally supplied via {@link Chat#objectify}.\n @private\n */\n addChatToSession(chat) {\n\n // create the chat group if it doesn't exist\n this.session[chat.group] = this.session[chat.group] || {};\n\n // check the chat exists within the global list but is not grouped\n let existingChat = this.chatEngine.chats[chat.channel];\n\n // if it exists\n if (existingChat) {\n // assign it to the group\n this.session[chat.group][chat.channel] = existingChat;\n } else {\n\n // otherwise, try to recreate it with the server information\n this.session[chat.group][chat.channel] = new this.chatEngine.Chat(chat.channel, chat.private, false, chat.meta, chat.group);\n\n /**\n Fired when another identical instance of {@link ChatEngine} and {@link Me} joins a {@link Chat} that this instance of {@link ChatEngine} is unaware of.\n Used to synchronize ChatEngine sessions between desktop and mobile, duplicate windows, etc.\n ChatEngine stores sessions on the server side identified by {@link User#uuid}.\n @event Me#$\".\"session\".\"chat\".\"join\n @example\n *\n * // Logged in as \"Ian\" in first window\n * ChatEngine.me.on('$.session.chat.join', (data) => {\n * console.log('I joined a new chat in a second window!', data.chat);\n * });\n *\n * // Logged in as \"Ian\" in second window\n * new ChatEngine.Chat('another-chat');\n */\n // this.trigger('$.session.chat.join', {\n // chat: this.session[chat.group][chat.channel]\n // });\n //\n this.trigger('$.session.chat.join', { chat: this.session[chat.group][chat.channel] });\n\n }\n\n }\n\n /**\n Removes {@link Chat} within this.session\n @private\n */\n removeChatFromSession(chat) {\n\n if (this.session[chat.group] && this.session[chat.group][chat.channel]) {\n\n chat = this.session[chat.group][chat.channel] || chat;\n\n /**\n * Fired when another identical instance of {@link ChatEngine} with an identical {@link Me} leaves a {@link Chat} via {@link Chat#leave}.\n * @event Me#$\".\"session\".\"chat\".\"leave\n */\n\n delete this.chatEngine.chats[chat.channel];\n delete this.session[chat.group][chat.channel];\n\n this.trigger('$.session.chat.leave', { chat });\n\n }\n\n }\n\n}\n\nmodule.exports = Me;\n"}],"filteredModules":77,"children":[]} \ No newline at end of file diff --git a/package.json b/package.json index d50d412f..3eb8358b 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "author": "PubNub", "name": "chat-engine", - "version": "0.8.3", + "version": "0.8.4", "description": "ChatEngine", "main": "src/index.js", "scripts": { diff --git a/setup/lib/chat-engine-setup.js b/setup/lib/chat-engine-setup.js index 54febbfe..b4e6ecde 100644 --- a/setup/lib/chat-engine-setup.js +++ b/setup/lib/chat-engine-setup.js @@ -5,4 +5,4 @@ * See https://raw.githubusercontent.com/stefanpenner/es6-promise/master/LICENSE * @version 4.1.1 */ -!function(e,n){t.exports=n()}(0,function(){"use strict";function t(t){return"function"==typeof t}function o(){var t=setTimeout;return function(){return t(i,1)}}function i(){for(var t=0;t1)for(var n=1;n{console.log(t),r(null,t)}).fail(t=>{console.log("fail",t),r(t||t.message||t)})}init(t,e){this.request("post",["api","me"],{data:{email:t.email||this.errHandle("No Email Supplied"),password:t.password||this.errHandle("No Password Supplied")}},(t,n)=>{n&&n.error?e(n.error):t?e(t):(this.session=n.result.token,e(null,n))})}startFunction({block:t,key:e},n){this.request("post",["api","v1","blocks","key",e.id,"block",t.id,"start"],{data:{block_id:t.id,key_id:e.id,action:"start"}},n)}storeSecretKey({key:t},e){this.request("put",["api","vault",t.subscribe_key,"key","secretKey"],{contentType:"application/json",data:JSON.stringify({keyName:"secretKey",key_id:t.id,subscribeKey:t.subscribe_key,value:t.secret_key})},e)}}},function(t,e,n){const r=n(8);t.exports=((t,e,n=(()=>{}),o=(()=>{}))=>{t.request("get",["api","accounts"],{data:{user_id:e}},(i,s)=>{if(i)return n("Could not get PubNub accounts. Please contact support@pubnub.com.");let u=s.result.accounts[0];o("Using account "+u.properties.company+", if this is incorrent deploy manually or log in as another user"),o("Creating new PubNub app..."),t.request("post",["api","apps"],{data:{name:"ChatEngine App",owner_id:u.id,properties:{}}},(i,s)=>{if(i)return n("Could not create new PubNub app. Please contact support@pubnub.com.");let a=s.result;o("Getting PubNub keys..."),t.request("get",["api","apps"],{data:{owner_id:u.id}},(i,s)=>{if(i)return n("Could not get PubNub keys. Please contact support@pubnub.com.");let u;s.result.forEach(t=>{t.id===a.id&&(u=t.keys[0])}),o("Enabling PubNub features..."),u.properties.name="ChatEngine Keyset",u.properties.presence=1,u.properties.history=1,u.properties.message_storage_ttl=7,u.properties.multiplexing=1,u.properties.presence_announce_max=20,u.properties.presence_debounce=2,u.properties.presence_global_here_now=1,u.properties.presence_interval=10,u.properties.presence_leave_on_disconnect=0,u.properties.blocks=1,u.properties.uls=1,u.properties.wildcardsubscribe=1,t.request("put",["api","keys",u.id],{data:u},(i,s)=>{i&&n("Could not enable PubNub features. Please contact support@pubnub.com."),r(t,e,u,n,o)})})})})})},function(t,e){t.exports=((t,e,n,r=(()=>{}),o=(()=>{}))=>{let i=null;o("Creating new PubNub Function...");t.request("post",["api","v1","blocks","key",n.id,"block"],{data:{name:"ChatEngine Function",key_id:n.id}},(e,s)=>{e&&r("Could not create new PubNub Function. Please contact support@pubnub.com."),i=s.payload;let u=$.get({url:"functions/state-to-kv.js",dataType:"text"}),a=$.get({url:"functions/auth.js",dataType:"text"}),c=$.get({url:"functions/server.js",dataType:"text"});$.when(u,a,c).then((e,s,u)=>{o("Creating new after-publish Event Handler..."),t.request("post",["api","v1","blocks","key",n.id,"event_handler"],{data:{key_id:n.id,block_id:i.id,type:"js",event:"js-after-presence",channels:"global",name:"state-to-kv",code:e[0],output:"output-state-to-kv-"+(new Date).getTime()}},(e,a)=>{e&&r("Could not create new PubNub after-publish Event Handler. Please contact support@pubnub.com."),t.request("post",["api","v1","blocks","key",n.id,"event_handler"],{data:{key_id:n.id,block_id:i.id,type:"js",event:"js-on-rest",path:"chat-engine-auth",name:"chat-engine-auth",code:s[0],output:"auth-"+Math.round((new Date).getTime())}},(e,s)=>{e&&r("Could not create new PubNub after-publish Event Handler. Please contact support@pubnub.com."),o("Creating new on-request Event Handler..."),t.request("post",["api","v1","blocks","key",n.id,"event_handler"],{data:{key_id:n.id,block_id:i.id,code:u[0],type:"js",name:"chat-engine-server",path:"chat-engine-server",event:"js-on-rest",output:"output-server-endpoint-"+Math.round((new Date).getTime())}},(e,s)=>{e?r("Could not create new Pubnub on-request Event Handler. Please contact support@pubnub.com."):(o("Starting Pubnub Function..."),t.startFunction({block:i,key:n},e=>{e?r("Could not start PubNub Function. Please contact support@pubnub.com."):(o("Adding Secret Key to Functions Vault..."),t.storeSecretKey({key:n},t=>{t?r("Could not add Secret Key to Functions Vault. Please contact support@pubnub.com"):(o("Success!"),r(null,{pub:n.publish_key,sub:n.subscribe_key}))}))}))})})})}).catch(()=>{o("Failed to fetch code")})})})},function(t,e){t.exports={findCookie:t=>{let e=null;return document.cookie.split(";").forEach(n=>{let r=n.split("=")[0],o=n.split("=")[1];r.endsWith(t)&&(e=o)}),e}}}])}); \ No newline at end of file +!function(e,n){t.exports=n()}(0,function(){"use strict";function t(t){return"function"==typeof t}function o(){var t=setTimeout;return function(){return t(i,1)}}function i(){for(var t=0;t1)for(var n=1;n{console.log(t),r(null,t)}).fail(t=>{console.log("fail",t),r(t||t.message||t)})}init(t,e){this.request("post",["api","me"],{data:{email:t.email||this.errHandle("No Email Supplied"),password:t.password||this.errHandle("No Password Supplied")}},(t,n)=>{n&&n.error?e(n.error):t?e(t):(this.session=n.result.token,e(null,n))})}startFunction({block:t,key:e},n){this.request("post",["api","v1","blocks","key",e.id,"block",t.id,"start"],{data:{block_id:t.id,key_id:e.id,action:"start"}},n)}storeSecretKey({key:t},e){this.request("put",["api","vault",t.subscribe_key,"key","secretKey"],{contentType:"application/json",data:JSON.stringify({keyName:"secretKey",key_id:t.id,subscribeKey:t.subscribe_key,value:t.secret_key})},e)}}},function(t,e,n){const r=n(8);t.exports=((t,e,n=(()=>{}),o=(()=>{}))=>{t.request("get",["api","accounts"],{data:{user_id:e}},(i,s)=>{if(i)return n("Could not get PubNub accounts. Please contact support@pubnub.com.");let u=s.result.accounts[0];o("Using account "+u.properties.company+", if this is incorrent deploy manually or log in as another user"),o("Creating new PubNub app..."),t.request("post",["api","apps"],{data:{name:"ChatEngine App",owner_id:u.id,properties:{}}},(i,s)=>{if(i)return n("Could not create new PubNub app. Please contact support@pubnub.com.");let a=s.result;o("Getting PubNub keys..."),t.request("get",["api","apps"],{data:{owner_id:u.id}},(i,s)=>{if(i)return n("Could not get PubNub keys. Please contact support@pubnub.com.");let u;s.result.forEach(t=>{t.id===a.id&&(u=t.keys[0])}),o("Enabling PubNub features..."),u.properties.name="ChatEngine Keyset",u.properties.presence=1,u.properties.history=1,u.properties.message_storage_ttl=7,u.properties.multiplexing=1,u.properties.presence_announce_max=20,u.properties.presence_debounce=2,u.properties.presence_global_here_now=1,u.properties.presence_interval=10,u.properties.presence_leave_on_disconnect=0,u.properties.blocks=1,u.properties.uls=1,u.properties.wildcardsubscribe=1,t.request("put",["api","keys",u.id],{data:u},(i,s)=>{i&&n("Could not enable PubNub features. Please contact support@pubnub.com."),r(t,e,u,n,o)})})})})})},function(t,e){t.exports=((t,e,n,r=(()=>{}),o=(()=>{}))=>{let i=null;o("Creating new PubNub Function...");t.request("post",["api","v1","blocks","key",n.id,"block"],{data:{name:"ChatEngine Function",key_id:n.id}},(e,s)=>{e&&r("Could not create new PubNub Function. Please contact support@pubnub.com."),i=s.payload;let u=$.get({url:"functions/state-to-kv.js",dataType:"text"}),a=$.get({url:"functions/auth.js",dataType:"text"}),c=$.get({url:"functions/server.js",dataType:"text"});$.when(u,a,c).then((e,s,u)=>{o("Creating new after-publish Event Handler..."),t.request("post",["api","v1","blocks","key",n.id,"event_handler"],{data:{key_id:n.id,block_id:i.id,type:"js",event:"js-after-presence",channels:"*",name:"chat-engine-state",code:e[0],output:"output-state-to-kv-"+(new Date).getTime()}},(e,a)=>{e&&r("Could not create new PubNub after-publish Event Handler. Please contact support@pubnub.com."),t.request("post",["api","v1","blocks","key",n.id,"event_handler"],{data:{key_id:n.id,block_id:i.id,type:"js",event:"js-on-rest",path:"chat-engine-auth",name:"chat-engine-auth",code:s[0],output:"auth-"+Math.round((new Date).getTime())}},(e,s)=>{e&&r("Could not create new PubNub after-publish Event Handler. Please contact support@pubnub.com."),o("Creating new on-request Event Handler..."),t.request("post",["api","v1","blocks","key",n.id,"event_handler"],{data:{key_id:n.id,block_id:i.id,code:u[0],type:"js",name:"chat-engine-server",path:"chat-engine-server",event:"js-on-rest",output:"output-server-endpoint-"+Math.round((new Date).getTime())}},(e,s)=>{e?r("Could not create new Pubnub on-request Event Handler. Please contact support@pubnub.com."):(o("Starting Pubnub Function..."),t.startFunction({block:i,key:n},e=>{e?r("Could not start PubNub Function. Please contact support@pubnub.com."):(o("Adding Secret Key to Functions Vault..."),t.storeSecretKey({key:n},t=>{t?r("Could not add Secret Key to Functions Vault. Please contact support@pubnub.com"):(o("Success!"),r(null,{pub:n.publish_key,sub:n.subscribe_key}))}))}))})})})}).catch(()=>{o("Failed to fetch code")})})})},function(t,e){t.exports={findCookie:t=>{let e=null;return document.cookie.split(";").forEach(n=>{let r=n.split("=")[0],o=n.split("=")[1];r.endsWith(t)&&(e=o)}),e}}}])}); \ No newline at end of file diff --git a/setup/lib/stats.json b/setup/lib/stats.json index b417deb4..8096f04e 100644 --- a/setup/lib/stats.json +++ b/setup/lib/stats.json @@ -1 +1 @@ -{"errors":[],"warnings":[],"version":"3.8.1","hash":"3373d3ec2b041a55fb48","publicPath":"","assetsByChunkName":{"main":"chat-engine-setup.js"},"assets":[{"name":"chat-engine-setup.js","size":15954,"chunks":[0],"chunkNames":["main"],"emitted":true},{"name":"stats.json","size":0,"chunks":[],"chunkNames":[]}],"filteredAssets":0,"entrypoints":{"main":{"chunks":[0],"assets":["chat-engine-setup.js"]}},"chunks":[{"id":0,"rendered":true,"initial":true,"entry":true,"extraAsync":false,"size":48627,"names":["main"],"files":["chat-engine-setup.js"],"hash":"1ea30526f93e00c7348d","parents":[],"modules":[{"id":0,"identifier":"/Users/ian/Development/chat-engine/setup/src/script.js","name":"./setup/src/script.js","index":0,"index2":9,"size":3577,"cacheable":true,"built":true,"optional":false,"prefetched":false,"chunks":[0],"assets":[],"issuer":null,"issuerId":null,"issuerName":null,"profile":{"factory":25,"building":49},"failed":false,"errors":0,"warnings":0,"reasons":[],"usedExports":true,"providedExports":null,"optimizationBailout":[],"depth":0,"source":"// polyfill Promise\nrequire('es6-promise/auto');\n\nconst Client = require('./client');\nconst ProvisionAccount = require('./setup_account');\nconst utils = require('./utils');\n\n\nconst extractError = (err) => {\n if (err && err.responseJSON && err.responseJSON.error) {\n return err.responseJSON.error;\n }\n};\n\nmodule.exports = class {\n\n constructor() {\n this.loginElement = $('#login');\n this.provisionElement = $('#setup');\n this.loadElement = $('#load');\n this.errorElement = $('#error');\n this.errorOutElement = $('#error-out');\n this.statusElement = $('#status');\n this.codeElement = $('#code');\n this.outputElement = $('#output');\n this.emailElement = $('#email');\n this.passwordElement = $('#password');\n\n this.loginElement.submit(this.onLoginRegister.bind(this));\n this.provisionElement.submit(this.onSetup.bind(this));\n\n this.userId = utils.findCookie('pnAdminId');\n let tokenCookie = utils.findCookie('pnAdminToken');\n\n this.client = new Client({\n session: tokenCookie,\n debug: false,\n endpoint: 'https://admin.pubnub.com'\n });\n\n if (this.userId && tokenCookie) {\n this.provisionElement.show();\n this.loginElement.hide();\n analytics.identify(this.userId);\n }\n\n }\n\n displayStatus(statusText) {\n this.statusElement.show();\n this.statusElement.append($('
  • ' + statusText + '
  • '));\n }\n\n clearErrors() {\n this.errorElement.hide();\n }\n\n raiseError(err) {\n this.errorOutElement.html(err);\n this.errorElement.show();\n }\n\n onProvisionSuccess(err, data) {\n if (err) {\n this.loadElement.hide();\n this.provisionElement.show();\n\n this.errorOutElement.html(err);\n this.errorElement.show();\n } else {\n this.loadElement.hide();\n\n let output = '';\n output += '// Make sure to import ChatEngine first!\\n';\n output += 'ChatEngine = ChatEngineCore.create({\\n';\n output += \" publishKey: '\" + data.pub + \"',\\n\";\n output += \" subscribeKey: '\" + data.sub + \"'\\n\";\n output += '});\\n';\n\n analytics.track('chat_engine_activation');\n\n this.codeElement.text(output);\n this.outputElement.show();\n }\n }\n\n onLoginRegister() {\n this.clearErrors();\n const email = this.emailElement.val();\n const password = this.passwordElement.val();\n\n if (!email || email === '') {\n this.raiseError('email not valid');\n return false;\n }\n\n if (!password || password === '') {\n this.raiseError('password not valid');\n return false;\n }\n\n this.client.init({ email, password }, (err, response) => {\n if (err) {\n this.raiseError(extractError(err));\n } else {\n this.userId = response.result.user_id;\n analytics.identify(this.userId);\n this.provisionElement.show();\n this.loginElement.hide();\n }\n });\n\n\n return false;\n }\n\n onSetup() {\n this.clearErrors();\n\n this.loadElement.show();\n this.errorElement.hide();\n this.statusElement.empty();\n\n ProvisionAccount(this.client, this.userId, this.onProvisionSuccess.bind(this), this.displayStatus.bind(this));\n\n return false;\n }\n\n};\n"},{"id":4,"identifier":"/Users/ian/Development/chat-engine/node_modules/webpack/buildin/global.js","name":"(webpack)/buildin/global.js","index":4,"index2":1,"size":488,"cacheable":true,"built":true,"optional":false,"prefetched":false,"chunks":[0],"assets":[],"issuer":"/Users/ian/Development/chat-engine/node_modules/es6-promise/dist/es6-promise.js","issuerId":2,"issuerName":"./node_modules/es6-promise/dist/es6-promise.js","profile":{"factory":4,"building":8},"failed":false,"errors":0,"warnings":0,"reasons":[{"moduleId":2,"moduleIdentifier":"/Users/ian/Development/chat-engine/node_modules/es6-promise/dist/es6-promise.js","module":"./node_modules/es6-promise/dist/es6-promise.js","moduleName":"./node_modules/es6-promise/dist/es6-promise.js","type":"cjs require","userRequest":"global","loc":"1:0-44"}],"usedExports":true,"providedExports":null,"optimizationBailout":[],"depth":3,"source":"var g;\n\n// This works in non-strict mode\ng = (function() {\n\treturn this;\n})();\n\ntry {\n\t// This works if eval is allowed (see CSP)\n\tg = g || Function(\"return this\")() || (1,eval)(\"this\");\n} catch(e) {\n\t// This works if the window reference is available\n\tif(typeof window === \"object\")\n\t\tg = window;\n}\n\n// g can still be undefined, but nothing to do about it...\n// We return undefined, instead of nothing here, so it's\n// easier to handle this case. if(!global) { ...}\n\nmodule.exports = g;\n"},{"id":5,"identifier":"ignored /Users/ian/Development/chat-engine/node_modules/es6-promise/dist vertx","name":"vertx (ignored)","index":5,"index2":2,"size":15,"cacheable":true,"built":false,"optional":true,"prefetched":false,"chunks":[0],"assets":[],"issuer":"/Users/ian/Development/chat-engine/node_modules/es6-promise/dist/es6-promise.js","issuerId":2,"issuerName":"./node_modules/es6-promise/dist/es6-promise.js","profile":{"factory":1,"building":1},"failed":false,"errors":0,"warnings":0,"reasons":[{"moduleId":2,"moduleIdentifier":"/Users/ian/Development/chat-engine/node_modules/es6-promise/dist/es6-promise.js","module":"./node_modules/es6-promise/dist/es6-promise.js","moduleName":"./node_modules/es6-promise/dist/es6-promise.js","type":"cjs require","userRequest":"vertx","loc":"138:16-26"}],"usedExports":true,"providedExports":null,"optimizationBailout":[],"depth":3},{"id":6,"identifier":"/Users/ian/Development/chat-engine/setup/src/client.js","name":"./setup/src/client.js","index":6,"index2":5,"size":2922,"cacheable":true,"built":true,"optional":false,"prefetched":false,"chunks":[0],"assets":[],"issuer":"/Users/ian/Development/chat-engine/setup/src/script.js","issuerId":0,"issuerName":"./setup/src/script.js","profile":{"factory":14,"building":18},"failed":false,"errors":0,"warnings":0,"reasons":[{"moduleId":0,"moduleIdentifier":"/Users/ian/Development/chat-engine/setup/src/script.js","module":"./setup/src/script.js","moduleName":"./setup/src/script.js","type":"cjs require","userRequest":"./client","loc":"4:15-34"}],"usedExports":true,"providedExports":null,"optimizationBailout":[],"depth":1,"source":"module.exports = class {\n\n constructor(options) {\n options = options || {};\n\n this.endpoint = options.endpoint || 'https://admin.pubnub.com';\n this.session = options.session || false;\n this.debug = options.debug || false;\n }\n\n errHandle(text) {\n if (this.debug) {\n console.error('API Error: ' + text);\n }\n }\n\n clog(input) {\n if (this.debug) {\n if (typeof (input) === 'object') {\n console.log(input);\n } else {\n console.log('API:'.yellow, input);\n }\n }\n }\n\n request(method, url, opts, holla) {\n\n if (url[1] !== 'me' && !this.session) {\n return this.errHandle('Authorize with init() first.');\n }\n\n opts = opts || {};\n\n opts.url = this.endpoint + '/' + url.join('/');\n opts.method = method;\n\n opts.json = true;\n opts.headers = opts.headers || {};\n // opts.headers.Authorization =\n // 'Basic cHVibnViLWJldGE6YmxvY2tzMjAxNg===';\n\n if (this.session) {\n opts.headers['X-Session-Token'] = this.session;\n }\n\n // clog('-- URL:'.yellow);\n this.clog(opts.method.red + ' ' + opts.url);\n this.clog('-- opts:'.yellow);\n this.clog(opts);\n\n $.ajax(opts)\n .done((data) => {\n console.log(data);\n holla(null, data);\n })\n .fail((data) => {\n console.log('fail', data);\n holla(data || data.message || data);\n });\n }\n\n init(input, holla) {\n this.request('post', ['api', 'me'], {\n data: {\n email: input.email || this.errHandle('No Email Supplied'),\n password: input.password || this.errHandle('No Password Supplied')\n }\n }, (err, body) => {\n if (body && body.error) {\n holla(body.error);\n } else if (err) {\n holla(err);\n } else {\n this.session = body.result.token;\n holla(null, body);\n }\n });\n }\n\n /* shortcuts to avoid pollution of executors */\n startFunction({ block, key }, callback) {\n this.request('post', ['api', 'v1', 'blocks', 'key', key.id, 'block', block.id, 'start'], {\n data: {\n block_id: block.id,\n key_id: key.id,\n action: 'start'\n }\n }, callback);\n }\n\n storeSecretKey({ key }, callback) {\n this.request('put', ['api', 'vault', key.subscribe_key, 'key', 'secretKey'], {\n contentType: 'application/json',\n data: JSON.stringify({\n keyName: 'secretKey',\n key_id: key.id,\n subscribeKey: key.subscribe_key,\n value: key.secret_key\n })\n }, callback);\n }\n\n};\n"},{"id":7,"identifier":"/Users/ian/Development/chat-engine/setup/src/setup_account.js","name":"./setup/src/setup_account.js","index":7,"index2":7,"size":2800,"cacheable":true,"built":true,"optional":false,"prefetched":false,"chunks":[0],"assets":[],"issuer":"/Users/ian/Development/chat-engine/setup/src/script.js","issuerId":0,"issuerName":"./setup/src/script.js","profile":{"factory":15,"building":25},"failed":false,"errors":0,"warnings":0,"reasons":[{"moduleId":0,"moduleIdentifier":"/Users/ian/Development/chat-engine/setup/src/script.js","module":"./setup/src/script.js","moduleName":"./setup/src/script.js","type":"cjs require","userRequest":"./setup_account","loc":"5:25-51"}],"usedExports":true,"providedExports":null,"optimizationBailout":[],"depth":1,"source":"const ProvisionBlocks = require('./setup_blocks.js');\n\nmodule.exports = (api, userId, callback = () => {}, status = () => {}) => {\n api.request('get', ['api', 'accounts'], {\n data: {\n user_id: userId\n }\n }, (err, response) => {\n\n if (err) {\n return callback('Could not get PubNub accounts. Please contact support@pubnub.com.');\n }\n\n let account = response.result.accounts[0];\n\n status('Using account ' + account.properties.company + ', if this is incorrent deploy manually or log in as another user');\n status('Creating new PubNub app...');\n\n api.request('post', ['api', 'apps'], {\n data: {\n name: 'ChatEngine App',\n owner_id: account.id,\n properties: {}\n }\n }, (err, response) => {\n\n if (err) {\n return callback('Could not create new PubNub app. Please contact support@pubnub.com.');\n }\n\n let app = response.result;\n\n status('Getting PubNub keys...');\n\n api.request('get', ['api', 'apps'], {\n data: {\n owner_id: account.id\n }\n }, (err, response) => {\n\n if (err) {\n return callback('Could not get PubNub keys. Please contact support@pubnub.com.');\n }\n\n let apps = response.result;\n let key;\n\n apps.forEach((item) => {\n if (item.id === app.id) {\n key = item.keys[0];\n }\n });\n\n status('Enabling PubNub features...');\n\n key.properties.name = 'ChatEngine Keyset';\n key.properties.presence = 1;\n key.properties.history = 1;\n key.properties.message_storage_ttl = 7;\n key.properties.multiplexing = 1;\n key.properties.presence_announce_max = 20;\n key.properties.presence_debounce = 2;\n key.properties.presence_global_here_now = 1;\n key.properties.presence_interval = 10;\n key.properties.presence_leave_on_disconnect = 0;\n key.properties.blocks = 1;\n key.properties.uls = 1;\n key.properties.wildcardsubscribe = 1;\n\n api.request('put', ['api', 'keys', key.id], {\n data: key\n }, (err, response) => {\n\n if (err) {\n callback('Could not enable PubNub features. Please contact support@pubnub.com.');\n }\n\n ProvisionBlocks(api, userId, key, callback, status);\n\n });\n });\n });\n });\n};\n"},{"id":8,"identifier":"/Users/ian/Development/chat-engine/setup/src/setup_blocks.js","name":"./setup/src/setup_blocks.js","index":8,"index2":6,"size":4285,"cacheable":true,"built":true,"optional":false,"prefetched":false,"chunks":[0],"assets":[],"issuer":"/Users/ian/Development/chat-engine/setup/src/setup_account.js","issuerId":7,"issuerName":"./setup/src/setup_account.js","profile":{"factory":9,"building":17},"failed":false,"errors":0,"warnings":0,"reasons":[{"moduleId":7,"moduleIdentifier":"/Users/ian/Development/chat-engine/setup/src/setup_account.js","module":"./setup/src/setup_account.js","moduleName":"./setup/src/setup_account.js","type":"cjs require","userRequest":"./setup_blocks.js","loc":"1:24-52"}],"usedExports":true,"providedExports":null,"optimizationBailout":[],"depth":2,"source":"module.exports = (api, userId, key, callback = () => {}, status = () => {}) => {\n\n let block = null;\n\n status('Creating new PubNub Function...');\n\n let addSecretKeyToVault = () => {\n status('Adding Secret Key to Functions Vault...');\n\n api.storeSecretKey({ key }, (err) => {\n if (err) {\n callback('Could not add Secret Key to Functions Vault. Please contact support@pubnub.com');\n return;\n }\n\n status('Success!');\n\n callback(null, {\n pub: key.publish_key,\n sub: key.subscribe_key\n });\n });\n };\n\n let startPubNubFunction = () => {\n status('Starting Pubnub Function...');\n\n api.startFunction({ block, key }, (err) => {\n if (err) {\n callback('Could not start PubNub Function. Please contact support@pubnub.com.');\n return;\n }\n\n addSecretKeyToVault();\n });\n };\n\n let onCodeFetch = (stateCodeResult, authCodeResult, functionCodeResult) => {\n status('Creating new after-publish Event Handler...');\n\n api.request('post', ['api', 'v1', 'blocks', 'key', key.id, 'event_handler'], {\n data: {\n key_id: key.id,\n block_id: block.id,\n type: 'js',\n event: 'js-after-presence',\n channels: 'global',\n name: 'state-to-kv',\n code: stateCodeResult[0],\n output: 'output-state-to-kv-' + (new Date()).getTime()\n }\n }, (err, response) => {\n if (err) {\n callback('Could not create new PubNub after-publish Event Handler. Please contact support@pubnub.com.');\n }\n\n api.request('post', ['api', 'v1', 'blocks', 'key', key.id, 'event_handler'], {\n data: {\n key_id: key.id,\n block_id: block.id,\n type: 'js',\n event: 'js-on-rest',\n path: 'chat-engine-auth',\n name: 'chat-engine-auth',\n code: authCodeResult[0],\n output: 'auth-' + Math.round((new Date()).getTime())\n }\n }, (err, response) => {\n if (err) {\n callback('Could not create new PubNub after-publish Event Handler. Please contact support@pubnub.com.');\n }\n\n status('Creating new on-request Event Handler...');\n\n api.request('post', ['api', 'v1', 'blocks', 'key', key.id, 'event_handler'], {\n data: {\n key_id: key.id,\n block_id: block.id,\n code: functionCodeResult[0],\n type: 'js',\n name: 'chat-engine-server',\n path: 'chat-engine-server',\n event: 'js-on-rest',\n output: 'output-server-endpoint-' + Math.round((new Date()).getTime())\n }\n }, (err, response) => {\n if (err) {\n callback('Could not create new Pubnub on-request Event Handler. Please contact support@pubnub.com.');\n return;\n }\n\n startPubNubFunction();\n });\n });\n });\n };\n\n api.request('post', ['api', 'v1', 'blocks', 'key', key.id, 'block'], {\n data: {\n name: 'ChatEngine Function',\n key_id: key.id\n }\n }, (err, response) => {\n\n if (err) {\n callback('Could not create new PubNub Function. Please contact support@pubnub.com.');\n }\n\n block = response.payload;\n\n let stateCodeFetch = $.get({ url: 'functions/state-to-kv.js', dataType: 'text' });\n let authCodeFetch = $.get({ url: 'functions/auth.js', dataType: 'text' });\n let functionsCodeFetch = $.get({ url: 'functions/server.js', dataType: 'text' });\n\n $.when(stateCodeFetch, authCodeFetch, functionsCodeFetch)\n .then(onCodeFetch)\n .catch(() => {\n status('Failed to fetch code');\n });\n });\n};\n"},{"id":9,"identifier":"/Users/ian/Development/chat-engine/setup/src/utils.js","name":"./setup/src/utils.js","index":9,"index2":8,"size":382,"cacheable":true,"built":true,"optional":false,"prefetched":false,"chunks":[0],"assets":[],"issuer":"/Users/ian/Development/chat-engine/setup/src/script.js","issuerId":0,"issuerName":"./setup/src/script.js","profile":{"factory":15,"building":33},"failed":false,"errors":0,"warnings":0,"reasons":[{"moduleId":0,"moduleIdentifier":"/Users/ian/Development/chat-engine/setup/src/script.js","module":"./setup/src/script.js","moduleName":"./setup/src/script.js","type":"cjs require","userRequest":"./utils","loc":"6:14-32"}],"usedExports":true,"providedExports":null,"optimizationBailout":[],"depth":1,"source":"\nconst findCookie = (name) => {\n let cookies = document.cookie.split(';');\n let result = null;\n\n cookies.forEach((cookie) => {\n let cookieName = cookie.split('=')[0];\n let cookieValue = cookie.split('=')[1];\n\n if (cookieName.endsWith(name)) {\n result = cookieValue;\n }\n });\n\n return result;\n};\n\nmodule.exports = { findCookie };\n"}],"filteredModules":3,"origins":[{"moduleId":0,"module":"/Users/ian/Development/chat-engine/setup/src/script.js","moduleIdentifier":"/Users/ian/Development/chat-engine/setup/src/script.js","moduleName":"./setup/src/script.js","loc":"","name":"main","reasons":[]}]}],"modules":[{"id":0,"identifier":"/Users/ian/Development/chat-engine/setup/src/script.js","name":"./setup/src/script.js","index":0,"index2":9,"size":3577,"cacheable":true,"built":true,"optional":false,"prefetched":false,"chunks":[0],"assets":[],"issuer":null,"issuerId":null,"issuerName":null,"profile":{"factory":25,"building":49},"failed":false,"errors":0,"warnings":0,"reasons":[],"usedExports":true,"providedExports":null,"optimizationBailout":[],"depth":0,"source":"// polyfill Promise\nrequire('es6-promise/auto');\n\nconst Client = require('./client');\nconst ProvisionAccount = require('./setup_account');\nconst utils = require('./utils');\n\n\nconst extractError = (err) => {\n if (err && err.responseJSON && err.responseJSON.error) {\n return err.responseJSON.error;\n }\n};\n\nmodule.exports = class {\n\n constructor() {\n this.loginElement = $('#login');\n this.provisionElement = $('#setup');\n this.loadElement = $('#load');\n this.errorElement = $('#error');\n this.errorOutElement = $('#error-out');\n this.statusElement = $('#status');\n this.codeElement = $('#code');\n this.outputElement = $('#output');\n this.emailElement = $('#email');\n this.passwordElement = $('#password');\n\n this.loginElement.submit(this.onLoginRegister.bind(this));\n this.provisionElement.submit(this.onSetup.bind(this));\n\n this.userId = utils.findCookie('pnAdminId');\n let tokenCookie = utils.findCookie('pnAdminToken');\n\n this.client = new Client({\n session: tokenCookie,\n debug: false,\n endpoint: 'https://admin.pubnub.com'\n });\n\n if (this.userId && tokenCookie) {\n this.provisionElement.show();\n this.loginElement.hide();\n analytics.identify(this.userId);\n }\n\n }\n\n displayStatus(statusText) {\n this.statusElement.show();\n this.statusElement.append($('
  • ' + statusText + '
  • '));\n }\n\n clearErrors() {\n this.errorElement.hide();\n }\n\n raiseError(err) {\n this.errorOutElement.html(err);\n this.errorElement.show();\n }\n\n onProvisionSuccess(err, data) {\n if (err) {\n this.loadElement.hide();\n this.provisionElement.show();\n\n this.errorOutElement.html(err);\n this.errorElement.show();\n } else {\n this.loadElement.hide();\n\n let output = '';\n output += '// Make sure to import ChatEngine first!\\n';\n output += 'ChatEngine = ChatEngineCore.create({\\n';\n output += \" publishKey: '\" + data.pub + \"',\\n\";\n output += \" subscribeKey: '\" + data.sub + \"'\\n\";\n output += '});\\n';\n\n analytics.track('chat_engine_activation');\n\n this.codeElement.text(output);\n this.outputElement.show();\n }\n }\n\n onLoginRegister() {\n this.clearErrors();\n const email = this.emailElement.val();\n const password = this.passwordElement.val();\n\n if (!email || email === '') {\n this.raiseError('email not valid');\n return false;\n }\n\n if (!password || password === '') {\n this.raiseError('password not valid');\n return false;\n }\n\n this.client.init({ email, password }, (err, response) => {\n if (err) {\n this.raiseError(extractError(err));\n } else {\n this.userId = response.result.user_id;\n analytics.identify(this.userId);\n this.provisionElement.show();\n this.loginElement.hide();\n }\n });\n\n\n return false;\n }\n\n onSetup() {\n this.clearErrors();\n\n this.loadElement.show();\n this.errorElement.hide();\n this.statusElement.empty();\n\n ProvisionAccount(this.client, this.userId, this.onProvisionSuccess.bind(this), this.displayStatus.bind(this));\n\n return false;\n }\n\n};\n"},{"id":4,"identifier":"/Users/ian/Development/chat-engine/node_modules/webpack/buildin/global.js","name":"(webpack)/buildin/global.js","index":4,"index2":1,"size":488,"cacheable":true,"built":true,"optional":false,"prefetched":false,"chunks":[0],"assets":[],"issuer":"/Users/ian/Development/chat-engine/node_modules/es6-promise/dist/es6-promise.js","issuerId":2,"issuerName":"./node_modules/es6-promise/dist/es6-promise.js","profile":{"factory":4,"building":8},"failed":false,"errors":0,"warnings":0,"reasons":[{"moduleId":2,"moduleIdentifier":"/Users/ian/Development/chat-engine/node_modules/es6-promise/dist/es6-promise.js","module":"./node_modules/es6-promise/dist/es6-promise.js","moduleName":"./node_modules/es6-promise/dist/es6-promise.js","type":"cjs require","userRequest":"global","loc":"1:0-44"}],"usedExports":true,"providedExports":null,"optimizationBailout":[],"depth":3,"source":"var g;\n\n// This works in non-strict mode\ng = (function() {\n\treturn this;\n})();\n\ntry {\n\t// This works if eval is allowed (see CSP)\n\tg = g || Function(\"return this\")() || (1,eval)(\"this\");\n} catch(e) {\n\t// This works if the window reference is available\n\tif(typeof window === \"object\")\n\t\tg = window;\n}\n\n// g can still be undefined, but nothing to do about it...\n// We return undefined, instead of nothing here, so it's\n// easier to handle this case. if(!global) { ...}\n\nmodule.exports = g;\n"},{"id":5,"identifier":"ignored /Users/ian/Development/chat-engine/node_modules/es6-promise/dist vertx","name":"vertx (ignored)","index":5,"index2":2,"size":15,"cacheable":true,"built":false,"optional":true,"prefetched":false,"chunks":[0],"assets":[],"issuer":"/Users/ian/Development/chat-engine/node_modules/es6-promise/dist/es6-promise.js","issuerId":2,"issuerName":"./node_modules/es6-promise/dist/es6-promise.js","profile":{"factory":1,"building":1},"failed":false,"errors":0,"warnings":0,"reasons":[{"moduleId":2,"moduleIdentifier":"/Users/ian/Development/chat-engine/node_modules/es6-promise/dist/es6-promise.js","module":"./node_modules/es6-promise/dist/es6-promise.js","moduleName":"./node_modules/es6-promise/dist/es6-promise.js","type":"cjs require","userRequest":"vertx","loc":"138:16-26"}],"usedExports":true,"providedExports":null,"optimizationBailout":[],"depth":3},{"id":6,"identifier":"/Users/ian/Development/chat-engine/setup/src/client.js","name":"./setup/src/client.js","index":6,"index2":5,"size":2922,"cacheable":true,"built":true,"optional":false,"prefetched":false,"chunks":[0],"assets":[],"issuer":"/Users/ian/Development/chat-engine/setup/src/script.js","issuerId":0,"issuerName":"./setup/src/script.js","profile":{"factory":14,"building":18},"failed":false,"errors":0,"warnings":0,"reasons":[{"moduleId":0,"moduleIdentifier":"/Users/ian/Development/chat-engine/setup/src/script.js","module":"./setup/src/script.js","moduleName":"./setup/src/script.js","type":"cjs require","userRequest":"./client","loc":"4:15-34"}],"usedExports":true,"providedExports":null,"optimizationBailout":[],"depth":1,"source":"module.exports = class {\n\n constructor(options) {\n options = options || {};\n\n this.endpoint = options.endpoint || 'https://admin.pubnub.com';\n this.session = options.session || false;\n this.debug = options.debug || false;\n }\n\n errHandle(text) {\n if (this.debug) {\n console.error('API Error: ' + text);\n }\n }\n\n clog(input) {\n if (this.debug) {\n if (typeof (input) === 'object') {\n console.log(input);\n } else {\n console.log('API:'.yellow, input);\n }\n }\n }\n\n request(method, url, opts, holla) {\n\n if (url[1] !== 'me' && !this.session) {\n return this.errHandle('Authorize with init() first.');\n }\n\n opts = opts || {};\n\n opts.url = this.endpoint + '/' + url.join('/');\n opts.method = method;\n\n opts.json = true;\n opts.headers = opts.headers || {};\n // opts.headers.Authorization =\n // 'Basic cHVibnViLWJldGE6YmxvY2tzMjAxNg===';\n\n if (this.session) {\n opts.headers['X-Session-Token'] = this.session;\n }\n\n // clog('-- URL:'.yellow);\n this.clog(opts.method.red + ' ' + opts.url);\n this.clog('-- opts:'.yellow);\n this.clog(opts);\n\n $.ajax(opts)\n .done((data) => {\n console.log(data);\n holla(null, data);\n })\n .fail((data) => {\n console.log('fail', data);\n holla(data || data.message || data);\n });\n }\n\n init(input, holla) {\n this.request('post', ['api', 'me'], {\n data: {\n email: input.email || this.errHandle('No Email Supplied'),\n password: input.password || this.errHandle('No Password Supplied')\n }\n }, (err, body) => {\n if (body && body.error) {\n holla(body.error);\n } else if (err) {\n holla(err);\n } else {\n this.session = body.result.token;\n holla(null, body);\n }\n });\n }\n\n /* shortcuts to avoid pollution of executors */\n startFunction({ block, key }, callback) {\n this.request('post', ['api', 'v1', 'blocks', 'key', key.id, 'block', block.id, 'start'], {\n data: {\n block_id: block.id,\n key_id: key.id,\n action: 'start'\n }\n }, callback);\n }\n\n storeSecretKey({ key }, callback) {\n this.request('put', ['api', 'vault', key.subscribe_key, 'key', 'secretKey'], {\n contentType: 'application/json',\n data: JSON.stringify({\n keyName: 'secretKey',\n key_id: key.id,\n subscribeKey: key.subscribe_key,\n value: key.secret_key\n })\n }, callback);\n }\n\n};\n"},{"id":7,"identifier":"/Users/ian/Development/chat-engine/setup/src/setup_account.js","name":"./setup/src/setup_account.js","index":7,"index2":7,"size":2800,"cacheable":true,"built":true,"optional":false,"prefetched":false,"chunks":[0],"assets":[],"issuer":"/Users/ian/Development/chat-engine/setup/src/script.js","issuerId":0,"issuerName":"./setup/src/script.js","profile":{"factory":15,"building":25},"failed":false,"errors":0,"warnings":0,"reasons":[{"moduleId":0,"moduleIdentifier":"/Users/ian/Development/chat-engine/setup/src/script.js","module":"./setup/src/script.js","moduleName":"./setup/src/script.js","type":"cjs require","userRequest":"./setup_account","loc":"5:25-51"}],"usedExports":true,"providedExports":null,"optimizationBailout":[],"depth":1,"source":"const ProvisionBlocks = require('./setup_blocks.js');\n\nmodule.exports = (api, userId, callback = () => {}, status = () => {}) => {\n api.request('get', ['api', 'accounts'], {\n data: {\n user_id: userId\n }\n }, (err, response) => {\n\n if (err) {\n return callback('Could not get PubNub accounts. Please contact support@pubnub.com.');\n }\n\n let account = response.result.accounts[0];\n\n status('Using account ' + account.properties.company + ', if this is incorrent deploy manually or log in as another user');\n status('Creating new PubNub app...');\n\n api.request('post', ['api', 'apps'], {\n data: {\n name: 'ChatEngine App',\n owner_id: account.id,\n properties: {}\n }\n }, (err, response) => {\n\n if (err) {\n return callback('Could not create new PubNub app. Please contact support@pubnub.com.');\n }\n\n let app = response.result;\n\n status('Getting PubNub keys...');\n\n api.request('get', ['api', 'apps'], {\n data: {\n owner_id: account.id\n }\n }, (err, response) => {\n\n if (err) {\n return callback('Could not get PubNub keys. Please contact support@pubnub.com.');\n }\n\n let apps = response.result;\n let key;\n\n apps.forEach((item) => {\n if (item.id === app.id) {\n key = item.keys[0];\n }\n });\n\n status('Enabling PubNub features...');\n\n key.properties.name = 'ChatEngine Keyset';\n key.properties.presence = 1;\n key.properties.history = 1;\n key.properties.message_storage_ttl = 7;\n key.properties.multiplexing = 1;\n key.properties.presence_announce_max = 20;\n key.properties.presence_debounce = 2;\n key.properties.presence_global_here_now = 1;\n key.properties.presence_interval = 10;\n key.properties.presence_leave_on_disconnect = 0;\n key.properties.blocks = 1;\n key.properties.uls = 1;\n key.properties.wildcardsubscribe = 1;\n\n api.request('put', ['api', 'keys', key.id], {\n data: key\n }, (err, response) => {\n\n if (err) {\n callback('Could not enable PubNub features. Please contact support@pubnub.com.');\n }\n\n ProvisionBlocks(api, userId, key, callback, status);\n\n });\n });\n });\n });\n};\n"},{"id":8,"identifier":"/Users/ian/Development/chat-engine/setup/src/setup_blocks.js","name":"./setup/src/setup_blocks.js","index":8,"index2":6,"size":4285,"cacheable":true,"built":true,"optional":false,"prefetched":false,"chunks":[0],"assets":[],"issuer":"/Users/ian/Development/chat-engine/setup/src/setup_account.js","issuerId":7,"issuerName":"./setup/src/setup_account.js","profile":{"factory":9,"building":17},"failed":false,"errors":0,"warnings":0,"reasons":[{"moduleId":7,"moduleIdentifier":"/Users/ian/Development/chat-engine/setup/src/setup_account.js","module":"./setup/src/setup_account.js","moduleName":"./setup/src/setup_account.js","type":"cjs require","userRequest":"./setup_blocks.js","loc":"1:24-52"}],"usedExports":true,"providedExports":null,"optimizationBailout":[],"depth":2,"source":"module.exports = (api, userId, key, callback = () => {}, status = () => {}) => {\n\n let block = null;\n\n status('Creating new PubNub Function...');\n\n let addSecretKeyToVault = () => {\n status('Adding Secret Key to Functions Vault...');\n\n api.storeSecretKey({ key }, (err) => {\n if (err) {\n callback('Could not add Secret Key to Functions Vault. Please contact support@pubnub.com');\n return;\n }\n\n status('Success!');\n\n callback(null, {\n pub: key.publish_key,\n sub: key.subscribe_key\n });\n });\n };\n\n let startPubNubFunction = () => {\n status('Starting Pubnub Function...');\n\n api.startFunction({ block, key }, (err) => {\n if (err) {\n callback('Could not start PubNub Function. Please contact support@pubnub.com.');\n return;\n }\n\n addSecretKeyToVault();\n });\n };\n\n let onCodeFetch = (stateCodeResult, authCodeResult, functionCodeResult) => {\n status('Creating new after-publish Event Handler...');\n\n api.request('post', ['api', 'v1', 'blocks', 'key', key.id, 'event_handler'], {\n data: {\n key_id: key.id,\n block_id: block.id,\n type: 'js',\n event: 'js-after-presence',\n channels: 'global',\n name: 'state-to-kv',\n code: stateCodeResult[0],\n output: 'output-state-to-kv-' + (new Date()).getTime()\n }\n }, (err, response) => {\n if (err) {\n callback('Could not create new PubNub after-publish Event Handler. Please contact support@pubnub.com.');\n }\n\n api.request('post', ['api', 'v1', 'blocks', 'key', key.id, 'event_handler'], {\n data: {\n key_id: key.id,\n block_id: block.id,\n type: 'js',\n event: 'js-on-rest',\n path: 'chat-engine-auth',\n name: 'chat-engine-auth',\n code: authCodeResult[0],\n output: 'auth-' + Math.round((new Date()).getTime())\n }\n }, (err, response) => {\n if (err) {\n callback('Could not create new PubNub after-publish Event Handler. Please contact support@pubnub.com.');\n }\n\n status('Creating new on-request Event Handler...');\n\n api.request('post', ['api', 'v1', 'blocks', 'key', key.id, 'event_handler'], {\n data: {\n key_id: key.id,\n block_id: block.id,\n code: functionCodeResult[0],\n type: 'js',\n name: 'chat-engine-server',\n path: 'chat-engine-server',\n event: 'js-on-rest',\n output: 'output-server-endpoint-' + Math.round((new Date()).getTime())\n }\n }, (err, response) => {\n if (err) {\n callback('Could not create new Pubnub on-request Event Handler. Please contact support@pubnub.com.');\n return;\n }\n\n startPubNubFunction();\n });\n });\n });\n };\n\n api.request('post', ['api', 'v1', 'blocks', 'key', key.id, 'block'], {\n data: {\n name: 'ChatEngine Function',\n key_id: key.id\n }\n }, (err, response) => {\n\n if (err) {\n callback('Could not create new PubNub Function. Please contact support@pubnub.com.');\n }\n\n block = response.payload;\n\n let stateCodeFetch = $.get({ url: 'functions/state-to-kv.js', dataType: 'text' });\n let authCodeFetch = $.get({ url: 'functions/auth.js', dataType: 'text' });\n let functionsCodeFetch = $.get({ url: 'functions/server.js', dataType: 'text' });\n\n $.when(stateCodeFetch, authCodeFetch, functionsCodeFetch)\n .then(onCodeFetch)\n .catch(() => {\n status('Failed to fetch code');\n });\n });\n};\n"},{"id":9,"identifier":"/Users/ian/Development/chat-engine/setup/src/utils.js","name":"./setup/src/utils.js","index":9,"index2":8,"size":382,"cacheable":true,"built":true,"optional":false,"prefetched":false,"chunks":[0],"assets":[],"issuer":"/Users/ian/Development/chat-engine/setup/src/script.js","issuerId":0,"issuerName":"./setup/src/script.js","profile":{"factory":15,"building":33},"failed":false,"errors":0,"warnings":0,"reasons":[{"moduleId":0,"moduleIdentifier":"/Users/ian/Development/chat-engine/setup/src/script.js","module":"./setup/src/script.js","moduleName":"./setup/src/script.js","type":"cjs require","userRequest":"./utils","loc":"6:14-32"}],"usedExports":true,"providedExports":null,"optimizationBailout":[],"depth":1,"source":"\nconst findCookie = (name) => {\n let cookies = document.cookie.split(';');\n let result = null;\n\n cookies.forEach((cookie) => {\n let cookieName = cookie.split('=')[0];\n let cookieValue = cookie.split('=')[1];\n\n if (cookieName.endsWith(name)) {\n result = cookieValue;\n }\n });\n\n return result;\n};\n\nmodule.exports = { findCookie };\n"}],"filteredModules":3,"children":[]} \ No newline at end of file +{"errors":[],"warnings":[],"version":"3.8.1","hash":"03d06470e714c27525c0","publicPath":"","assetsByChunkName":{"main":"chat-engine-setup.js"},"assets":[{"name":"chat-engine-setup.js","size":15955,"chunks":[0],"chunkNames":["main"],"emitted":true},{"name":"stats.json","size":0,"chunks":[],"chunkNames":[]}],"filteredAssets":0,"entrypoints":{"main":{"chunks":[0],"assets":["chat-engine-setup.js"]}},"chunks":[{"id":0,"rendered":true,"initial":true,"entry":true,"extraAsync":false,"size":48628,"names":["main"],"files":["chat-engine-setup.js"],"hash":"0d61b947e54073bd8d55","parents":[],"modules":[{"id":0,"identifier":"/Users/ian/Development/chat-engine/setup/src/script.js","name":"./setup/src/script.js","index":0,"index2":9,"size":3577,"cacheable":true,"built":true,"optional":false,"prefetched":false,"chunks":[0],"assets":[],"issuer":null,"issuerId":null,"issuerName":null,"profile":{"factory":4,"building":5},"failed":false,"errors":0,"warnings":0,"reasons":[],"usedExports":true,"providedExports":null,"optimizationBailout":[],"depth":0,"source":"// polyfill Promise\nrequire('es6-promise/auto');\n\nconst Client = require('./client');\nconst ProvisionAccount = require('./setup_account');\nconst utils = require('./utils');\n\n\nconst extractError = (err) => {\n if (err && err.responseJSON && err.responseJSON.error) {\n return err.responseJSON.error;\n }\n};\n\nmodule.exports = class {\n\n constructor() {\n this.loginElement = $('#login');\n this.provisionElement = $('#setup');\n this.loadElement = $('#load');\n this.errorElement = $('#error');\n this.errorOutElement = $('#error-out');\n this.statusElement = $('#status');\n this.codeElement = $('#code');\n this.outputElement = $('#output');\n this.emailElement = $('#email');\n this.passwordElement = $('#password');\n\n this.loginElement.submit(this.onLoginRegister.bind(this));\n this.provisionElement.submit(this.onSetup.bind(this));\n\n this.userId = utils.findCookie('pnAdminId');\n let tokenCookie = utils.findCookie('pnAdminToken');\n\n this.client = new Client({\n session: tokenCookie,\n debug: false,\n endpoint: 'https://admin.pubnub.com'\n });\n\n if (this.userId && tokenCookie) {\n this.provisionElement.show();\n this.loginElement.hide();\n analytics.identify(this.userId);\n }\n\n }\n\n displayStatus(statusText) {\n this.statusElement.show();\n this.statusElement.append($('
  • ' + statusText + '
  • '));\n }\n\n clearErrors() {\n this.errorElement.hide();\n }\n\n raiseError(err) {\n this.errorOutElement.html(err);\n this.errorElement.show();\n }\n\n onProvisionSuccess(err, data) {\n if (err) {\n this.loadElement.hide();\n this.provisionElement.show();\n\n this.errorOutElement.html(err);\n this.errorElement.show();\n } else {\n this.loadElement.hide();\n\n let output = '';\n output += '// Make sure to import ChatEngine first!\\n';\n output += 'ChatEngine = ChatEngineCore.create({\\n';\n output += \" publishKey: '\" + data.pub + \"',\\n\";\n output += \" subscribeKey: '\" + data.sub + \"'\\n\";\n output += '});\\n';\n\n analytics.track('chat_engine_activation');\n\n this.codeElement.text(output);\n this.outputElement.show();\n }\n }\n\n onLoginRegister() {\n this.clearErrors();\n const email = this.emailElement.val();\n const password = this.passwordElement.val();\n\n if (!email || email === '') {\n this.raiseError('email not valid');\n return false;\n }\n\n if (!password || password === '') {\n this.raiseError('password not valid');\n return false;\n }\n\n this.client.init({ email, password }, (err, response) => {\n if (err) {\n this.raiseError(extractError(err));\n } else {\n this.userId = response.result.user_id;\n analytics.identify(this.userId);\n this.provisionElement.show();\n this.loginElement.hide();\n }\n });\n\n\n return false;\n }\n\n onSetup() {\n this.clearErrors();\n\n this.loadElement.show();\n this.errorElement.hide();\n this.statusElement.empty();\n\n ProvisionAccount(this.client, this.userId, this.onProvisionSuccess.bind(this), this.displayStatus.bind(this));\n\n return false;\n }\n\n};\n"},{"id":4,"identifier":"/Users/ian/Development/chat-engine/node_modules/webpack/buildin/global.js","name":"(webpack)/buildin/global.js","index":4,"index2":1,"size":488,"cacheable":true,"built":true,"optional":false,"prefetched":false,"chunks":[0],"assets":[],"issuer":"/Users/ian/Development/chat-engine/node_modules/es6-promise/dist/es6-promise.js","issuerId":2,"issuerName":"./node_modules/es6-promise/dist/es6-promise.js","profile":{"factory":9,"building":9},"failed":false,"errors":0,"warnings":0,"reasons":[{"moduleId":2,"moduleIdentifier":"/Users/ian/Development/chat-engine/node_modules/es6-promise/dist/es6-promise.js","module":"./node_modules/es6-promise/dist/es6-promise.js","moduleName":"./node_modules/es6-promise/dist/es6-promise.js","type":"cjs require","userRequest":"global","loc":"1:0-44"}],"usedExports":true,"providedExports":null,"optimizationBailout":[],"depth":3,"source":"var g;\n\n// This works in non-strict mode\ng = (function() {\n\treturn this;\n})();\n\ntry {\n\t// This works if eval is allowed (see CSP)\n\tg = g || Function(\"return this\")() || (1,eval)(\"this\");\n} catch(e) {\n\t// This works if the window reference is available\n\tif(typeof window === \"object\")\n\t\tg = window;\n}\n\n// g can still be undefined, but nothing to do about it...\n// We return undefined, instead of nothing here, so it's\n// easier to handle this case. if(!global) { ...}\n\nmodule.exports = g;\n"},{"id":5,"identifier":"ignored /Users/ian/Development/chat-engine/node_modules/es6-promise/dist vertx","name":"vertx (ignored)","index":5,"index2":2,"size":15,"cacheable":true,"built":false,"optional":true,"prefetched":false,"chunks":[0],"assets":[],"issuer":"/Users/ian/Development/chat-engine/node_modules/es6-promise/dist/es6-promise.js","issuerId":2,"issuerName":"./node_modules/es6-promise/dist/es6-promise.js","profile":{"factory":2,"building":1},"failed":false,"errors":0,"warnings":0,"reasons":[{"moduleId":2,"moduleIdentifier":"/Users/ian/Development/chat-engine/node_modules/es6-promise/dist/es6-promise.js","module":"./node_modules/es6-promise/dist/es6-promise.js","moduleName":"./node_modules/es6-promise/dist/es6-promise.js","type":"cjs require","userRequest":"vertx","loc":"138:16-26"}],"usedExports":true,"providedExports":null,"optimizationBailout":[],"depth":3},{"id":6,"identifier":"/Users/ian/Development/chat-engine/setup/src/client.js","name":"./setup/src/client.js","index":6,"index2":5,"size":2922,"cacheable":true,"built":true,"optional":false,"prefetched":false,"chunks":[0],"assets":[],"issuer":"/Users/ian/Development/chat-engine/setup/src/script.js","issuerId":0,"issuerName":"./setup/src/script.js","profile":{"factory":9,"building":25},"failed":false,"errors":0,"warnings":0,"reasons":[{"moduleId":0,"moduleIdentifier":"/Users/ian/Development/chat-engine/setup/src/script.js","module":"./setup/src/script.js","moduleName":"./setup/src/script.js","type":"cjs require","userRequest":"./client","loc":"4:15-34"}],"usedExports":true,"providedExports":null,"optimizationBailout":[],"depth":1,"source":"module.exports = class {\n\n constructor(options) {\n options = options || {};\n\n this.endpoint = options.endpoint || 'https://admin.pubnub.com';\n this.session = options.session || false;\n this.debug = options.debug || false;\n }\n\n errHandle(text) {\n if (this.debug) {\n console.error('API Error: ' + text);\n }\n }\n\n clog(input) {\n if (this.debug) {\n if (typeof (input) === 'object') {\n console.log(input);\n } else {\n console.log('API:'.yellow, input);\n }\n }\n }\n\n request(method, url, opts, holla) {\n\n if (url[1] !== 'me' && !this.session) {\n return this.errHandle('Authorize with init() first.');\n }\n\n opts = opts || {};\n\n opts.url = this.endpoint + '/' + url.join('/');\n opts.method = method;\n\n opts.json = true;\n opts.headers = opts.headers || {};\n // opts.headers.Authorization =\n // 'Basic cHVibnViLWJldGE6YmxvY2tzMjAxNg===';\n\n if (this.session) {\n opts.headers['X-Session-Token'] = this.session;\n }\n\n // clog('-- URL:'.yellow);\n this.clog(opts.method.red + ' ' + opts.url);\n this.clog('-- opts:'.yellow);\n this.clog(opts);\n\n $.ajax(opts)\n .done((data) => {\n console.log(data);\n holla(null, data);\n })\n .fail((data) => {\n console.log('fail', data);\n holla(data || data.message || data);\n });\n }\n\n init(input, holla) {\n this.request('post', ['api', 'me'], {\n data: {\n email: input.email || this.errHandle('No Email Supplied'),\n password: input.password || this.errHandle('No Password Supplied')\n }\n }, (err, body) => {\n if (body && body.error) {\n holla(body.error);\n } else if (err) {\n holla(err);\n } else {\n this.session = body.result.token;\n holla(null, body);\n }\n });\n }\n\n /* shortcuts to avoid pollution of executors */\n startFunction({ block, key }, callback) {\n this.request('post', ['api', 'v1', 'blocks', 'key', key.id, 'block', block.id, 'start'], {\n data: {\n block_id: block.id,\n key_id: key.id,\n action: 'start'\n }\n }, callback);\n }\n\n storeSecretKey({ key }, callback) {\n this.request('put', ['api', 'vault', key.subscribe_key, 'key', 'secretKey'], {\n contentType: 'application/json',\n data: JSON.stringify({\n keyName: 'secretKey',\n key_id: key.id,\n subscribeKey: key.subscribe_key,\n value: key.secret_key\n })\n }, callback);\n }\n\n};\n"},{"id":7,"identifier":"/Users/ian/Development/chat-engine/setup/src/setup_account.js","name":"./setup/src/setup_account.js","index":7,"index2":7,"size":2800,"cacheable":true,"built":true,"optional":false,"prefetched":false,"chunks":[0],"assets":[],"issuer":"/Users/ian/Development/chat-engine/setup/src/script.js","issuerId":0,"issuerName":"./setup/src/script.js","profile":{"factory":9,"building":2},"failed":false,"errors":0,"warnings":0,"reasons":[{"moduleId":0,"moduleIdentifier":"/Users/ian/Development/chat-engine/setup/src/script.js","module":"./setup/src/script.js","moduleName":"./setup/src/script.js","type":"cjs require","userRequest":"./setup_account","loc":"5:25-51"}],"usedExports":true,"providedExports":null,"optimizationBailout":[],"depth":1,"source":"const ProvisionBlocks = require('./setup_blocks.js');\n\nmodule.exports = (api, userId, callback = () => {}, status = () => {}) => {\n api.request('get', ['api', 'accounts'], {\n data: {\n user_id: userId\n }\n }, (err, response) => {\n\n if (err) {\n return callback('Could not get PubNub accounts. Please contact support@pubnub.com.');\n }\n\n let account = response.result.accounts[0];\n\n status('Using account ' + account.properties.company + ', if this is incorrent deploy manually or log in as another user');\n status('Creating new PubNub app...');\n\n api.request('post', ['api', 'apps'], {\n data: {\n name: 'ChatEngine App',\n owner_id: account.id,\n properties: {}\n }\n }, (err, response) => {\n\n if (err) {\n return callback('Could not create new PubNub app. Please contact support@pubnub.com.');\n }\n\n let app = response.result;\n\n status('Getting PubNub keys...');\n\n api.request('get', ['api', 'apps'], {\n data: {\n owner_id: account.id\n }\n }, (err, response) => {\n\n if (err) {\n return callback('Could not get PubNub keys. Please contact support@pubnub.com.');\n }\n\n let apps = response.result;\n let key;\n\n apps.forEach((item) => {\n if (item.id === app.id) {\n key = item.keys[0];\n }\n });\n\n status('Enabling PubNub features...');\n\n key.properties.name = 'ChatEngine Keyset';\n key.properties.presence = 1;\n key.properties.history = 1;\n key.properties.message_storage_ttl = 7;\n key.properties.multiplexing = 1;\n key.properties.presence_announce_max = 20;\n key.properties.presence_debounce = 2;\n key.properties.presence_global_here_now = 1;\n key.properties.presence_interval = 10;\n key.properties.presence_leave_on_disconnect = 0;\n key.properties.blocks = 1;\n key.properties.uls = 1;\n key.properties.wildcardsubscribe = 1;\n\n api.request('put', ['api', 'keys', key.id], {\n data: key\n }, (err, response) => {\n\n if (err) {\n callback('Could not enable PubNub features. Please contact support@pubnub.com.');\n }\n\n ProvisionBlocks(api, userId, key, callback, status);\n\n });\n });\n });\n });\n};\n"},{"id":8,"identifier":"/Users/ian/Development/chat-engine/setup/src/setup_blocks.js","name":"./setup/src/setup_blocks.js","index":8,"index2":6,"size":4286,"cacheable":true,"built":true,"optional":false,"prefetched":false,"chunks":[0],"assets":[],"issuer":"/Users/ian/Development/chat-engine/setup/src/setup_account.js","issuerId":7,"issuerName":"./setup/src/setup_account.js","profile":{"factory":33,"building":10},"failed":false,"errors":0,"warnings":0,"reasons":[{"moduleId":7,"moduleIdentifier":"/Users/ian/Development/chat-engine/setup/src/setup_account.js","module":"./setup/src/setup_account.js","moduleName":"./setup/src/setup_account.js","type":"cjs require","userRequest":"./setup_blocks.js","loc":"1:24-52"}],"usedExports":true,"providedExports":null,"optimizationBailout":[],"depth":2,"source":"module.exports = (api, userId, key, callback = () => {}, status = () => {}) => {\n\n let block = null;\n\n status('Creating new PubNub Function...');\n\n let addSecretKeyToVault = () => {\n status('Adding Secret Key to Functions Vault...');\n\n api.storeSecretKey({ key }, (err) => {\n if (err) {\n callback('Could not add Secret Key to Functions Vault. Please contact support@pubnub.com');\n return;\n }\n\n status('Success!');\n\n callback(null, {\n pub: key.publish_key,\n sub: key.subscribe_key\n });\n });\n };\n\n let startPubNubFunction = () => {\n status('Starting Pubnub Function...');\n\n api.startFunction({ block, key }, (err) => {\n if (err) {\n callback('Could not start PubNub Function. Please contact support@pubnub.com.');\n return;\n }\n\n addSecretKeyToVault();\n });\n };\n\n let onCodeFetch = (stateCodeResult, authCodeResult, functionCodeResult) => {\n status('Creating new after-publish Event Handler...');\n\n api.request('post', ['api', 'v1', 'blocks', 'key', key.id, 'event_handler'], {\n data: {\n key_id: key.id,\n block_id: block.id,\n type: 'js',\n event: 'js-after-presence',\n channels: '*',\n name: 'chat-engine-state',\n code: stateCodeResult[0],\n output: 'output-state-to-kv-' + (new Date()).getTime()\n }\n }, (err, response) => {\n if (err) {\n callback('Could not create new PubNub after-publish Event Handler. Please contact support@pubnub.com.');\n }\n\n api.request('post', ['api', 'v1', 'blocks', 'key', key.id, 'event_handler'], {\n data: {\n key_id: key.id,\n block_id: block.id,\n type: 'js',\n event: 'js-on-rest',\n path: 'chat-engine-auth',\n name: 'chat-engine-auth',\n code: authCodeResult[0],\n output: 'auth-' + Math.round((new Date()).getTime())\n }\n }, (err, response) => {\n if (err) {\n callback('Could not create new PubNub after-publish Event Handler. Please contact support@pubnub.com.');\n }\n\n status('Creating new on-request Event Handler...');\n\n api.request('post', ['api', 'v1', 'blocks', 'key', key.id, 'event_handler'], {\n data: {\n key_id: key.id,\n block_id: block.id,\n code: functionCodeResult[0],\n type: 'js',\n name: 'chat-engine-server',\n path: 'chat-engine-server',\n event: 'js-on-rest',\n output: 'output-server-endpoint-' + Math.round((new Date()).getTime())\n }\n }, (err, response) => {\n if (err) {\n callback('Could not create new Pubnub on-request Event Handler. Please contact support@pubnub.com.');\n return;\n }\n\n startPubNubFunction();\n });\n });\n });\n };\n\n api.request('post', ['api', 'v1', 'blocks', 'key', key.id, 'block'], {\n data: {\n name: 'ChatEngine Function',\n key_id: key.id\n }\n }, (err, response) => {\n\n if (err) {\n callback('Could not create new PubNub Function. Please contact support@pubnub.com.');\n }\n\n block = response.payload;\n\n let stateCodeFetch = $.get({ url: 'functions/state-to-kv.js', dataType: 'text' });\n let authCodeFetch = $.get({ url: 'functions/auth.js', dataType: 'text' });\n let functionsCodeFetch = $.get({ url: 'functions/server.js', dataType: 'text' });\n\n $.when(stateCodeFetch, authCodeFetch, functionsCodeFetch)\n .then(onCodeFetch)\n .catch(() => {\n status('Failed to fetch code');\n });\n });\n};\n"},{"id":9,"identifier":"/Users/ian/Development/chat-engine/setup/src/utils.js","name":"./setup/src/utils.js","index":9,"index2":8,"size":382,"cacheable":true,"built":true,"optional":false,"prefetched":false,"chunks":[0],"assets":[],"issuer":"/Users/ian/Development/chat-engine/setup/src/script.js","issuerId":0,"issuerName":"./setup/src/script.js","profile":{"factory":9,"building":33},"failed":false,"errors":0,"warnings":0,"reasons":[{"moduleId":0,"moduleIdentifier":"/Users/ian/Development/chat-engine/setup/src/script.js","module":"./setup/src/script.js","moduleName":"./setup/src/script.js","type":"cjs require","userRequest":"./utils","loc":"6:14-32"}],"usedExports":true,"providedExports":null,"optimizationBailout":[],"depth":1,"source":"\nconst findCookie = (name) => {\n let cookies = document.cookie.split(';');\n let result = null;\n\n cookies.forEach((cookie) => {\n let cookieName = cookie.split('=')[0];\n let cookieValue = cookie.split('=')[1];\n\n if (cookieName.endsWith(name)) {\n result = cookieValue;\n }\n });\n\n return result;\n};\n\nmodule.exports = { findCookie };\n"}],"filteredModules":3,"origins":[{"moduleId":0,"module":"/Users/ian/Development/chat-engine/setup/src/script.js","moduleIdentifier":"/Users/ian/Development/chat-engine/setup/src/script.js","moduleName":"./setup/src/script.js","loc":"","name":"main","reasons":[]}]}],"modules":[{"id":0,"identifier":"/Users/ian/Development/chat-engine/setup/src/script.js","name":"./setup/src/script.js","index":0,"index2":9,"size":3577,"cacheable":true,"built":true,"optional":false,"prefetched":false,"chunks":[0],"assets":[],"issuer":null,"issuerId":null,"issuerName":null,"profile":{"factory":4,"building":5},"failed":false,"errors":0,"warnings":0,"reasons":[],"usedExports":true,"providedExports":null,"optimizationBailout":[],"depth":0,"source":"// polyfill Promise\nrequire('es6-promise/auto');\n\nconst Client = require('./client');\nconst ProvisionAccount = require('./setup_account');\nconst utils = require('./utils');\n\n\nconst extractError = (err) => {\n if (err && err.responseJSON && err.responseJSON.error) {\n return err.responseJSON.error;\n }\n};\n\nmodule.exports = class {\n\n constructor() {\n this.loginElement = $('#login');\n this.provisionElement = $('#setup');\n this.loadElement = $('#load');\n this.errorElement = $('#error');\n this.errorOutElement = $('#error-out');\n this.statusElement = $('#status');\n this.codeElement = $('#code');\n this.outputElement = $('#output');\n this.emailElement = $('#email');\n this.passwordElement = $('#password');\n\n this.loginElement.submit(this.onLoginRegister.bind(this));\n this.provisionElement.submit(this.onSetup.bind(this));\n\n this.userId = utils.findCookie('pnAdminId');\n let tokenCookie = utils.findCookie('pnAdminToken');\n\n this.client = new Client({\n session: tokenCookie,\n debug: false,\n endpoint: 'https://admin.pubnub.com'\n });\n\n if (this.userId && tokenCookie) {\n this.provisionElement.show();\n this.loginElement.hide();\n analytics.identify(this.userId);\n }\n\n }\n\n displayStatus(statusText) {\n this.statusElement.show();\n this.statusElement.append($('
  • ' + statusText + '
  • '));\n }\n\n clearErrors() {\n this.errorElement.hide();\n }\n\n raiseError(err) {\n this.errorOutElement.html(err);\n this.errorElement.show();\n }\n\n onProvisionSuccess(err, data) {\n if (err) {\n this.loadElement.hide();\n this.provisionElement.show();\n\n this.errorOutElement.html(err);\n this.errorElement.show();\n } else {\n this.loadElement.hide();\n\n let output = '';\n output += '// Make sure to import ChatEngine first!\\n';\n output += 'ChatEngine = ChatEngineCore.create({\\n';\n output += \" publishKey: '\" + data.pub + \"',\\n\";\n output += \" subscribeKey: '\" + data.sub + \"'\\n\";\n output += '});\\n';\n\n analytics.track('chat_engine_activation');\n\n this.codeElement.text(output);\n this.outputElement.show();\n }\n }\n\n onLoginRegister() {\n this.clearErrors();\n const email = this.emailElement.val();\n const password = this.passwordElement.val();\n\n if (!email || email === '') {\n this.raiseError('email not valid');\n return false;\n }\n\n if (!password || password === '') {\n this.raiseError('password not valid');\n return false;\n }\n\n this.client.init({ email, password }, (err, response) => {\n if (err) {\n this.raiseError(extractError(err));\n } else {\n this.userId = response.result.user_id;\n analytics.identify(this.userId);\n this.provisionElement.show();\n this.loginElement.hide();\n }\n });\n\n\n return false;\n }\n\n onSetup() {\n this.clearErrors();\n\n this.loadElement.show();\n this.errorElement.hide();\n this.statusElement.empty();\n\n ProvisionAccount(this.client, this.userId, this.onProvisionSuccess.bind(this), this.displayStatus.bind(this));\n\n return false;\n }\n\n};\n"},{"id":4,"identifier":"/Users/ian/Development/chat-engine/node_modules/webpack/buildin/global.js","name":"(webpack)/buildin/global.js","index":4,"index2":1,"size":488,"cacheable":true,"built":true,"optional":false,"prefetched":false,"chunks":[0],"assets":[],"issuer":"/Users/ian/Development/chat-engine/node_modules/es6-promise/dist/es6-promise.js","issuerId":2,"issuerName":"./node_modules/es6-promise/dist/es6-promise.js","profile":{"factory":9,"building":9},"failed":false,"errors":0,"warnings":0,"reasons":[{"moduleId":2,"moduleIdentifier":"/Users/ian/Development/chat-engine/node_modules/es6-promise/dist/es6-promise.js","module":"./node_modules/es6-promise/dist/es6-promise.js","moduleName":"./node_modules/es6-promise/dist/es6-promise.js","type":"cjs require","userRequest":"global","loc":"1:0-44"}],"usedExports":true,"providedExports":null,"optimizationBailout":[],"depth":3,"source":"var g;\n\n// This works in non-strict mode\ng = (function() {\n\treturn this;\n})();\n\ntry {\n\t// This works if eval is allowed (see CSP)\n\tg = g || Function(\"return this\")() || (1,eval)(\"this\");\n} catch(e) {\n\t// This works if the window reference is available\n\tif(typeof window === \"object\")\n\t\tg = window;\n}\n\n// g can still be undefined, but nothing to do about it...\n// We return undefined, instead of nothing here, so it's\n// easier to handle this case. if(!global) { ...}\n\nmodule.exports = g;\n"},{"id":5,"identifier":"ignored /Users/ian/Development/chat-engine/node_modules/es6-promise/dist vertx","name":"vertx (ignored)","index":5,"index2":2,"size":15,"cacheable":true,"built":false,"optional":true,"prefetched":false,"chunks":[0],"assets":[],"issuer":"/Users/ian/Development/chat-engine/node_modules/es6-promise/dist/es6-promise.js","issuerId":2,"issuerName":"./node_modules/es6-promise/dist/es6-promise.js","profile":{"factory":2,"building":1},"failed":false,"errors":0,"warnings":0,"reasons":[{"moduleId":2,"moduleIdentifier":"/Users/ian/Development/chat-engine/node_modules/es6-promise/dist/es6-promise.js","module":"./node_modules/es6-promise/dist/es6-promise.js","moduleName":"./node_modules/es6-promise/dist/es6-promise.js","type":"cjs require","userRequest":"vertx","loc":"138:16-26"}],"usedExports":true,"providedExports":null,"optimizationBailout":[],"depth":3},{"id":6,"identifier":"/Users/ian/Development/chat-engine/setup/src/client.js","name":"./setup/src/client.js","index":6,"index2":5,"size":2922,"cacheable":true,"built":true,"optional":false,"prefetched":false,"chunks":[0],"assets":[],"issuer":"/Users/ian/Development/chat-engine/setup/src/script.js","issuerId":0,"issuerName":"./setup/src/script.js","profile":{"factory":9,"building":25},"failed":false,"errors":0,"warnings":0,"reasons":[{"moduleId":0,"moduleIdentifier":"/Users/ian/Development/chat-engine/setup/src/script.js","module":"./setup/src/script.js","moduleName":"./setup/src/script.js","type":"cjs require","userRequest":"./client","loc":"4:15-34"}],"usedExports":true,"providedExports":null,"optimizationBailout":[],"depth":1,"source":"module.exports = class {\n\n constructor(options) {\n options = options || {};\n\n this.endpoint = options.endpoint || 'https://admin.pubnub.com';\n this.session = options.session || false;\n this.debug = options.debug || false;\n }\n\n errHandle(text) {\n if (this.debug) {\n console.error('API Error: ' + text);\n }\n }\n\n clog(input) {\n if (this.debug) {\n if (typeof (input) === 'object') {\n console.log(input);\n } else {\n console.log('API:'.yellow, input);\n }\n }\n }\n\n request(method, url, opts, holla) {\n\n if (url[1] !== 'me' && !this.session) {\n return this.errHandle('Authorize with init() first.');\n }\n\n opts = opts || {};\n\n opts.url = this.endpoint + '/' + url.join('/');\n opts.method = method;\n\n opts.json = true;\n opts.headers = opts.headers || {};\n // opts.headers.Authorization =\n // 'Basic cHVibnViLWJldGE6YmxvY2tzMjAxNg===';\n\n if (this.session) {\n opts.headers['X-Session-Token'] = this.session;\n }\n\n // clog('-- URL:'.yellow);\n this.clog(opts.method.red + ' ' + opts.url);\n this.clog('-- opts:'.yellow);\n this.clog(opts);\n\n $.ajax(opts)\n .done((data) => {\n console.log(data);\n holla(null, data);\n })\n .fail((data) => {\n console.log('fail', data);\n holla(data || data.message || data);\n });\n }\n\n init(input, holla) {\n this.request('post', ['api', 'me'], {\n data: {\n email: input.email || this.errHandle('No Email Supplied'),\n password: input.password || this.errHandle('No Password Supplied')\n }\n }, (err, body) => {\n if (body && body.error) {\n holla(body.error);\n } else if (err) {\n holla(err);\n } else {\n this.session = body.result.token;\n holla(null, body);\n }\n });\n }\n\n /* shortcuts to avoid pollution of executors */\n startFunction({ block, key }, callback) {\n this.request('post', ['api', 'v1', 'blocks', 'key', key.id, 'block', block.id, 'start'], {\n data: {\n block_id: block.id,\n key_id: key.id,\n action: 'start'\n }\n }, callback);\n }\n\n storeSecretKey({ key }, callback) {\n this.request('put', ['api', 'vault', key.subscribe_key, 'key', 'secretKey'], {\n contentType: 'application/json',\n data: JSON.stringify({\n keyName: 'secretKey',\n key_id: key.id,\n subscribeKey: key.subscribe_key,\n value: key.secret_key\n })\n }, callback);\n }\n\n};\n"},{"id":7,"identifier":"/Users/ian/Development/chat-engine/setup/src/setup_account.js","name":"./setup/src/setup_account.js","index":7,"index2":7,"size":2800,"cacheable":true,"built":true,"optional":false,"prefetched":false,"chunks":[0],"assets":[],"issuer":"/Users/ian/Development/chat-engine/setup/src/script.js","issuerId":0,"issuerName":"./setup/src/script.js","profile":{"factory":9,"building":2},"failed":false,"errors":0,"warnings":0,"reasons":[{"moduleId":0,"moduleIdentifier":"/Users/ian/Development/chat-engine/setup/src/script.js","module":"./setup/src/script.js","moduleName":"./setup/src/script.js","type":"cjs require","userRequest":"./setup_account","loc":"5:25-51"}],"usedExports":true,"providedExports":null,"optimizationBailout":[],"depth":1,"source":"const ProvisionBlocks = require('./setup_blocks.js');\n\nmodule.exports = (api, userId, callback = () => {}, status = () => {}) => {\n api.request('get', ['api', 'accounts'], {\n data: {\n user_id: userId\n }\n }, (err, response) => {\n\n if (err) {\n return callback('Could not get PubNub accounts. Please contact support@pubnub.com.');\n }\n\n let account = response.result.accounts[0];\n\n status('Using account ' + account.properties.company + ', if this is incorrent deploy manually or log in as another user');\n status('Creating new PubNub app...');\n\n api.request('post', ['api', 'apps'], {\n data: {\n name: 'ChatEngine App',\n owner_id: account.id,\n properties: {}\n }\n }, (err, response) => {\n\n if (err) {\n return callback('Could not create new PubNub app. Please contact support@pubnub.com.');\n }\n\n let app = response.result;\n\n status('Getting PubNub keys...');\n\n api.request('get', ['api', 'apps'], {\n data: {\n owner_id: account.id\n }\n }, (err, response) => {\n\n if (err) {\n return callback('Could not get PubNub keys. Please contact support@pubnub.com.');\n }\n\n let apps = response.result;\n let key;\n\n apps.forEach((item) => {\n if (item.id === app.id) {\n key = item.keys[0];\n }\n });\n\n status('Enabling PubNub features...');\n\n key.properties.name = 'ChatEngine Keyset';\n key.properties.presence = 1;\n key.properties.history = 1;\n key.properties.message_storage_ttl = 7;\n key.properties.multiplexing = 1;\n key.properties.presence_announce_max = 20;\n key.properties.presence_debounce = 2;\n key.properties.presence_global_here_now = 1;\n key.properties.presence_interval = 10;\n key.properties.presence_leave_on_disconnect = 0;\n key.properties.blocks = 1;\n key.properties.uls = 1;\n key.properties.wildcardsubscribe = 1;\n\n api.request('put', ['api', 'keys', key.id], {\n data: key\n }, (err, response) => {\n\n if (err) {\n callback('Could not enable PubNub features. Please contact support@pubnub.com.');\n }\n\n ProvisionBlocks(api, userId, key, callback, status);\n\n });\n });\n });\n });\n};\n"},{"id":8,"identifier":"/Users/ian/Development/chat-engine/setup/src/setup_blocks.js","name":"./setup/src/setup_blocks.js","index":8,"index2":6,"size":4286,"cacheable":true,"built":true,"optional":false,"prefetched":false,"chunks":[0],"assets":[],"issuer":"/Users/ian/Development/chat-engine/setup/src/setup_account.js","issuerId":7,"issuerName":"./setup/src/setup_account.js","profile":{"factory":33,"building":10},"failed":false,"errors":0,"warnings":0,"reasons":[{"moduleId":7,"moduleIdentifier":"/Users/ian/Development/chat-engine/setup/src/setup_account.js","module":"./setup/src/setup_account.js","moduleName":"./setup/src/setup_account.js","type":"cjs require","userRequest":"./setup_blocks.js","loc":"1:24-52"}],"usedExports":true,"providedExports":null,"optimizationBailout":[],"depth":2,"source":"module.exports = (api, userId, key, callback = () => {}, status = () => {}) => {\n\n let block = null;\n\n status('Creating new PubNub Function...');\n\n let addSecretKeyToVault = () => {\n status('Adding Secret Key to Functions Vault...');\n\n api.storeSecretKey({ key }, (err) => {\n if (err) {\n callback('Could not add Secret Key to Functions Vault. Please contact support@pubnub.com');\n return;\n }\n\n status('Success!');\n\n callback(null, {\n pub: key.publish_key,\n sub: key.subscribe_key\n });\n });\n };\n\n let startPubNubFunction = () => {\n status('Starting Pubnub Function...');\n\n api.startFunction({ block, key }, (err) => {\n if (err) {\n callback('Could not start PubNub Function. Please contact support@pubnub.com.');\n return;\n }\n\n addSecretKeyToVault();\n });\n };\n\n let onCodeFetch = (stateCodeResult, authCodeResult, functionCodeResult) => {\n status('Creating new after-publish Event Handler...');\n\n api.request('post', ['api', 'v1', 'blocks', 'key', key.id, 'event_handler'], {\n data: {\n key_id: key.id,\n block_id: block.id,\n type: 'js',\n event: 'js-after-presence',\n channels: '*',\n name: 'chat-engine-state',\n code: stateCodeResult[0],\n output: 'output-state-to-kv-' + (new Date()).getTime()\n }\n }, (err, response) => {\n if (err) {\n callback('Could not create new PubNub after-publish Event Handler. Please contact support@pubnub.com.');\n }\n\n api.request('post', ['api', 'v1', 'blocks', 'key', key.id, 'event_handler'], {\n data: {\n key_id: key.id,\n block_id: block.id,\n type: 'js',\n event: 'js-on-rest',\n path: 'chat-engine-auth',\n name: 'chat-engine-auth',\n code: authCodeResult[0],\n output: 'auth-' + Math.round((new Date()).getTime())\n }\n }, (err, response) => {\n if (err) {\n callback('Could not create new PubNub after-publish Event Handler. Please contact support@pubnub.com.');\n }\n\n status('Creating new on-request Event Handler...');\n\n api.request('post', ['api', 'v1', 'blocks', 'key', key.id, 'event_handler'], {\n data: {\n key_id: key.id,\n block_id: block.id,\n code: functionCodeResult[0],\n type: 'js',\n name: 'chat-engine-server',\n path: 'chat-engine-server',\n event: 'js-on-rest',\n output: 'output-server-endpoint-' + Math.round((new Date()).getTime())\n }\n }, (err, response) => {\n if (err) {\n callback('Could not create new Pubnub on-request Event Handler. Please contact support@pubnub.com.');\n return;\n }\n\n startPubNubFunction();\n });\n });\n });\n };\n\n api.request('post', ['api', 'v1', 'blocks', 'key', key.id, 'block'], {\n data: {\n name: 'ChatEngine Function',\n key_id: key.id\n }\n }, (err, response) => {\n\n if (err) {\n callback('Could not create new PubNub Function. Please contact support@pubnub.com.');\n }\n\n block = response.payload;\n\n let stateCodeFetch = $.get({ url: 'functions/state-to-kv.js', dataType: 'text' });\n let authCodeFetch = $.get({ url: 'functions/auth.js', dataType: 'text' });\n let functionsCodeFetch = $.get({ url: 'functions/server.js', dataType: 'text' });\n\n $.when(stateCodeFetch, authCodeFetch, functionsCodeFetch)\n .then(onCodeFetch)\n .catch(() => {\n status('Failed to fetch code');\n });\n });\n};\n"},{"id":9,"identifier":"/Users/ian/Development/chat-engine/setup/src/utils.js","name":"./setup/src/utils.js","index":9,"index2":8,"size":382,"cacheable":true,"built":true,"optional":false,"prefetched":false,"chunks":[0],"assets":[],"issuer":"/Users/ian/Development/chat-engine/setup/src/script.js","issuerId":0,"issuerName":"./setup/src/script.js","profile":{"factory":9,"building":33},"failed":false,"errors":0,"warnings":0,"reasons":[{"moduleId":0,"moduleIdentifier":"/Users/ian/Development/chat-engine/setup/src/script.js","module":"./setup/src/script.js","moduleName":"./setup/src/script.js","type":"cjs require","userRequest":"./utils","loc":"6:14-32"}],"usedExports":true,"providedExports":null,"optimizationBailout":[],"depth":1,"source":"\nconst findCookie = (name) => {\n let cookies = document.cookie.split(';');\n let result = null;\n\n cookies.forEach((cookie) => {\n let cookieName = cookie.split('=')[0];\n let cookieValue = cookie.split('=')[1];\n\n if (cookieName.endsWith(name)) {\n result = cookieValue;\n }\n });\n\n return result;\n};\n\nmodule.exports = { findCookie };\n"}],"filteredModules":3,"children":[]} \ No newline at end of file